An open-source, faster Devin alternative
TypeScript
feat(awsvmlite): hibernate-as-suspend, customer idle timeouts, exec sessions, PTY and secret transport — the manager-side half of the surfaces the QEMU runtime already offered
Brian Reardon1454c51d9f5b
diff --git a/internal/awsvmlite/billing_test.go b/internal/awsvmlite/billing_test.gonew file mode 100644index 00000000..e51eff6a--- /dev/null+++ b/internal/awsvmlite/billing_test.go@@ -0,0 +1,141 @@+package awsvmlite++import (+ "context"+ "testing"+ "time"+)++// recordingObs captures the usage-metering boundaries the manager reports.+type recordingObs struct {+ destroyed []string+ hibernated []string+ woken []string+ memoryMB int+ cpuCount int+ startedAt time.Time+}++func (r *recordingObs) OnSandboxScale(string, int, int, time.Time) {}+func (r *recordingObs) OnSandboxDestroy(id string, memoryMB, cpuCount int, startedAt time.Time) {+ r.destroyed = append(r.destroyed, id)+ r.memoryMB, r.cpuCount, r.startedAt = memoryMB, cpuCount, startedAt+}+func (r *recordingObs) OnSandboxHibernate(id string, memoryMB, cpuCount int, startedAt time.Time) {+ r.hibernated = append(r.hibernated, id)+ r.memoryMB, r.cpuCount, r.startedAt = memoryMB, cpuCount, startedAt+}+func (r *recordingObs) OnSandboxWake(id string) { r.woken = append(r.woken, id) }++// Destroying a box must report the final billing slice, with the size and start+// time the sandbox actually ran at.+//+// The failure this prevents is silent and one-directional: the usage ticker+// samples every 20s and prices only what it sees, so a sandbox created and+// destroyed between two samples is never observed and bills EXACTLY NOTHING.+// Short-lived sandboxes are the normal shape of traffic on this runtime.+//+// It is asserted on Manager.Destroy rather than on any one caller because every+// path that kills a box goes through here — the customer's DELETE, the idle+// sweep, the shutdown drain, create-cleanup. An earlier version of this fix+// hooked a single caller and missed the customer's own delete entirely.+func TestDestroyReportsTheFinalBillingSlice(t *testing.T) {+ obs := &recordingObs{}+ m := New(nil, Config{})+ m.SetLifecycleObserver(obs)++ boundAt := time.Now().Add(-3 * time.Second)+ m.mu.Lock()+ m.bound["sb-flash"] = &Box{+ MicrovmID: "microvm-flash",+ Meta: Meta{MemoryMB: 4096, CPUCount: 1},+ boundAt: boundAt,+ }+ m.mu.Unlock()++ // nil client: Terminate will fail, and that must NOT swallow the billing —+ // the customer ran the sandbox whether or not the teardown call succeeds.+ func() {+ defer func() { _ = recover() }()+ _ = m.Destroy(context.Background(), "sb-flash")+ }()++ if len(obs.destroyed) != 1 || obs.destroyed[0] != "sb-flash" {+ t.Fatalf("destroy reported %v, want one slice for sb-flash — a sandbox "++ "that lived under one tick interval would bill nothing", obs.destroyed)+ }+ if obs.memoryMB != 4096 || obs.cpuCount != 1 {+ t.Errorf("slice priced at %dMB/%dcpu, want the delivered 4096MB/1cpu",+ obs.memoryMB, obs.cpuCount)+ }+ if !obs.startedAt.Equal(boundAt) {+ t.Errorf("slice measured from %s, want the bind time %s", obs.startedAt, boundAt)+ }+}++// Destroying a sandbox this manager does not hold must bill nothing: there is+// no size to price a slice at, and inventing one invents a charge.+func TestDestroyOfAnUnheldSandboxBillsNothing(t *testing.T) {+ obs := &recordingObs{}+ m := New(nil, Config{})+ m.SetLifecycleObserver(obs)++ if err := m.Destroy(context.Background(), "sb-never-existed"); err != nil {+ t.Fatalf("Destroy of an unheld sandbox errored: %v", err)+ }+ if len(obs.destroyed) != 0 {+ t.Fatalf("billed a sandbox that was never held: %v", obs.destroyed)+ }+}++// A destroyed sandbox's host must stay resolvable briefly, or its closing usage+// tick cannot be attributed and is thrown away.+//+// The event publisher stamps each tick with a worker_id resolved from this+// manager, and events-ingest discards any tick whose worker_id disagrees with+// the sandbox's row. The closing tick is emitted during Destroy and drained a+// beat later, so a live-only lookup misses, the publisher falls back to a+// generic id, and the tick is dropped as coming from a non-owner worker — the+// last slice of every destroyed sandbox, unbilled, for that reason alone.+func TestDestroyedSandboxStaysAttributableForItsClosingTick(t *testing.T) {+ m := New(nil, Config{})+ m.mu.Lock()+ m.bound["sb-1"] = &Box{MicrovmID: "microvm-1", Meta: Meta{MemoryMB: 4096, CPUCount: 1}}+ m.mu.Unlock()++ if id, ok := m.WorkerIDFor("sb-1"); !ok || id != "microvm-1" {+ t.Fatalf("live sandbox resolved to (%q,%v), want microvm-1", id, ok)+ }++ func() {+ defer func() { _ = recover() }() // nil client: Terminate panics, billing already happened+ _ = m.Destroy(context.Background(), "sb-1")+ }()++ // Routing must NOT see it — a destroyed sandbox is unreachable.+ if _, ok := m.BoxFor("sb-1"); ok {+ t.Error("BoxFor still resolves a destroyed sandbox — it would look routable")+ }+ // Attribution must.+ if id, ok := m.WorkerIDFor("sb-1"); !ok || id != "microvm-1" {+ t.Fatalf("destroyed sandbox resolved to (%q,%v) — its closing tick would be "++ "stamped with a fallback id and discarded as non-owner", id, ok)+ }++ // And it must not be remembered forever.+ m.mu.Lock()+ m.lastBox["sb-1"] = lastBoxEntry{microvmID: "microvm-1", at: time.Now().Add(-2 * lastBoxRetention)}+ m.mu.Unlock()+ if _, ok := m.WorkerIDFor("sb-1"); ok {+ t.Error("a long-expired entry still resolves — the map would grow without bound")+ }+}++// A sandbox this manager never held resolves to nothing, so a stray tick cannot+// borrow another sandbox's identity.+func TestWorkerIDForUnknownSandboxResolvesToNothing(t *testing.T) {+ m := New(nil, Config{})+ if id, ok := m.WorkerIDFor("sb-never"); ok {+ t.Fatalf("unknown sandbox resolved to %q", id)+ }+}diff --git a/internal/awsvmlite/execsession.go b/internal/awsvmlite/execsession.gonew file mode 100644index 00000000..a8e4d9d4--- /dev/null+++ b/internal/awsvmlite/execsession.go@@ -0,0 +1,148 @@+package awsvmlite++// execsession.go — long-running commands with a live output stream.+//+// /oc/run answers one command in one request, which is the right shape for+// almost everything a sandbox is asked to do and the wrong shape for anything+// a customer wants to watch: a dev server, a build, a training run. A session+// starts a process, keeps it alive across disconnects, and streams output to+// whoever is attached.+//+// Same construction as pty.go: unary calls over plain JSON, one WebSocket per+// attached client opened on demand and closed on detach, and the gRPC stream+// living entirely inside the guest. Nothing here is on the create or exec hot+// path.++import (+ "context"+ "fmt"+ "net/http"+ "net/url"+ "strconv"+ "time"++ "github.com/gorilla/websocket"+)++const (+ ocExecCreatePath = "/oc/exec/create"+ ocExecAttachPath = "/oc/exec/attach"+ ocExecListPath = "/oc/exec/list"+ ocExecKillPath = "/oc/exec/kill"+ ocExecResultPath = "/oc/exec/result"+)++// ExecSessionRequest starts or addresses a session. Mirrors the guest's shape.+type ExecSessionRequest struct {+ SessionID string `json:"sessionId,omitempty"`+ Command string `json:"cmd,omitempty"`+ Args []string `json:"args,omitempty"`+ Env map[string]string `json:"envs,omitempty"`+ Cwd string `json:"cwd,omitempty"`+ TimeoutSec int32 `json:"timeoutSec,omitempty"`+ MaxRunAfterDisconnect int32 `json:"maxRunAfterDisconnect,omitempty"`+ Signal int32 `json:"signal,omitempty"`+}++// ExecSessionInfo is one session in a listing.+type ExecSessionInfo struct {+ SessionID string `json:"sessionId"`+ Command string `json:"command"`+ Args []string `json:"args"`+ Running bool `json:"running"`+ ExitCode int32 `json:"exitCode"`+ StartedAt int64 `json:"startedAt"`+ AttachedClients int `json:"attachedClients"`+}++// ExecSessionResult is a session's output so far, without attaching.+type ExecSessionResult struct {+ Running bool `json:"running"`+ ExitCode *int32 `json:"exitCode,omitempty"`+ Stdout []byte `json:"stdout,omitempty"`+ Stderr []byte `json:"stderr,omitempty"`+}++func (m *Manager) ExecSessionCreate(ctx context.Context, sandboxID string, req ExecSessionRequest) (string, error) {+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()+ var out struct {+ SessionID string `json:"sessionId"`+ }+ if err := m.call(ctx, sandboxID, http.MethodPost, ocExecCreatePath, req, &out); err != nil {+ return "", err+ }+ return out.SessionID, nil+}++func (m *Manager) ExecSessionList(ctx context.Context, sandboxID string) ([]ExecSessionInfo, error) {+ ctx, cancel := context.WithTimeout(ctx, 20*time.Second)+ defer cancel()+ var out struct {+ Sessions []ExecSessionInfo `json:"sessions"`+ }+ if err := m.call(ctx, sandboxID, http.MethodGet, ocExecListPath, nil, &out); err != nil {+ return nil, err+ }+ return out.Sessions, nil+}++func (m *Manager) ExecSessionKill(ctx context.Context, sandboxID, sessionID string, signal int32) error {+ ctx, cancel := context.WithTimeout(ctx, 20*time.Second)+ defer cancel()+ return m.call(ctx, sandboxID, http.MethodPost, ocExecKillPath,+ ExecSessionRequest{SessionID: sessionID, Signal: signal}, nil)+}++// ExecSessionGetResult reports a session's output so far.+//+// The guest synthesises this from the agent's scrollback rather than from a+// buffer the control plane keeps — see the handler for why the SCROLLBACK_END+// marker is what makes it terminate instead of hanging on a quiet process.+func (m *Manager) ExecSessionGetResult(ctx context.Context, sandboxID, sessionID string) (*ExecSessionResult, error) {+ ctx, cancel := context.WithTimeout(ctx, 45*time.Second)+ defer cancel()+ var out ExecSessionResult+ path := ocExecResultPath + "?sessionId=" + url.QueryEscape(sessionID)+ if err := m.call(ctx, sandboxID, http.MethodGet, path, nil, &out); err != nil {+ return nil, err+ }+ return &out, nil+}++// DialExecSession opens the WebSocket carrying one attached client.+//+// The caller owns the connection and must close it — closing is what detaches+// the client inside the guest. A detach does NOT kill the session: it outlives+// its clients by design, which is the whole point of a session as opposed to a+// run.+func (m *Manager) DialExecSession(ctx context.Context, sandboxID, sessionID string) (*websocket.Conn, error) {+ b, ok := m.BoxFor(sandboxID)+ if !ok {+ return nil, fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)+ }+ u := url.URL{+ Scheme: "wss",+ Host: hostOnly(b.Endpoint),+ Path: ocExecAttachPath,+ RawQuery: "sessionId=" + url.QueryEscape(sessionID),+ }+ dialer := &websocket.Dialer{+ HandshakeTimeout: ptyDialTimeout,+ ReadBufferSize: 32 * 1024,+ WriteBufferSize: 32 * 1024,+ }+ hdr := http.Header{}+ hdr.Set("X-aws-proxy-auth", m.token(ctx, b))+ hdr.Set("X-aws-proxy-port", strconv.FormatInt(int64(b.Port), 10))++ conn, resp, err := dialer.DialContext(ctx, u.String(), hdr)+ if err != nil {+ if resp != nil {+ return nil, fmt.Errorf("awsvmlite: dial exec session %s: %w (http %d)", sandboxID, err, resp.StatusCode)+ }+ return nil, fmt.Errorf("awsvmlite: dial exec session %s: %w", sandboxID, err)+ }+ m.stampTouch(b)+ return conn, nil+}diff --git a/internal/awsvmlite/hibernate.go b/internal/awsvmlite/hibernate.gonew file mode 100644index 00000000..f702a69e--- /dev/null+++ b/internal/awsvmlite/hibernate.go@@ -0,0 +1,225 @@+package awsvmlite++// hibernate.go — parking a sandbox by suspending its box.+//+// The agent path hibernates by EXPORTING the workspace to blob storage and then+// suspending, which makes the archive the durable copy and the suspended box a+// disposable latency cache. That design exists because it needs to be able to+// terminate the box: a suspended box holds regional memory quota, and quota is+// what caps warm-pool depth.+//+// This path has no file transfer on its hot side and does not want one here+// either, so hibernation is the suspend alone:+//+// hibernate SuspendMicrovm — memory and disk snapshotted, compute unbilled+// wake the next request auto-resumes; Resume just pays it earlier+//+// WHAT THIS BUYS: the customer stops paying for an idle sandbox, and the wake is+// a resume (~1s) rather than a restore. WHAT IT DOES NOT BUY: longevity. AWS+// counts RUNNING and SUSPENDED time together against the 8h service cap, so a+// suspended sandbox still dies on the same schedule — hibernation defers cost,+// not death.+//+// AND THE COST: because there is no archive, the box can never be terminated to+// reclaim its quota. A suspended sandbox holds a slot in the regional memory+// quota for as long as it exists, and that quota is the ceiling on how deep the+// warm pool can be. Parking is therefore not free to the fleet even though it+// is free to the customer, which is why suspendedCap exists below.++import (+ "context"+ "fmt"+ "log"+ "net/http"+ "time"+)++// defaultSuspendedCap bounds how many sandboxes may sit suspended at once.+//+// OURS, NOT AWS'S. There is no service limit on suspended microvms; this is a+// guard we impose on the quota that funds the warm pool. Every suspended box is+// a box the pool cannot have, and unlike the agent path — which exports an+// archive first and can therefore terminate the box — there is nothing here+// that would let one be reclaimed. A parked sandbox holds its slot until the 8h+// cap kills it.+//+// The arithmetic it is drawn from: the regional quota is expressed in gigabytes+// (1024 by default, adjustable), and a box costs its image's delivered size+// regardless of what the create asked for. At the default 4096 MB that is+// 1024/4 = 256 boxes for the whole cell, against a prod pool target of 150. So+// 64 is roughly a quarter of the fleet, chosen to leave the pool intact rather+// than measured against real hibernate demand — which nobody has yet, because+// this is the first release that can hibernate at all.+//+// Past the cap, hibernate is REFUSED and the sandbox keeps running. That costs+// the customer money and is the right way round: the alternative, letting+// parked sandboxes quietly eat the pool, turns into cold launches for every+// customer on the cell and is far harder to diagnose.+const defaultSuspendedCap = 64++// suspendedCap reports the effective cap. Tunable per deployment for the same+// reason OPENSANDBOX_MICROVM_MAX_TOTAL_BOXES is: the quota it protects is a+// property of the account and region, not of this code.+func (m *Manager) suspendedCap() int {+ if m.cfg.SuspendedCap > 0 {+ return m.cfg.SuspendedCap+ }+ return defaultSuspendedCap+}++// Hibernate suspends the box behind a sandbox.+//+// Returns no archive key: there is no archive. The caller records the+// hibernation against the sandbox row, and the box itself holds the state.+func (m *Manager) Hibernate(ctx context.Context, sandboxID string) error {+ b, ok := m.BoxFor(sandboxID)+ if !ok {+ return fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)+ }++ m.mu.Lock()+ if _, already := m.suspended[sandboxID]; already {+ m.mu.Unlock()+ // Idempotent: a retried hibernate must not fail, and must not issue a+ // second SuspendMicrovm against a box that is already parked.+ return nil+ }+ if cap := m.suspendedCap(); len(m.suspended) >= cap {+ n := len(m.suspended)+ m.mu.Unlock()+ return fmt.Errorf("awsvmlite: %d sandboxes are already suspended (cap %d): "++ "suspended boxes hold regional memory quota and cannot be reclaimed", n, cap)+ }+ // Marked BEFORE the AWS call, not after. The touch loop auto-resumes any box+ // it probes, so a box that is suspended while still unmarked would be woken+ // by the very next tick — the hibernation would appear to succeed and then+ // silently undo itself, with the customer billed throughout.+ if m.suspended == nil {+ m.suspended = map[string]time.Time{}+ }+ m.suspended[sandboxID] = time.Now()+ m.mu.Unlock()++ // Bill the slice before parking. Once suspended the sandbox reports as+ // unbillable (see SandboxManager.IsSandboxAlive) and the ticker stops+ // sampling it, so anything since the last sample has to be taken now.+ m.mu.Lock()+ obs := m.lifecycleObs+ m.mu.Unlock()+ if obs != nil {+ obs.OnSandboxHibernate(sandboxID, b.Meta.MemoryMB, b.Meta.CPUCount, b.boundAt)+ }+ if err := m.client.Suspend(ctx, b.MicrovmID); err != nil {+ // Unmark, or the sandbox is treated as parked — excluded from billing+ // and from the touch loop — while actually running.+ m.mu.Lock()+ delete(m.suspended, sandboxID)+ m.mu.Unlock()+ return err+ }+ log.Printf("awsvmlite: hibernated %s (box %s) — suspended, %d/%d parked",+ sandboxID, b.MicrovmID, len(m.suspended), m.suspendedCap())+ return nil+}++// Wake resumes a suspended sandbox.+//+// The explicit Resume is optional in principle — Lambda holds an inbound+// request while it restores, so the next exec would resume the box on its own —+// but it is issued anyway so that a wake reports its own success. Relying on+// auto-resume would mean the API returned 200 for a wake it never verified, and+// a box that failed to restore would surface as a mysteriously slow exec+// minutes later instead.+func (m *Manager) Wake(ctx context.Context, sandboxID string) error {+ b, ok := m.BoxFor(sandboxID)+ if !ok {+ return fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)+ }+ if err := m.client.Resume(ctx, b.MicrovmID); err != nil {+ return err+ }+ // Resume only ASKS the provider to restore the host; the guest is not+ // serving the moment it returns. Waking and immediately using the sandbox+ // is the normal shape of the request, and without this wait the customer's+ // first call lands on a box that is still restoring and gets a 502 — a wake+ // that reports success and then does not work.+ if err := m.waitGuestReady(ctx, b); err != nil {+ // Unmarking anyway: the host IS resumed, so leaving it flagged as+ // parked would exclude it from billing and let the touch loop treat it+ // as stock. Report the error so the caller does not claim readiness.+ m.mu.Lock()+ delete(m.suspended, sandboxID)+ m.mu.Unlock()+ return fmt.Errorf("awsvmlite: woke %s but it did not become ready: %w", sandboxID, err)+ }+ m.mu.Lock()+ delete(m.suspended, sandboxID)+ // Count the resume as a touch. Otherwise the box is immediately due for one+ // and pays a probe it does not need.+ b.lastTouch = time.Now()+ obs := m.lifecycleObs+ m.mu.Unlock()+ // Restart the billing interval at the wake rather than letting the next+ // sample measure from before the sandbox was parked.+ if obs != nil {+ obs.OnSandboxWake(sandboxID)+ }+ log.Printf("awsvmlite: woke %s (box %s)", sandboxID, b.MicrovmID)+ return nil+}++// IsHibernated reports whether a sandbox is parked.+//+// Load-bearing in two places that both fail silently: billing (a suspended box+// still reports Alive() to AWS, so metering has to be told separately) and the+// touch loop (a probe auto-resumes what it touches).+func (m *Manager) IsHibernated(sandboxID string) bool {+ m.mu.Lock()+ defer m.mu.Unlock()+ _, ok := m.suspended[sandboxID]+ return ok+}++// SuspendedCount reports how many sandboxes are parked, for the admin view.+func (m *Manager) SuspendedCount() int {+ m.mu.Lock()+ defer m.mu.Unlock()+ return len(m.suspended)+}++// waitGuestReady polls the guest's health endpoint until it answers or the+// configured ready timeout elapses.+//+// The same probe the keep-warm loop uses, for the same reason it exists: it is+// served by the in-guest front door, so a 200 means the thing that actually+// handles customer requests is up — not merely that the provider says the host+// is RUNNING.+func (m *Manager) waitGuestReady(ctx context.Context, b *Box) error {+ timeout := m.cfg.ReadyTimeout+ if timeout <= 0 {+ timeout = 30 * time.Second+ }+ deadline := time.Now().Add(timeout)+ var lastErr error+ for attempt := 0; time.Now().Before(deadline); attempt++ {+ resp, err := m.do(ctx, b, http.MethodGet, healthPath, nil)+ if err == nil {+ _ = resp.Body.Close()+ if resp.StatusCode < 400 {+ return nil+ }+ lastErr = fmt.Errorf("health returned %d", resp.StatusCode)+ } else {+ lastErr = err+ }+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(250 * time.Millisecond):+ }+ }+ if lastErr == nil {+ lastErr = fmt.Errorf("timed out after %s", timeout)+ }+ return lastErr+}diff --git a/internal/awsvmlite/hibernate_test.go b/internal/awsvmlite/hibernate_test.gonew file mode 100644index 00000000..7670fe02--- /dev/null+++ b/internal/awsvmlite/hibernate_test.go@@ -0,0 +1,134 @@+package awsvmlite++import (+ "context"+ "errors"+ "testing"+ "time"+)++// hibernate_test.go — the two ways parking a sandbox fails silently.+//+// Both were found by reading rather than by a failure, and neither would show+// up in a smoke test: the sandbox looks hibernated, the API returns 200, and+// the damage is either a bill the customer did not expect or a warm pool that+// quietly stops filling.++// newParkedManager returns a Manager holding one bound sandbox, with the+// suspended set pre-populated. Constructed directly rather than through New so+// no AWS client is needed.+func newParkedManager(parked ...string) *Manager {+ m := &Manager{+ cfg: Config{TouchInterval: time.Minute},+ bound: map[string]*Box{},+ suspended: map[string]time.Time{},+ }+ m.bound["sbx-awake"] = &Box{MicrovmID: "mvm-awake"}+ for _, id := range parked {+ m.bound[id] = &Box{MicrovmID: "mvm-" + id}+ m.suspended[id] = time.Now()+ }+ return m+}++// The touch loop must skip parked sandboxes. Lambda auto-resumes a suspended+// box on ANY inbound request, so a probe would wake it within one tick — the+// hibernation undoes itself and the customer is billed throughout.+func TestTouchNeverProbesAParkedSandbox(t *testing.T) {+ m := newParkedManager("sbx-parked")++ // Everything is due: a zero lastTouch is past any interval.+ m.mu.Lock()+ var due []string+ for id, b := range m.bound {+ if _, parked := m.suspended[id]; parked {+ continue+ }+ if b.lastTouch.IsZero() || time.Since(b.lastTouch) >= m.cfg.TouchInterval {+ due = append(due, id)+ }+ }+ m.mu.Unlock()++ for _, id := range due {+ if id == "sbx-parked" {+ t.Fatal("a parked sandbox was scheduled for a touch — the probe would auto-resume it and silently un-hibernate the sandbox")+ }+ }+ if len(due) != 1 || due[0] != "sbx-awake" {+ t.Errorf("due = %v, want only the awake sandbox", due)+ }+}++// Billing asks IsSandboxAlive, and AWS says a SUSPENDED box is alive. If that+// answer reaches the usage ticker, a parked sandbox meters at the full rate+// forever while the product tells the customer it is hibernated.+func TestParkedSandboxIsNotAliveForBilling(t *testing.T) {+ m := newParkedManager("sbx-parked")+ sm := NewSandboxManager(m)++ alive, err := sm.IsSandboxAlive(context.Background(), "sbx-parked")+ if err != nil {+ t.Fatalf("IsSandboxAlive: %v", err)+ }+ if alive {+ t.Fatal("a hibernated sandbox reported alive — the usage ticker would keep billing it at the full rate")+ }+}++func TestIsHibernatedTracksTheSet(t *testing.T) {+ m := newParkedManager("sbx-parked")+ if !m.IsHibernated("sbx-parked") {+ t.Error("parked sandbox not reported hibernated")+ }+ if m.IsHibernated("sbx-awake") {+ t.Error("running sandbox reported hibernated")+ }+ if got := m.SuspendedCount(); got != 1 {+ t.Errorf("SuspendedCount = %d, want 1", got)+ }+}++// The cap is a guard on the quota that funds the warm pool, so it must refuse+// rather than park. A suspended box can never be reclaimed — there is no+// archive to restore from — so letting parked sandboxes past the cap turns into+// cold launches for every customer on the cell.+func TestHibernateRefusesPastTheCap(t *testing.T) {+ m := &Manager{bound: map[string]*Box{}, suspended: map[string]time.Time{}}+ for i := 0; i < defaultSuspendedCap; i++ {+ id := "filler-" + string(rune('a'+i%26)) + string(rune('a'+i/26))+ m.suspended[id] = time.Now()+ }+ m.bound["sbx-one-too-many"] = &Box{MicrovmID: "mvm-x"}++ err := m.Hibernate(context.Background(), "sbx-one-too-many")+ if err == nil {+ t.Fatal("hibernate past the cap succeeded — parked boxes would eat the quota the warm pool needs")+ }+ if m.IsHibernated("sbx-one-too-many") {+ t.Error("a refused hibernate still marked the sandbox parked")+ }+}++// A retried hibernate must not issue a second suspend, and must not fail.+func TestHibernateIsIdempotent(t *testing.T) {+ m := newParkedManager("sbx-parked")+ if err := m.Hibernate(context.Background(), "sbx-parked"); err != nil {+ t.Fatalf("re-hibernating a parked sandbox failed: %v", err)+ }+ if got := m.SuspendedCount(); got != 1 {+ t.Errorf("SuspendedCount = %d after a retry, want 1", got)+ }+}++// An unbound sandbox is refused before anything is marked.+func TestHibernateUnknownSandbox(t *testing.T) {+ m := newParkedManager()+ err := m.Hibernate(context.Background(), "sbx-nope")+ if err == nil {+ t.Fatal("hibernated a sandbox this process holds no box for")+ }+ if !errors.Is(err, err) || m.SuspendedCount() != 0 {+ t.Errorf("SuspendedCount = %d, want 0", m.SuspendedCount())+ }+}diff --git a/internal/awsvmlite/idle.go b/internal/awsvmlite/idle.gonew file mode 100644index 00000000..ec931e3d--- /dev/null+++ b/internal/awsvmlite/idle.go@@ -0,0 +1,142 @@+package awsvmlite++import (+ "fmt"+ "log"+ "time"+)++// idle.go — the customer-settable idle timeout.+//+// A sandbox that has gone unused for its timeout is PARKED, not destroyed:+// hibernate is suspend on this runtime, which stops the meter while keeping the+// disk, and the customer can wake it. That matches the QEMU fleet, where the+// same timeout drives auto-hibernate rather than a kill, so a customer moving+// between runtimes sees one behaviour.+//+// Two things make this runtime different, and both are visible below:+//+// - The keepalive already pokes every box on a timer to stop the provider+// suspending idle stock. Driving an idle policy off that clock would find+// every sandbox permanently busy. Hence lastUsed, stamped only by customer+// traffic, distinct from lastTouch.+//+// - The provider destroys every host at a hard cap regardless of anything we+// do. A timeout longer than the time remaining to that cap cannot be+// honoured, so it is refused rather than silently stored — see+// SetIdleTimeout.++// Coarse on+// purpose: this decides when to stop billing, not when to answer a request, and+// each pass may issue a suspend per expired sandbox against a rate-limited API.+// IdleSweepInterval is how often the control plane collects expired sandboxes.+const IdleSweepInterval = 30 * time.Second++// MarkUsed records customer activity against a sandbox, refreshing its idle+// timeout. Cheap and called on every customer-facing operation; a sandbox this+// process does not hold is silently ignored.+func (m *Manager) MarkUsed(sandboxID string) {+ if m == nil {+ return+ }+ m.mu.Lock()+ if b, ok := m.bound[sandboxID]; ok {+ b.lastUsed = time.Now()+ }+ m.mu.Unlock()+}++// SetIdleTimeout sets how long a sandbox may sit unused before being parked,+// and reports the timeout actually in force.+//+// d <= 0 clears it: the sandbox runs until killed or until the provider's cap+// ends it.+//+// A timeout at or beyond the host's remaining life is NOT stored, and the+// returned duration is zero to say so. The provider terminates the host at its+// cap whatever we do, so accepting a longer timeout would be a promise this+// runtime cannot keep — the sandbox would vanish at the cap while the API+// claimed it had hours left. Refusing is the honest answer, and the row's+// end_at already tells the customer when the host actually dies.+func (m *Manager) SetIdleTimeout(sandboxID string, d time.Duration) (time.Duration, error) {+ if m == nil {+ return 0, fmt.Errorf("awsvmlite: manager unavailable")+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ b, ok := m.bound[sandboxID]+ if !ok {+ return 0, fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)+ }+ if d <= 0 {+ b.idleTimeout = 0+ b.lastUsed = time.Now()+ return 0, nil+ }+ // Measured against the host's OWN remaining life, not a fixed 8h: a box+ // claimed off the warm set was launched earlier, so it has less than a full+ // cap left, and the honest ceiling is per sandbox.+ if m.client != nil {+ if deadline := m.client.Config().Deadline(b.launchedAt); !deadline.IsZero() {+ if remaining := time.Until(deadline); d >= remaining {+ b.idleTimeout = 0+ b.lastUsed = time.Now()+ log.Printf("awsvmlite: %s: idle timeout %s ignored — the host is destroyed at its cap in %s regardless",+ sandboxID, d, remaining.Truncate(time.Second))+ return 0, nil+ }+ }+ }+ b.idleTimeout = d+ b.lastUsed = time.Now()+ return d, nil+}++// IdleTimeout reports the timeout in force for a sandbox, zero for none.+func (m *Manager) IdleTimeout(sandboxID string) time.Duration {+ if m == nil {+ return 0+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ if b, ok := m.bound[sandboxID]; ok {+ return b.idleTimeout+ }+ return 0+}++// ExpiredIdle lists sandboxes whose idle timeout has elapsed.+//+// Exported because this manager deliberately does NOT park them itself. Parking+// is as much a database transition as a provider call — the row has to move to+// hibernated AND a hibernation record has to exist, or wake answers "no active+// hibernation found" and the sandbox is stranded parked forever. Only the+// control-plane backend can do that, so it owns the sweep and this reports what+// is due. See liteBackend.StartIdleSweeper.+//+// Snapshotted under the lock and acted on outside it: parking a sandbox issues+// a provider call, and holding the manager's mutex across that would stall+// every claim and route on the cell behind a rate-limited API.+func (m *Manager) ExpiredIdle(now time.Time) []string {+ m.mu.Lock()+ defer m.mu.Unlock()+ var out []string+ for id, b := range m.bound {+ if b.idleTimeout <= 0 {+ continue+ }+ if _, parked := m.suspended[id]; parked {+ continue // already parked; nothing to collect+ }+ // A sandbox that has never been used measures from when it was bound,+ // so a create followed by silence still expires.+ since := b.lastUsed+ if since.IsZero() {+ since = b.boundAt+ }+ if now.Sub(since) >= b.idleTimeout {+ out = append(out, id)+ }+ }+ return out+}diff --git a/internal/awsvmlite/idle_test.go b/internal/awsvmlite/idle_test.gonew file mode 100644index 00000000..dc22d426--- /dev/null+++ b/internal/awsvmlite/idle_test.go@@ -0,0 +1,146 @@+package awsvmlite++import (+ "testing"+ "time"++ "github.com/opensandbox/opensandbox/internal/awsvm"+)++func idleTestManager(t *testing.T) *Manager {+ t.Helper()+ return New(awsvm.NewClientWithAPI(nil, awsvm.Config{ImageIdentifier: "arn:image"}), Config{})+}++// bindBox puts a sandbox in the bound map with a chosen launch time.+func bindBox(m *Manager, sandboxID string, launchedAt time.Time) *Box {+ b := &Box{+ MicrovmID: "microvm-" + sandboxID,+ Meta: Meta{MemoryMB: 4096, CPUCount: 1},+ launchedAt: launchedAt,+ boundAt: time.Now(),+ }+ m.mu.Lock()+ m.bound[sandboxID] = b+ m.mu.Unlock()+ return b+}++// THE defining rule: the keepalive must not look like the customer.+//+// Warm and bound boxes are poked on a timer so the provider does not suspend+// them. If the idle policy read that clock, every sandbox would appear busy+// forever and no timeout would ever fire — the timeout would be accepted by the+// API and silently do nothing, which is worse than refusing it.+func TestKeepaliveTouchDoesNotCountAsCustomerActivity(t *testing.T) {+ m := idleTestManager(t)+ b := bindBox(m, "sb-1", time.Now())+ if _, err := m.SetIdleTimeout("sb-1", time.Minute); err != nil {+ t.Fatalf("SetIdleTimeout: %v", err)+ }++ // Age the sandbox past its timeout, then let the keepalive poke it.+ m.mu.Lock()+ b.lastUsed = time.Now().Add(-5 * time.Minute)+ b.lastTouch = time.Now()+ m.mu.Unlock()++ if got := m.ExpiredIdle(time.Now()); len(got) != 1 {+ t.Fatalf("keepalive touch kept an idle sandbox alive (expired=%v) — no timeout would ever fire", got)+ }++ // Real customer activity DOES refresh it.+ m.MarkUsed("sb-1")+ if got := m.ExpiredIdle(time.Now()); len(got) != 0 {+ t.Fatalf("customer activity did not refresh the timeout (expired=%v)", got)+ }+}++// A timeout longer than the host has left is refused, not stored.+//+// The provider destroys every host at a hard cap. Accepting a longer timeout+// would have the API claim the sandbox has hours left while it vanishes at the+// cap — a promise this runtime cannot keep. Zero back means "nothing running".+func TestTimeoutBeyondTheHostsRemainingLifeIsRefused(t *testing.T) {+ m := idleTestManager(t)+ // Launched 7h ago against the 8h cap: roughly one hour left.+ bindBox(m, "sb-old", time.Now().Add(-7*time.Hour))++ got, err := m.SetIdleTimeout("sb-old", 4*time.Hour)+ if err != nil {+ t.Fatalf("SetIdleTimeout: %v", err)+ }+ if got != 0 {+ t.Fatalf("accepted a %s timeout on a host with ~1h left (got %s) — the sandbox "++ "would disappear at the cap while the API claimed it was alive", 4*time.Hour, got)+ }+ if running := m.IdleTimeout("sb-old"); running != 0 {+ t.Fatalf("a refused timeout was still stored: %s", running)+ }++ // Comfortably inside the remaining life: honoured exactly.+ got, err = m.SetIdleTimeout("sb-old", 10*time.Minute)+ if err != nil {+ t.Fatalf("SetIdleTimeout: %v", err)+ }+ if got != 10*time.Minute {+ t.Fatalf("a timeout inside the host's life was not honoured: got %s", got)+ }+}++// Zero clears the timeout — the documented "persistent" case, matching QEMU.+func TestZeroTimeoutMeansPersistent(t *testing.T) {+ m := idleTestManager(t)+ bindBox(m, "sb-2", time.Now())+ if _, err := m.SetIdleTimeout("sb-2", time.Minute); err != nil {+ t.Fatalf("SetIdleTimeout: %v", err)+ }+ if _, err := m.SetIdleTimeout("sb-2", 0); err != nil {+ t.Fatalf("SetIdleTimeout(0): %v", err)+ }+ m.mu.Lock()+ m.bound["sb-2"].lastUsed = time.Now().Add(-24 * time.Hour)+ m.mu.Unlock()+ if got := m.ExpiredIdle(time.Now()); len(got) != 0 {+ t.Fatalf("a persistent sandbox expired anyway: %v", got)+ }+}++// A sandbox created and never touched still expires — measured from its bind+// time, so silence after create is not immunity.+func TestNeverUsedSandboxExpiresFromItsBindTime(t *testing.T) {+ m := idleTestManager(t)+ b := bindBox(m, "sb-3", time.Now())+ if _, err := m.SetIdleTimeout("sb-3", time.Minute); err != nil {+ t.Fatalf("SetIdleTimeout: %v", err)+ }+ m.mu.Lock()+ b.lastUsed = time.Time{} // never used+ b.boundAt = time.Now().Add(-5 * time.Minute)+ m.mu.Unlock()++ if got := m.ExpiredIdle(time.Now()); len(got) != 1 {+ t.Fatalf("a never-used sandbox did not expire (%v) — silence after create would run to the cap", got)+ }+}++// An already-parked sandbox is not collected again: it is not billing, and a+// second suspend against a rate-limited API buys nothing.+func TestAlreadyParkedSandboxIsNotCollectedAgain(t *testing.T) {+ m := idleTestManager(t)+ b := bindBox(m, "sb-4", time.Now())+ if _, err := m.SetIdleTimeout("sb-4", time.Minute); err != nil {+ t.Fatalf("SetIdleTimeout: %v", err)+ }+ m.mu.Lock()+ b.lastUsed = time.Now().Add(-time.Hour)+ if m.suspended == nil {+ m.suspended = map[string]time.Time{}+ }+ m.suspended["sb-4"] = time.Now()+ m.mu.Unlock()++ if got := m.ExpiredIdle(time.Now()); len(got) != 0 {+ t.Fatalf("a parked sandbox was collected again: %v", got)+ }+}diff --git a/internal/awsvmlite/pty.go b/internal/awsvmlite/pty.gonew file mode 100644index 00000000..0fa4fa65--- /dev/null+++ b/internal/awsvmlite/pty.go@@ -0,0 +1,121 @@+package awsvmlite++// pty.go — interactive terminals, on a data plane that has no persistent+// connection.+//+// The tunnel this needs already exists on every box: handleAgentTunnel splices+// a WebSocket to the agent's gRPC listener, and it works through the proxy.+// What made it a liability on the agent path was that it was ALWAYS ON — one+// pre-dialed channel per box, keepalives, a re-dial ladder, and a Durable+// Object holding sockets open, decaying whether or not anybody was attached.+//+// Here it is opened only when a customer attaches a terminal and closed when+// they detach. A box with no terminal open has no socket, nothing to keep+// alive, and nothing to re-dial — so create and exec are untouched, which is+// the property this whole backend exists to protect.+//+// And the gRPC stream itself never leaves the guest: the customer's side of+// this socket carries a small JSON frame format (see cmd/microvm-hooks/+// oc_stream.go), which the guest translates. So the proxy's trailer stripping —+// the reason gRPC cannot cross it — never comes into play.++import (+ "context"+ "fmt"+ "net/http"+ "net/url"+ "strconv"+ "time"++ "github.com/gorilla/websocket"+)++const (+ ocPTYCreatePath = "/oc/pty/create"+ ocPTYAttachPath = "/oc/pty/attach"+ ocPTYResizePath = "/oc/pty/resize"+ ocPTYKillPath = "/oc/pty/kill"+)++// PTYRequest is the body of the unary PTY calls, matching the guest's shape.+type PTYRequest struct {+ SessionID string `json:"sessionId,omitempty"`+ Cols int32 `json:"cols,omitempty"`+ Rows int32 `json:"rows,omitempty"`+ Shell string `json:"shell,omitempty"`+}++// PTYCreate starts a terminal and returns its session id.+func (m *Manager) PTYCreate(ctx context.Context, sandboxID string, req PTYRequest) (string, error) {+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()+ var out struct {+ SessionID string `json:"sessionId"`+ }+ if err := m.call(ctx, sandboxID, http.MethodPost, ocPTYCreatePath, req, &out); err != nil {+ return "", err+ }+ return out.SessionID, nil+}++// PTYResize tells the terminal its new dimensions. Out of band, because a+// resize has to reach the PTY even when the customer is not typing — a terminal+// that cannot be resized renders every full-screen program wrong.+func (m *Manager) PTYResize(ctx context.Context, sandboxID, sessionID string, cols, rows int32) error {+ ctx, cancel := context.WithTimeout(ctx, 15*time.Second)+ defer cancel()+ return m.call(ctx, sandboxID, http.MethodPost, ocPTYResizePath,+ PTYRequest{SessionID: sessionID, Cols: cols, Rows: rows}, nil)+}++// PTYKill ends a terminal.+func (m *Manager) PTYKill(ctx context.Context, sandboxID, sessionID string) error {+ ctx, cancel := context.WithTimeout(ctx, 15*time.Second)+ defer cancel()+ return m.call(ctx, sandboxID, http.MethodPost, ocPTYKillPath,+ PTYRequest{SessionID: sessionID}, nil)+}++// ptyDialTimeout bounds the handshake to the box. Only the handshake — the+// socket it returns has no deadline, because a terminal is idle most of the+// time and a read deadline would close it under a customer who stopped typing.+const ptyDialTimeout = 20 * time.Second++// DialPTY opens the WebSocket carrying one terminal session.+//+// The caller owns the returned connection and must close it; closing it is what+// releases the gRPC stream inside the guest, so a caller that leaks this leaks+// a PTY on the box too.+func (m *Manager) DialPTY(ctx context.Context, sandboxID, sessionID string) (*websocket.Conn, error) {+ b, ok := m.BoxFor(sandboxID)+ if !ok {+ return nil, fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)+ }+ u := url.URL{+ Scheme: "wss",+ Host: hostOnly(b.Endpoint),+ Path: ocPTYAttachPath,+ RawQuery: "sessionId=" + url.QueryEscape(sessionID),+ }+ dialer := &websocket.Dialer{+ HandshakeTimeout: ptyDialTimeout,+ ReadBufferSize: 32 * 1024,+ WriteBufferSize: 32 * 1024,+ }+ hdr := http.Header{}+ hdr.Set("X-aws-proxy-auth", m.token(ctx, b))+ hdr.Set("X-aws-proxy-port", strconv.FormatInt(int64(b.Port), 10))++ conn, resp, err := dialer.DialContext(ctx, u.String(), hdr)+ if err != nil {+ // The status is worth reporting: the proxy answers 403 for a bad token+ // and 502 for a box that is gone, and those want very different+ // responses from the caller.+ if resp != nil {+ return nil, fmt.Errorf("awsvmlite: dial pty %s: %w (http %d)", sandboxID, err, resp.StatusCode)+ }+ return nil, fmt.Errorf("awsvmlite: dial pty %s: %w", sandboxID, err)+ }+ m.stampTouch(b)+ return conn, nil+}diff --git a/internal/awsvmlite/secrets.go b/internal/awsvmlite/secrets.gonew file mode 100644index 00000000..937f3df8--- /dev/null+++ b/internal/awsvmlite/secrets.go@@ -0,0 +1,87 @@+package awsvmlite++// secrets.go — handing a sandbox its secrets.+//+// The REAL values go to the box. That is the design, not an oversight: the+// substitution has to happen somewhere the sandbox cannot read, and on this+// runtime the only such place is the guest's own root process — there is no+// worker to put it on. See cmd/microvm-hooks/oc_secrets.go for why that beats a+// shared in-region service, and for the honest account of where it is weaker+// than the QEMU fleet.+//+// What crosses this wire is protected the same way every other call to the box+// is: the platform's authenticated proxy, terminating in a root process the+// customer's unprivileged code cannot read. What comes back OUT toward the+// customer is sealed.++import (+ "context"+ "net/http"+ "time"++ "github.com/opensandbox/opensandbox/pkg/types"+)++const (+ ocSecrets = "/oc/secrets"+ ocSecretsUpdate = "/oc/secrets/update"+)++// secretsPayload mirrors the guest's handler, which in turn mirrors+// secretsproxy.CreateSealedEnvs.+type secretsPayload struct {+ SandboxID string `json:"sandboxId"`+ PlaintextEnvs map[string]string `json:"envs,omitempty"`+ SecretEnvs map[string]string `json:"secretEnvs,omitempty"`+ Allowlist []string `json:"allowlist,omitempty"`+ SecretAllowedHosts map[string][]string `json:"secretAllowedHosts,omitempty"`+}++// HasSecrets reports whether a config needs the secrets path at all.+//+// This is the hot-path gate. A create with no secrets — every pooled create the+// benchmark makes — must not pay for any of this, so the caller asks here+// first rather than sending an empty request.+//+// An allowlist with no secrets still counts: it is an egress restriction the+// proxy has to enforce, and skipping it would leave the sandbox unrestricted+// while the API reported the store applied.+func HasSecrets(cfg types.SandboxConfig) bool {+ return len(cfg.SecretEnvs) > 0 || len(cfg.EgressAllowlist) > 0 || len(cfg.SecretAllowedHosts) > 0+}++// SetSecrets seals the sandbox's secrets in the guest and applies the resulting+// environment.+//+// Carries the plaintext envs too, because the guest merges both into ONE+// environment. Sending them separately through SetEnvs afterwards would+// overwrite the sealed values with an environment that has none of them.+func (m *Manager) SetSecrets(ctx context.Context, sandboxID string, cfg types.SandboxConfig) error {+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()+ return m.call(ctx, sandboxID, http.MethodPost, ocSecrets, secretsPayload{+ SandboxID: sandboxID,+ PlaintextEnvs: cfg.Envs,+ SecretEnvs: cfg.SecretEnvs,+ Allowlist: cfg.EgressAllowlist,+ SecretAllowedHosts: cfg.SecretAllowedHosts,+ }, nil)+}++// UpdateSecret refreshes one secret's value without re-sealing it.+//+// Reports whether a session and name matched. False is a MISS, not a failure:+// the refresh flow sweeps every sandbox in an org and most of them will not+// hold the secret being rotated.+func (m *Manager) UpdateSecret(ctx context.Context, sandboxID, name, value string) (bool, error) {+ ctx, cancel := context.WithTimeout(ctx, 20*time.Second)+ defer cancel()+ var out struct {+ Updated bool `json:"updated"`+ }+ body := map[string]string{"sandboxId": sandboxID, "name": name, "value": value}+ if err := m.call(ctx, sandboxID, http.MethodPost, ocSecretsUpdate, body, &out); err != nil {+ return false, err+ }+ return out.Updated, nil+}