Skip to content

An open-source, faster Devin alternative

TypeScript

router

Brian Reardonf8b83bbf357f
diff --git a/cmd/server/main.go b/cmd/server/main.go
index cc2e0f94..8f2b3f0d 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -130,16 +130,32 @@ func main() {
} else {
opts.CheckpointStore = checkpointStore
log.Printf("opensandbox: S3 checkpoint store configured (bucket=%s, region=%s)", cfg.S3Bucket, cfg.S3Region)
+ }
+ }
- // Enable hibernate-on-timeout in combined mode
- if mgr != nil {
- mgr.SetCheckpointStore(checkpointStore)
- mgr.SetOnHibernate(func(sandboxID string, result *sandbox.HibernateResult) {
- log.Printf("opensandbox: sandbox %s auto-hibernated (key=%s, size=%d bytes)",
- sandboxID, result.CheckpointKey, result.SizeBytes)
- })
- }
+ // Initialize SandboxRouter for rolling timeouts, auto-wake, and command routing
+ if mgr != nil {
+ workerID := cfg.WorkerID
+ if workerID == "" {
+ workerID = "w-local-1"
}
+ sbRouter := sandbox.NewSandboxRouter(sandbox.RouterConfig{
+ Manager: mgr,
+ CheckpointStore: opts.CheckpointStore,
+ Store: opts.Store,
+ WorkerID: workerID,
+ OnHibernate: func(sandboxID string, result *sandbox.HibernateResult) {
+ log.Printf("opensandbox: sandbox %s auto-hibernated (key=%s, size=%d bytes)",
+ sandboxID, result.CheckpointKey, result.SizeBytes)
+ // Update PG session status if store is available
+ if opts.Store != nil {
+ _ = opts.Store.UpdateSandboxSessionStatus(context.Background(), sandboxID, "hibernated", nil)
+ }
+ },
+ })
+ defer sbRouter.Close()
+ opts.Router = sbRouter
+ log.Println("opensandbox: sandbox router initialized (rolling timeouts, auto-wake)")
}
// Initialize Redis worker registry in server mode
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 9003497e..8b28b9a7 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -73,14 +73,20 @@ func main() {
log.Fatalf("failed to initialize checkpoint store: %v", err)
}
log.Printf("opensandbox-worker: S3 checkpoint store configured (bucket=%s, region=%s)", cfg.S3Bucket, cfg.S3Region)
+ }
- // Enable hibernate-on-timeout
- mgr.SetCheckpointStore(checkpointStore)
- mgr.SetOnHibernate(func(sandboxID string, result *sandbox.HibernateResult) {
+ // Initialize SandboxRouter for rolling timeouts, auto-wake, and command routing
+ sbRouter := sandbox.NewSandboxRouter(sandbox.RouterConfig{
+ Manager: mgr,
+ CheckpointStore: checkpointStore,
+ WorkerID: cfg.WorkerID,
+ OnHibernate: func(sandboxID string, result *sandbox.HibernateResult) {
log.Printf("opensandbox-worker: sandbox %s auto-hibernated (key=%s, size=%d bytes)",
sandboxID, result.CheckpointKey, result.SizeBytes)
- })
- }
+ },
+ })
+ defer sbRouter.Close()
+ log.Println("opensandbox-worker: sandbox router initialized (rolling timeouts, auto-wake)")
// Start Prometheus metrics server on :9091
metricsSrv := metrics.StartMetricsServer(":9091")
@@ -88,7 +94,7 @@ func main() {
log.Println("opensandbox-worker: metrics server started on :9091")
// Start gRPC server for control plane communication
- grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr, checkpointStore)
+ grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr, checkpointStore, sbRouter)
grpcAddr := ":9090"
log.Printf("opensandbox-worker: starting gRPC server on %s", grpcAddr)
go func() {
diff --git a/internal/api/commands.go b/internal/api/commands.go
index 3023bcca..54fb7da9 100644
--- a/internal/api/commands.go
+++ b/internal/api/commands.go
@@ -1,6 +1,7 @@
package api
import (
+ "context"
"net/http"
"time"
@@ -28,16 +29,33 @@ func (s *Server) runCommand(c echo.Context) error {
})
}
+ var result *types.ProcessResult
+ var execErr error
+
start := time.Now()
- result, err := s.manager.Exec(c.Request().Context(), id, cfg)
- durationMs := int(time.Since(start).Milliseconds())
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
+ routeOp := func(ctx context.Context) error {
+ result, execErr = s.manager.Exec(ctx, id, cfg)
+ return execErr
}
+ // Route through sandbox router (handles auto-wake, rolling timeout reset)
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "exec", routeOp); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ } else {
+ if err := routeOp(c.Request().Context()); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ }
+
+ durationMs := int(time.Since(start).Milliseconds())
+
// Log command to per-sandbox SQLite
if s.sandboxDBs != nil {
sdb, dbErr := s.sandboxDBs.Get(id)
diff --git a/internal/api/filesystem.go b/internal/api/filesystem.go
index 41d2b515..7964f883 100644
--- a/internal/api/filesystem.go
+++ b/internal/api/filesystem.go
@@ -1,10 +1,12 @@
package api
import (
+ "context"
"io"
"net/http"
"github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/pkg/types"
)
func (s *Server) readFile(c echo.Context) error {
@@ -20,11 +22,26 @@ func (s *Server) readFile(c echo.Context) error {
})
}
- content, err := s.manager.ReadFile(c.Request().Context(), id, path)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
+ var content string
+
+ routeOp := func(ctx context.Context) error {
+ var err error
+ content, err = s.manager.ReadFile(ctx, id, path)
+ return err
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "readFile", routeOp); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ } else {
+ if err := routeOp(c.Request().Context()); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
}
return c.String(http.StatusOK, content)
@@ -50,10 +67,22 @@ func (s *Server) writeFile(c echo.Context) error {
})
}
- if err := s.manager.WriteFile(c.Request().Context(), id, path, string(body)); err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
+ routeOp := func(ctx context.Context) error {
+ return s.manager.WriteFile(ctx, id, path, string(body))
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "writeFile", routeOp); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ } else {
+ if err := routeOp(c.Request().Context()); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
}
return c.NoContent(http.StatusNoContent)
@@ -70,11 +99,26 @@ func (s *Server) listDir(c echo.Context) error {
path = "/"
}
- entries, err := s.manager.ListDir(c.Request().Context(), id, path)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
+ var entries []types.EntryInfo
+
+ routeOp := func(ctx context.Context) error {
+ var err error
+ entries, err = s.manager.ListDir(ctx, id, path)
+ return err
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "listDir", routeOp); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ } else {
+ if err := routeOp(c.Request().Context()); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
}
return c.JSON(http.StatusOK, entries)
@@ -93,10 +137,22 @@ func (s *Server) makeDir(c echo.Context) error {
})
}
- if err := s.manager.MakeDir(c.Request().Context(), id, path); err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
+ routeOp := func(ctx context.Context) error {
+ return s.manager.MakeDir(ctx, id, path)
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "makeDir", routeOp); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ } else {
+ if err := routeOp(c.Request().Context()); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
}
return c.NoContent(http.StatusNoContent)
@@ -115,10 +171,22 @@ func (s *Server) removeFile(c echo.Context) error {
})
}
- if err := s.manager.Remove(c.Request().Context(), id, path); err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
+ routeOp := func(ctx context.Context) error {
+ return s.manager.Remove(ctx, id, path)
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "removeFile", routeOp); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ } else {
+ if err := routeOp(c.Request().Context()); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
}
return c.NoContent(http.StatusNoContent)
diff --git a/internal/api/pty.go b/internal/api/pty.go
index e7a5445c..f1a42ada 100644
--- a/internal/api/pty.go
+++ b/internal/api/pty.go
@@ -1,11 +1,13 @@
package api
import (
+ "context"
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/pkg/types"
)
@@ -31,11 +33,27 @@ func (s *Server) createPTY(c echo.Context) error {
})
}
- session, err := s.ptyManager.CreateSession(id, req)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
+ var session *sandbox.PTYSessionHandle
+
+ routeOp := func(_ context.Context) error {
+ var err error
+ session, err = s.ptyManager.CreateSession(id, req)
+ return err
+ }
+
+ // Route through sandbox router (handles auto-wake, rolling timeout reset)
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "createPTY", routeOp); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ } else {
+ if err := routeOp(c.Request().Context()); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
}
return c.JSON(http.StatusCreated, types.PTYSession{
@@ -49,8 +67,14 @@ func (s *Server) ptyWebSocket(c echo.Context) error {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
+ id := c.Param("id")
sessionID := c.Param("sessionID")
+ // Touch the router on initial WebSocket connection to reset timeout
+ if s.router != nil {
+ s.router.Touch(id)
+ }
+
session, err := s.ptyManager.GetSession(sessionID)
if err != nil {
return c.JSON(http.StatusNotFound, map[string]string{
@@ -82,7 +106,7 @@ func (s *Server) ptyWebSocket(c echo.Context) error {
}
}()
- // Read from WebSocket -> write to PTY
+ // Read from WebSocket -> write to PTY (with router touch on activity)
go func() {
for {
_, msg, err := ws.ReadMessage()
@@ -92,6 +116,10 @@ func (s *Server) ptyWebSocket(c echo.Context) error {
if _, err := session.PTY.Write(msg); err != nil {
return
}
+ // Touch on every WebSocket message to keep sandbox alive
+ if s.router != nil {
+ s.router.Touch(id)
+ }
}
}()
@@ -114,14 +142,27 @@ func (s *Server) killPTY(c echo.Context) error {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
+ id := c.Param("id")
sessionID := c.Param("sessionID")
- if err := s.ptyManager.KillSession(sessionID); err != nil {
- return c.JSON(http.StatusNotFound, map[string]string{
- "error": err.Error(),
- })
+ routeOp := func(_ context.Context) error {
+ return s.ptyManager.KillSession(sessionID)
+ }
+
+ // Route through sandbox router
+ if s.router != nil {
+ if err := s.router.Route(c.Request().Context(), id, "killPTY", routeOp); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{
+ "error": err.Error(),
+ })
+ }
+ } else {
+ if err := routeOp(c.Request().Context()); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{
+ "error": err.Error(),
+ })
+ }
}
return c.NoContent(http.StatusNoContent)
}
-
diff --git a/internal/api/router.go b/internal/api/router.go
index d9208c1c..6434648b 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -25,6 +25,7 @@ var errSandboxNotAvailable = map[string]string{
type Server struct {
echo *echo.Echo
manager *sandbox.Manager
+ router *sandbox.SandboxRouter // routes all sandbox interactions (state machine, auto-wake, rolling timeout)
ptyManager *sandbox.PTYManager
templates *templateDeps
store *db.Store // nil in combined/dev mode without PG
@@ -48,6 +49,7 @@ type ServerOpts struct {
Region string
HTTPAddr string
SandboxDBs *sandbox.SandboxDBManager
+ Router *sandbox.SandboxRouter // nil in server-only mode
WorkOSConfig *auth.WorkOSConfig // nil if WorkOS not configured
WorkerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
CheckpointStore *storage.CheckpointStore // nil if hibernation not configured
@@ -73,6 +75,7 @@ func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string,
s.region = opts.Region
s.httpAddr = opts.HTTPAddr
s.sandboxDBs = opts.SandboxDBs
+ s.router = opts.Router
s.workerRegistry = opts.WorkerRegistry
s.checkpointStore = opts.CheckpointStore
}
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 078ef6b2..8d953471 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -54,6 +54,15 @@ func (s *Server) createSandbox(c echo.Context) error {
})
}
+ // Register with sandbox router for rolling timeout tracking
+ if s.router != nil {
+ timeout := cfg.Timeout
+ if timeout <= 0 {
+ timeout = 300
+ }
+ s.router.Register(sb.ID, time.Duration(timeout)*time.Second)
+ }
+
// Initialize per-sandbox SQLite if available
if s.sandboxDBs != nil {
sdb, err := s.sandboxDBs.Get(sb.ID)
@@ -279,6 +288,11 @@ func (s *Server) killSandbox(c echo.Context) error {
})
}
+ // Unregister from sandbox router
+ if s.router != nil {
+ s.router.Unregister(id)
+ }
+
if s.store != nil {
_ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), id, "stopped", nil)
}
@@ -410,7 +424,7 @@ func (s *Server) setTimeout(c echo.Context) error {
})
}
- if s.manager == nil {
+ if s.router == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
@@ -429,11 +443,7 @@ func (s *Server) setTimeout(c echo.Context) error {
})
}
- if err := s.manager.SetTimeout(c.Request().Context(), id, req.Timeout); err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
- }
+ s.router.SetTimeout(id, time.Duration(req.Timeout)*time.Second)
return c.NoContent(http.StatusNoContent)
}
@@ -461,6 +471,12 @@ func (s *Server) hibernateSandbox(c echo.Context) error {
})
}
+ // Mark hibernated in sandbox router
+ if s.router != nil {
+ timeout := 600 // default for explicit hibernate
+ s.router.MarkHibernated(id, time.Duration(timeout)*time.Second)
+ }
+
// Record checkpoint in PG
orgID, hasOrg := auth.GetOrgID(c)
if s.store != nil && hasOrg {
@@ -576,6 +592,15 @@ func (s *Server) wakeSandbox(c echo.Context) error {
})
}
+ // Register with sandbox router after explicit wake
+ if s.router != nil {
+ timeout := req.Timeout
+ if timeout <= 0 {
+ timeout = 300
+ }
+ s.router.Register(id, time.Duration(timeout)*time.Second)
+ }
+
_ = s.store.MarkCheckpointRestored(ctx, id)
_ = s.store.UpdateSandboxSessionForWake(ctx, id, s.workerID)
diff --git a/internal/sandbox/hibernate.go b/internal/sandbox/hibernate.go
index 6c6eacd1..8ba193af 100644
--- a/internal/sandbox/hibernate.go
+++ b/internal/sandbox/hibernate.go
@@ -60,7 +60,7 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointSto
}
// 4. Remove the container (checkpoint --export already stopped it)
- m.cancelTimeout(sandboxID)
+ // Note: timer management now lives in SandboxRouter (caller handles MarkHibernated)
_ = m.podman.RemoveContainer(ctx, name, true)
return &HibernateResult{
@@ -87,13 +87,7 @@ func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey stri
return nil, fmt.Errorf("failed to restore sandbox %s: %w", sandboxID, err)
}
- // 3. Schedule new timeout
- if timeout <= 0 {
- timeout = defaultTimeout
- }
- m.scheduleTimeout(sandboxID, name, time.Duration(timeout)*time.Second)
-
- // 4. Get sandbox info
+ // 3. Get sandbox info (timer management now lives in SandboxRouter; caller handles Register)
info, err := m.podman.InspectContainer(ctx, name)
if err != nil {
return nil, fmt.Errorf("failed to inspect restored sandbox %s: %w", sandboxID, err)
diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.go
index b2e71479..1b3c7ace 100644
--- a/internal/sandbox/manager.go
+++ b/internal/sandbox/manager.go
@@ -3,14 +3,11 @@ package sandbox
import (
"context"
"fmt"
- "log"
"strconv"
- "sync"
"time"
"github.com/google/uuid"
"github.com/opensandbox/opensandbox/internal/podman"
- "github.com/opensandbox/opensandbox/internal/storage"
"github.com/opensandbox/opensandbox/pkg/types"
)
@@ -28,34 +25,19 @@ const (
defaultCPU = 1
)
-// Manager handles sandbox lifecycle operations.
+// Manager handles sandbox lifecycle operations (pure container executor).
+// Timer management and state machine logic live in SandboxRouter.
type Manager struct {
- podman *podman.Client
- mu sync.RWMutex
- timers map[string]*time.Timer // sandbox ID -> timeout timer
- checkpointStore *storage.CheckpointStore // nil if hibernation not configured
- onHibernate func(string, *HibernateResult) // callback after successful hibernate
+ podman *podman.Client
}
// NewManager creates a new sandbox manager.
func NewManager(client *podman.Client) *Manager {
return &Manager{
podman: client,
- timers: make(map[string]*time.Timer),
}
}
-// SetCheckpointStore configures the checkpoint store for hibernation support.
-// When set, sandboxes hibernate instead of being killed on timeout.
-func (m *Manager) SetCheckpointStore(store *storage.CheckpointStore) {
- m.checkpointStore = store
-}
-
-// SetOnHibernate sets a callback invoked after successful hibernation.
-func (m *Manager) SetOnHibernate(fn func(sandboxID string, result *HibernateResult)) {
- m.onHibernate = fn
-}
-
// Create creates a new sandbox container and starts it.
func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {
id := uuid.New().String()[:8]
@@ -125,8 +107,6 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
MemoryMB: memoryMB,
}
- m.scheduleTimeout(id, name, time.Duration(timeout)*time.Second)
-
return sandbox, nil
}
@@ -143,7 +123,6 @@ func (m *Manager) Get(ctx context.Context, id string) (*types.Sandbox, error) {
// Kill forcefully removes a sandbox.
func (m *Manager) Kill(ctx context.Context, id string) error {
name := fmt.Sprintf("%s-%s", containerName, id)
- m.cancelTimeout(id)
if err := m.podman.RemoveContainer(ctx, name, true); err != nil {
return fmt.Errorf("failed to kill sandbox %s: %w", id, err)
}
@@ -173,82 +152,13 @@ func (m *Manager) Count(ctx context.Context) (int, error) {
return len(entries), nil
}
-// SetTimeout updates the timeout for a running sandbox.
-func (m *Manager) SetTimeout(ctx context.Context, id string, timeoutSec int) error {
- name := fmt.Sprintf("%s-%s", containerName, id)
-
- // Verify sandbox exists and is running
- info, err := m.podman.InspectContainer(ctx, name)
- if err != nil {
- return fmt.Errorf("sandbox %s not found: %w", id, err)
- }
- if !info.State.Running {
- return fmt.Errorf("sandbox %s is not running", id)
- }
-
- m.scheduleTimeout(id, name, time.Duration(timeoutSec)*time.Second)
- return nil
-}
-
// ContainerName returns the podman container name for a sandbox ID.
func (m *Manager) ContainerName(id string) string {
return fmt.Sprintf("%s-%s", containerName, id)
}
-// Close cancels all timeout timers.
-func (m *Manager) Close() {
- m.mu.Lock()
- defer m.mu.Unlock()
- for _, timer := range m.timers {
- timer.Stop()
- }
- m.timers = make(map[string]*time.Timer)
-}
-
-func (m *Manager) scheduleTimeout(id, name string, d time.Duration) {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- if existing, ok := m.timers[id]; ok {
- existing.Stop()
- }
-
- m.timers[id] = time.AfterFunc(d, func() {
- // If checkpoint store is configured, hibernate instead of kill
- if m.checkpointStore != nil {
- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
- defer cancel()
-
- result, err := m.Hibernate(ctx, id, m.checkpointStore)
- if err != nil {
- log.Printf("manager: hibernate failed for %s, falling back to kill: %v", id, err)
- _ = m.podman.RemoveContainer(ctx, name, true)
- } else {
- log.Printf("manager: sandbox %s hibernated (key=%s, size=%d)", id, result.CheckpointKey, result.SizeBytes)
- if m.onHibernate != nil {
- m.onHibernate(id, result)
- }
- }
- } else {
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
- _ = m.podman.RemoveContainer(ctx, name, true)
- }
-
- m.mu.Lock()
- delete(m.timers, id)
- m.mu.Unlock()
- })
-}
-
-func (m *Manager) cancelTimeout(id string) {
- m.mu.Lock()
- defer m.mu.Unlock()
- if timer, ok := m.timers[id]; ok {
- timer.Stop()
- delete(m.timers, id)
- }
-}
+// Close is a no-op — timer management now lives in SandboxRouter.
+func (m *Manager) Close() {}
func resolveTemplateImage(template string) string {
switch template {
diff --git a/internal/sandbox/router.go b/internal/sandbox/router.go
new file mode 100644
index 00000000..a2942c0a
--- /dev/null
+++ b/internal/sandbox/router.go
@@ -0,0 +1,487 @@
+package sandbox
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/storage"
+)
+
+// SandboxState represents the lifecycle state of a sandbox from the router's perspective.
+type SandboxState int
+
+const (
+ StateRunning SandboxState = iota
+ StateHibernated
+ StateWaking
+)
+
+func (s SandboxState) String() string {
+ switch s {
+ case StateRunning:
+ return "running"
+ case StateHibernated:
+ return "hibernated"
+ case StateWaking:
+ return "waking"
+ default:
+ return "unknown"
+ }
+}
+
+// sandboxEntry holds per-sandbox routing state.
+type sandboxEntry struct {
+ mu sync.Mutex
+ state SandboxState
+ timeout time.Duration // configured rolling timeout duration
+ timer *time.Timer // rolling timeout timer (nil if hibernated)
+ wakeCh chan struct{} // closed when wake completes; nil if not waking
+ wakeErr error // set if wake failed
+}
+
+// Middleware wraps a routed operation. It receives the sandbox ID, the operation
+// name (e.g., "exec", "readFile"), and the next function to call. It can
+// short-circuit, augment, or observe the operation.
+type Middleware func(ctx context.Context, sandboxID string, op string, next func(ctx context.Context) error) error
+
+// RouterConfig holds configuration for the SandboxRouter.
+type RouterConfig struct {
+ Manager *Manager
+ CheckpointStore *storage.CheckpointStore // nil disables auto-wake/hibernate
+ Store *db.Store // nil disables DB lookups for wake
+ WorkerID string
+ DefaultTimeout time.Duration
+ OnHibernate func(sandboxID string, result *HibernateResult)
+}
+
+// SandboxRouter routes sandbox interactions through a state machine,
+// managing rolling timeouts, auto-wake, and command queueing.
+// Every sandbox interaction (exec, file ops, PTY) flows through Route(),
+// which ensures the sandbox is running, executes the operation, and
+// resets the rolling idle timeout.
+type SandboxRouter struct {
+ manager *Manager
+ checkpointStore *storage.CheckpointStore
+ store *db.Store
+ workerID string
+ defaultTimeout time.Duration
+ onHibernate func(sandboxID string, result *HibernateResult)
+
+ mu sync.RWMutex
+ sandboxes map[string]*sandboxEntry
+
+ middlewares []Middleware
+}
+
+// NewSandboxRouter creates a new sandbox router.
+func NewSandboxRouter(cfg RouterConfig) *SandboxRouter {
+ dt := cfg.DefaultTimeout
+ if dt == 0 {
+ dt = 300 * time.Second
+ }
+ return &SandboxRouter{
+ manager: cfg.Manager,
+ checkpointStore: cfg.CheckpointStore,
+ store: cfg.Store,
+ workerID: cfg.WorkerID,
+ defaultTimeout: dt,
+ onHibernate: cfg.OnHibernate,
+ sandboxes: make(map[string]*sandboxEntry),
+ }
+}
+
+// Use registers middleware that wraps every routed operation.
+// Middleware is applied in the order registered (first registered = outermost).
+func (r *SandboxRouter) Use(mw Middleware) {
+ r.middlewares = append(r.middlewares, mw)
+}
+
+// Register is called when a sandbox is created or explicitly woken,
+// to begin tracking it with a rolling timeout.
+func (r *SandboxRouter) Register(sandboxID string, timeout time.Duration) {
+ if timeout <= 0 {
+ timeout = r.defaultTimeout
+ }
+
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ // Stop existing timer if re-registering
+ if existing, ok := r.sandboxes[sandboxID]; ok {
+ existing.mu.Lock()
+ if existing.timer != nil {
+ existing.timer.Stop()
+ }
+ existing.mu.Unlock()
+ }
+
+ entry := &sandboxEntry{
+ state: StateRunning,
+ timeout: timeout,
+ }
+ entry.timer = time.AfterFunc(timeout, func() {
+ r.onTimeout(sandboxID)
+ })
+ r.sandboxes[sandboxID] = entry
+}
+
+// Unregister removes a sandbox from the router (called on kill/destroy).
+func (r *SandboxRouter) Unregister(sandboxID string) {
+ r.mu.Lock()
+ entry, ok := r.sandboxes[sandboxID]
+ if ok {
+ delete(r.sandboxes, sandboxID)
+ }
+ r.mu.Unlock()
+
+ if ok {
+ entry.mu.Lock()
+ if entry.timer != nil {
+ entry.timer.Stop()
+ }
+ entry.mu.Unlock()
+ }
+}
+
+// MarkHibernated transitions a sandbox to the hibernated state.
+// Called after a successful explicit or timeout-triggered hibernate.
+func (r *SandboxRouter) MarkHibernated(sandboxID string, timeout time.Duration) {
+ if timeout <= 0 {
+ timeout = r.defaultTimeout
+ }
+
+ r.mu.Lock()
+ entry, ok := r.sandboxes[sandboxID]
+ if !ok {
+ // Create entry in hibernated state for auto-wake
+ entry = &sandboxEntry{
+ state: StateHibernated,
+ timeout: timeout,
+ }
+ r.sandboxes[sandboxID] = entry
+ r.mu.Unlock()
+ return
+ }
+ r.mu.Unlock()
+
+ entry.mu.Lock()
+ defer entry.mu.Unlock()
+ if entry.timer != nil {
+ entry.timer.Stop()
+ entry.timer = nil
+ }
+ entry.state = StateHibernated
+ entry.timeout = timeout
+}
+
+// Route is the core method. It ensures the sandbox is running before
+// executing the operation. If hibernated, it triggers auto-wake and
+// queues the operation. If waking, it waits behind the wake lock.
+// Every successful route resets the rolling timeout.
+func (r *SandboxRouter) Route(ctx context.Context, sandboxID string, op string, fn func(ctx context.Context) error) error {
+ // Apply middleware chain (outermost first)
+ wrapped := fn
+ for i := len(r.middlewares) - 1; i >= 0; i-- {
+ mw := r.middlewares[i]
+ next := wrapped
+ wrapped = func(ctx context.Context) error {
+ return mw(ctx, sandboxID, op, next)
+ }
+ }
+
+ // Ensure sandbox is ready (running state)
+ if err := r.ensureRunning(ctx, sandboxID); err != nil {
+ return err
+ }
+
+ // Execute the operation
+ err := wrapped(ctx)
+
+ // Reset rolling timeout on ANY interaction (success or failure)
+ r.resetTimeout(sandboxID)
+
+ return err
+}
+
+// Touch resets the rolling timeout without routing an operation.
+// Useful for long-lived connections (WebSocket PTY) that indicate activity.
+func (r *SandboxRouter) Touch(sandboxID string) {
+ r.resetTimeout(sandboxID)
+}
+
+// SetTimeout updates the configured timeout duration for a sandbox
+// and resets the timer.
+func (r *SandboxRouter) SetTimeout(sandboxID string, timeout time.Duration) {
+ r.mu.RLock()
+ entry, ok := r.sandboxes[sandboxID]
+ r.mu.RUnlock()
+ if !ok {
+ return
+ }
+
+ entry.mu.Lock()
+ defer entry.mu.Unlock()
+
+ entry.timeout = timeout
+ if entry.timer != nil {
+ entry.timer.Stop()
+ }
+ if entry.state == StateRunning {
+ entry.timer = time.AfterFunc(timeout, func() {
+ r.onTimeout(sandboxID)
+ })
+ }
+}
+
+// GetState returns the current state of a sandbox in the router.
+// Returns (state, tracked). If tracked is false, the sandbox is unknown.
+func (r *SandboxRouter) GetState(sandboxID string) (SandboxState, bool) {
+ r.mu.RLock()
+ entry, ok := r.sandboxes[sandboxID]
+ r.mu.RUnlock()
+ if !ok {
+ return 0, false
+ }
+ entry.mu.Lock()
+ defer entry.mu.Unlock()
+ return entry.state, true
+}
+
+// Close stops all timers and cleans up.
+func (r *SandboxRouter) Close() {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ for _, entry := range r.sandboxes {
+ entry.mu.Lock()
+ if entry.timer != nil {
+ entry.timer.Stop()
+ }
+ entry.mu.Unlock()
+ }
+ r.sandboxes = make(map[string]*sandboxEntry)
+}
+
+// Manager returns the underlying Manager for direct lifecycle operations
+// (create, kill, hibernate, wake) that don't go through routing.
+func (r *SandboxRouter) Manager() *Manager {
+ return r.manager
+}
+
+// ensureRunning checks the sandbox state and handles wake if needed.
+func (r *SandboxRouter) ensureRunning(ctx context.Context, sandboxID string) error {
+ r.mu.RLock()
+ entry, ok := r.sandboxes[sandboxID]
+ r.mu.RUnlock()
+
+ if !ok {
+ // Not tracked by the router — try to discover state from DB
+ return r.discoverAndEnsure(ctx, sandboxID)
+ }
+
+ entry.mu.Lock()
+
+ switch entry.state {
+ case StateRunning:
+ entry.mu.Unlock()
+ return nil
+
+ case StateHibernated:
+ // Transition to waking, start wake, other requests will queue
+ entry.state = StateWaking
+ entry.wakeCh = make(chan struct{})
+ entry.wakeErr = nil
+ entry.mu.Unlock()
+
+ // Perform wake (only one goroutine does this)
+ r.doWake(ctx, sandboxID, entry)
+
+ // Check wake result
+ entry.mu.Lock()
+ err := entry.wakeErr
+ entry.mu.Unlock()
+ if err != nil {
+ return fmt.Errorf("auto-wake failed for sandbox %s: %w", sandboxID, err)
+ }
+ return nil
+
+ case StateWaking:
+ // Another goroutine is already waking — wait for it
+ wakeCh := entry.wakeCh
+ entry.mu.Unlock()
+
+ select {
+ case <-wakeCh:
+ // Wake completed — check result
+ entry.mu.Lock()
+ err := entry.wakeErr
+ entry.mu.Unlock()
+ if err != nil {
+ return fmt.Errorf("auto-wake failed for sandbox %s: %w", sandboxID, err)
+ }
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+
+ default:
+ entry.mu.Unlock()
+ return fmt.Errorf("sandbox %s in unexpected state: %v", sandboxID, entry.state)
+ }
+}
+
+// discoverAndEnsure attempts to look up a sandbox's state from the DB
+// (for cases where the router doesn't have it tracked yet, e.g. after restart).
+func (r *SandboxRouter) discoverAndEnsure(ctx context.Context, sandboxID string) error {
+ if r.store == nil || r.checkpointStore == nil {
+ // No DB/S3 — can't auto-wake, let the operation proceed
+ // (podman will return an error if the container doesn't exist)
+ return nil
+ }
+
+ // Check if there's an active checkpoint (meaning it's hibernated)
+ checkpoint, err := r.store.GetActiveCheckpoint(ctx, sandboxID)
+ if err != nil || checkpoint == nil {
+ // No checkpoint found — sandbox might be running or doesn't exist
+ return nil
+ }
+
+ // Found a checkpoint — register as hibernated and then ensure running
+ r.MarkHibernated(sandboxID, r.defaultTimeout)
+ return r.ensureRunning(ctx, sandboxID)
+}
+
+// doWake performs the actual wake operation and transitions state.
+// Only one goroutine calls this per sandbox per wake cycle.
+func (r *SandboxRouter) doWake(ctx context.Context, sandboxID string, entry *sandboxEntry) {
+ // Use a background context for the wake itself so it completes
+ // even if the original request times out
+ wakeCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ var wakeErr error
+ defer func() {
+ entry.mu.Lock()
+ entry.wakeErr = wakeErr
+ if wakeErr != nil {
+ entry.state = StateHibernated // revert on failure
+ }
+ close(entry.wakeCh)
+ entry.wakeCh = nil
+ entry.mu.Unlock()
+ }()
+
+ if r.store == nil || r.checkpointStore == nil {
+ wakeErr = fmt.Errorf("hibernation infrastructure not configured")
+ return
+ }
+
+ checkpoint, err := r.store.GetActiveCheckpoint(wakeCtx, sandboxID)
+ if err != nil {
+ wakeErr = fmt.Errorf("no active checkpoint: %w", err)
+ return
+ }
+
+ timeout := int(entry.timeout.Seconds())
+ if timeout <= 0 {
+ timeout = int(r.defaultTimeout.Seconds())
+ }
+
+ sb, err := r.manager.Wake(wakeCtx, sandboxID, checkpoint.CheckpointKey, r.checkpointStore, timeout)
+ if err != nil {
+ wakeErr = err
+ return
+ }
+
+ // Update DB records
+ _ = r.store.MarkCheckpointRestored(wakeCtx, sandboxID)
+ _ = r.store.UpdateSandboxSessionForWake(wakeCtx, sandboxID, r.workerID)
+
+ log.Printf("router: auto-woke sandbox %s (status=%s)", sandboxID, sb.Status)
+
+ // Transition to running and start rolling timeout
+ entry.mu.Lock()
+ entry.state = StateRunning
+ entry.timer = time.AfterFunc(entry.timeout, func() {
+ r.onTimeout(sandboxID)
+ })
+ entry.mu.Unlock()
+}
+
+// resetTimeout resets the rolling timeout for a sandbox.
+func (r *SandboxRouter) resetTimeout(sandboxID string) {
+ r.mu.RLock()
+ entry, ok := r.sandboxes[sandboxID]
+ r.mu.RUnlock()
+
+ if !ok {
+ return
+ }
+
+ entry.mu.Lock()
+ defer entry.mu.Unlock()
+
+ if entry.state != StateRunning {
+ return
+ }
+
+ if entry.timer != nil {
+ entry.timer.Stop()
+ }
+ entry.timer = time.AfterFunc(entry.timeout, func() {
+ r.onTimeout(sandboxID)
+ })
+}
+
+// onTimeout is called when the rolling timeout fires (no activity for timeout duration).
+func (r *SandboxRouter) onTimeout(sandboxID string) {
+ r.mu.RLock()
+ entry, ok := r.sandboxes[sandboxID]
+ r.mu.RUnlock()
+
+ if !ok {
+ return
+ }
+
+ entry.mu.Lock()
+ if entry.state != StateRunning {
+ entry.mu.Unlock()
+ return
+ }
+ entry.mu.Unlock()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ // Try hibernate if checkpoint store is available
+ if r.checkpointStore != nil {
+ name := r.manager.ContainerName(sandboxID)
+ result, err := r.manager.Hibernate(ctx, sandboxID, r.checkpointStore)
+ if err != nil {
+ log.Printf("router: hibernate failed for %s, killing: %v", sandboxID, err)
+ _ = r.manager.podman.RemoveContainer(ctx, name, true)
+ r.Unregister(sandboxID)
+ return
+ }
+
+ log.Printf("router: sandbox %s hibernated on timeout (key=%s, size=%d)", sandboxID, result.CheckpointKey, result.SizeBytes)
+
+ entry.mu.Lock()
+ entry.state = StateHibernated
+ entry.timer = nil
+ entry.mu.Unlock()
+
+ if r.onHibernate != nil {
+ r.onHibernate(sandboxID, result)
+ }
+ return
+ }
+
+ // No checkpoint store — just kill
+ name := r.manager.ContainerName(sandboxID)
+ _ = r.manager.podman.RemoveContainer(ctx, name, true)
+ r.Unregister(sandboxID)
+}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 32e2e2a0..dce61fd2 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"net"
+ "time"
"google.golang.org/grpc"
@@ -17,6 +18,7 @@ import (
type GRPCServer struct {
pb.UnimplementedSandboxWorkerServer
manager *sandbox.Manager
+ router *sandbox.SandboxRouter
ptyManager *sandbox.PTYManager
sandboxDBs *sandbox.SandboxDBManager
checkpointStore *storage.CheckpointStore
@@ -24,9 +26,10 @@ type GRPCServer struct {
}
// NewGRPCServer creates a new gRPC server wrapping the sandbox manager.
-func NewGRPCServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore) *GRPCServer {
+func NewGRPCServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter) *GRPCServer {
s := &GRPCServer{
manager: mgr,
+ router: router,
ptyManager: ptyMgr,
sandboxDBs: sandboxDBs,
checkpointStore: checkpointStore,
@@ -65,6 +68,15 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
return nil, fmt.Errorf("failed to create sandbox: %w", err)
}
+ // Register with sandbox router for rolling timeout tracking
+ if s.router != nil {
+ timeout := cfg.Timeout
+ if timeout <= 0 {
+ timeout = 300
+ }
+ s.router.Register(sb.ID, time.Duration(timeout)*time.Second)
+ }
+
// Initialize per-sandbox SQLite
if s.sandboxDBs != nil {
sdb, err := s.sandboxDBs.Get(sb.ID)
@@ -87,6 +99,11 @@ func (s *GRPCServer) DestroySandbox(ctx context.Context, req *pb.DestroySandboxR
return nil, fmt.Errorf("failed to destroy sandbox: %w", err)
}
+ // Unregister from sandbox router
+ if s.router != nil {
+ s.router.Unregister(req.SandboxId)
+ }
+
// Clean up SQLite
if s.sandboxDBs != nil {
_ = s.sandboxDBs.Remove(req.SandboxId)
@@ -139,9 +156,23 @@ func (s *GRPCServer) ExecCommand(ctx context.Context, req *pb.ExecCommandRequest
Timeout: int(req.Timeout),
}
- result, err := s.manager.Exec(ctx, req.SandboxId, cfg)
- if err != nil {
- return nil, fmt.Errorf("exec failed: %w", err)
+ var result *types.ProcessResult
+
+ routeOp := func(ctx context.Context) error {
+ var err error
+ result, err = s.manager.Exec(ctx, req.SandboxId, cfg)
+ return err
+ }
+
+ // Route through sandbox router (handles auto-wake, rolling timeout reset)
+ if s.router != nil {
+ if err := s.router.Route(ctx, req.SandboxId, "exec", routeOp); err != nil {
+ return nil, fmt.Errorf("exec failed: %w", err)
+ }
+ } else {
+ if err := routeOp(ctx); err != nil {
+ return nil, fmt.Errorf("exec failed: %w", err)
+ }
}
return &pb.ExecCommandResponse{
@@ -152,24 +183,62 @@ func (s *GRPCServer) ExecCommand(ctx context.Context, req *pb.ExecCommandRequest
}
func (s *GRPCServer) ReadFile(ctx context.Context, req *pb.ReadFileRequest) (*pb.ReadFileResponse, error) {
- content, err := s.manager.ReadFile(ctx, req.SandboxId, req.Path)
- if err != nil {
- return nil, fmt.Errorf("read file failed: %w", err)
+ var content string
+
+ routeOp := func(ctx context.Context) error {
+ var err error
+ content, err = s.manager.ReadFile(ctx, req.SandboxId, req.Path)
+ return err
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(ctx, req.SandboxId, "readFile", routeOp); err != nil {
+ return nil, fmt.Errorf("read file failed: %w", err)
+ }
+ } else {
+ if err := routeOp(ctx); err != nil {
+ return nil, fmt.Errorf("read file failed: %w", err)
+ }
}
+
return &pb.ReadFileResponse{Content: []byte(content)}, nil
}
func (s *GRPCServer) WriteFile(ctx context.Context, req *pb.WriteFileRequest) (*pb.WriteFileResponse, error) {
- if err := s.manager.WriteFile(ctx, req.SandboxId, req.Path, string(req.Content)); err != nil {
- return nil, fmt.Errorf("write file failed: %w", err)
+ routeOp := func(ctx context.Context) error {
+ return s.manager.WriteFile(ctx, req.SandboxId, req.Path, string(req.Content))
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(ctx, req.SandboxId, "writeFile", routeOp); err != nil {
+ return nil, fmt.Errorf("write file failed: %w", err)
+ }
+ } else {
+ if err := routeOp(ctx); err != nil {
+ return nil, fmt.Errorf("write file failed: %w", err)
+ }
}
+
return &pb.WriteFileResponse{}, nil
}
func (s *GRPCServer) ListDir(ctx context.Context, req *pb.ListDirRequest) (*pb.ListDirResponse, error) {
- entries, err := s.manager.ListDir(ctx, req.SandboxId, req.Path)
- if err != nil {
- return nil, fmt.Errorf("list dir failed: %w", err)
+ var entries []types.EntryInfo
+
+ routeOp := func(ctx context.Context) error {
+ var err error
+ entries, err = s.manager.ListDir(ctx, req.SandboxId, req.Path)
+ return err
+ }
+
+ if s.router != nil {
+ if err := s.router.Route(ctx, req.SandboxId, "listDir", routeOp); err != nil {
+ return nil, fmt.Errorf("list dir failed: %w", err)
+ }
+ } else {
+ if err := routeOp(ctx); err != nil {
+ return nil, fmt.Errorf("list dir failed: %w", err)
+ }
}
var pbEntries []*pb.DirEntry
@@ -222,6 +291,11 @@ func (s *GRPCServer) HibernateSandbox(ctx context.Context, req *pb.HibernateSand
return nil, fmt.Errorf("failed to hibernate sandbox: %w", err)
}
+ // Mark hibernated in sandbox router
+ if s.router != nil {
+ s.router.MarkHibernated(req.SandboxId, 600*time.Second)
+ }
+
// Clean up per-sandbox SQLite
if s.sandboxDBs != nil {
_ = s.sandboxDBs.Remove(req.SandboxId)
@@ -244,6 +318,15 @@ func (s *GRPCServer) WakeSandbox(ctx context.Context, req *pb.WakeSandboxRequest
return nil, fmt.Errorf("failed to wake sandbox: %w", err)
}
+ // Register with sandbox router after explicit wake
+ if s.router != nil {
+ timeout := int(req.Timeout)
+ if timeout <= 0 {
+ timeout = 300
+ }
+ s.router.Register(sb.ID, time.Duration(timeout)*time.Second)
+ }
+
// Re-initialize per-sandbox SQLite
if s.sandboxDBs != nil {
sdb, err := s.sandboxDBs.Get(sb.ID)
diff --git a/scripts/test-hibernation.sh b/scripts/test-hibernation.sh
index b2094aba..fddf0664 100755
--- a/scripts/test-hibernation.sh
+++ b/scripts/test-hibernation.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
-# Test hibernation: file persistence, process preservation, and timing
+# Test hibernation: file persistence, process preservation, auto-wake, and timing
# Usage: ./scripts/test-hibernation.sh [api_url] [api_key]
API_URL="${1:-http://localhost:8080}"
@@ -43,25 +43,13 @@ run_cmd() {
api POST "/api/sandboxes/${sandbox_id}/commands" "{\"cmd\": \"bash\", \"args\": [\"-c\", \"${cmd}\"]}"
}
-timed() {
- local label="$1"
- shift
- local start end duration
- start=$(python3 -c 'import time; print(time.time())')
- "$@"
- end=$(python3 -c 'import time; print(time.time())')
- duration=$(python3 -c "print(f'{${end} - ${start}:.3f}')")
- yellow " TIME: ${label} = ${duration}s"
- echo "$duration"
-}
-
bold "========================================="
bold " OpenSandbox Hibernation Test"
bold "========================================="
echo ""
# --- Cleanup stale sessions ---
-bold "[0/7] Cleaning up stale sandbox sessions..."
+bold "[0/9] Cleaning up stale sandbox sessions..."
docker compose -f deploy/docker-compose.yml exec -T postgres \
psql -U opensandbox -d opensandbox -c \
"UPDATE sandbox_sessions SET status = 'stopped', stopped_at = now() WHERE status IN ('running', 'hibernated');" \
@@ -69,7 +57,7 @@ docker compose -f deploy/docker-compose.yml exec -T postgres \
echo ""
# --- Create sandbox ---
-bold "[1/7] Creating sandbox..."
+bold "[1/9] Creating sandbox..."
CREATE_RESP=$(api POST "/api/sandboxes" '{"template": "ubuntu:22.04", "timeout": 600}')
SANDBOX_ID=$(echo "$CREATE_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])" 2>/dev/null)
if [[ -z "$SANDBOX_ID" ]]; then
@@ -80,7 +68,7 @@ green " Created sandbox: $SANDBOX_ID"
echo ""
# --- Write file state ---
-bold "[2/7] Writing file state..."
+bold "[2/9] Writing file state..."
run_cmd "$SANDBOX_ID" "echo hibernation-proof-42 > /tmp/proof.txt" > /dev/null
run_cmd "$SANDBOX_ID" "echo hello-world > /root/hello.txt" > /dev/null
run_cmd "$SANDBOX_ID" "mkdir -p /var/data && echo persistent-data > /var/data/test.txt" > /dev/null
@@ -95,13 +83,13 @@ check "/var/data/test.txt before hibernate" "persistent-data" "$DATA"
echo ""
# --- Check PID 1 process ---
-bold "[3/7] Verifying PID 1 (entrypoint) before hibernate..."
+bold "[3/9] Verifying PID 1 (entrypoint) before hibernate..."
PID1_CMD_BEFORE=$(run_cmd "$SANDBOX_ID" "cat /proc/1/cmdline | tr '\\0' ' '" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null || echo "unknown")
green " PID 1 command: $PID1_CMD_BEFORE"
echo ""
# --- Hibernate ---
-bold "[4/7] Hibernating sandbox..."
+bold "[4/9] Hibernating sandbox..."
HIB_START=$(python3 -c 'import time; print(time.time())')
HIB_RESP=$(api POST "/api/sandboxes/${SANDBOX_ID}/hibernate")
HIB_END=$(python3 -c 'import time; print(time.time())')
@@ -120,8 +108,8 @@ CONTAINER_CHECK=$(podman ps --format '{{.Names}}' 2>/dev/null | grep "osb-${SAND
check "Container removed after hibernate" "" "$CONTAINER_CHECK"
echo ""
-# --- Wake ---
-bold "[5/7] Waking sandbox..."
+# --- Explicit Wake ---
+bold "[5/9] Waking sandbox (explicit)..."
WAKE_START=$(python3 -c 'import time; print(time.time())')
WAKE_RESP=$(api POST "/api/sandboxes/${SANDBOX_ID}/wake" '{"timeout": 600}')
WAKE_END=$(python3 -c 'import time; print(time.time())')
@@ -133,7 +121,7 @@ check "Wake status" "running" "$WAKE_STATUS"
echo ""
# --- Verify file state ---
-bold "[6/7] Verifying file state after wake..."
+bold "[6/9] Verifying file state after wake..."
PROOF_AFTER=$(run_cmd "$SANDBOX_ID" "cat /tmp/proof.txt" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null)
HELLO_AFTER=$(run_cmd "$SANDBOX_ID" "cat /root/hello.txt" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null)
DATA_AFTER=$(run_cmd "$SANDBOX_ID" "cat /var/data/test.txt" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null)
@@ -143,7 +131,7 @@ check "/var/data/test.txt after wake" "persistent-data" "$DATA_AFTER"
echo ""
# --- Verify process state ---
-bold "[7/7] Verifying process state after wake..."
+bold "[7/9] Verifying process state after wake..."
PID1_CMD_AFTER=$(run_cmd "$SANDBOX_ID" "cat /proc/1/cmdline | tr '\\0' ' '" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null || echo "unknown")
check "PID 1 command preserved" "$PID1_CMD_BEFORE" "$PID1_CMD_AFTER"
PID1_EXISTS=$(run_cmd "$SANDBOX_ID" "test -d /proc/1 && echo yes || echo no" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null || echo "no")
@@ -154,16 +142,60 @@ ECHO_TEST=$(run_cmd "$SANDBOX_ID" "echo alive" | python3 -c "import sys,json; pr
check "Container is functional after wake" "alive" "$ECHO_TEST"
echo ""
+# --- Test auto-wake (hibernate then send command without explicit wake) ---
+bold "[8/9] Testing auto-wake (command to hibernated sandbox)..."
+
+# Write a marker file before second hibernate
+run_cmd "$SANDBOX_ID" "echo auto-wake-marker > /tmp/autowake.txt" > /dev/null
+
+# Hibernate again
+HIB2_RESP=$(api POST "/api/sandboxes/${SANDBOX_ID}/hibernate")
+HIB2_KEY=$(echo "$HIB2_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('checkpointKey',''))" 2>/dev/null)
+if [[ -z "$HIB2_KEY" ]]; then
+ red " Second hibernate failed: $HIB2_RESP"
+else
+ green " Hibernated (second time)"
+fi
+
+# Verify container is gone
+CONTAINER_CHECK2=$(podman ps --format '{{.Names}}' 2>/dev/null | grep "osb-${SANDBOX_ID}" || true)
+check "Container removed after second hibernate" "" "$CONTAINER_CHECK2"
+
+# Now send a command WITHOUT calling /wake — the router should auto-wake
+AUTOWAKE_START=$(python3 -c 'import time; print(time.time())')
+AUTOWAKE_RESP=$(run_cmd "$SANDBOX_ID" "cat /tmp/autowake.txt")
+AUTOWAKE_END=$(python3 -c 'import time; print(time.time())')
+AUTOWAKE_DURATION=$(python3 -c "print(f'{${AUTOWAKE_END} - ${AUTOWAKE_START}:.3f}')")
+yellow " TIME: Auto-wake + exec = ${AUTOWAKE_DURATION}s"
+
+AUTOWAKE_STDOUT=$(echo "$AUTOWAKE_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null || echo "")
+check "Auto-wake: file content preserved" "auto-wake-marker" "$AUTOWAKE_STDOUT"
+
+AUTOWAKE_EXIT=$(echo "$AUTOWAKE_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('exitCode', -1))" 2>/dev/null || echo "-1")
+check "Auto-wake: command succeeded (exit 0)" "0" "$AUTOWAKE_EXIT"
+echo ""
+
+# --- Test rolling timeout reset ---
+bold "[9/9] Verifying rolling timeout resets on activity..."
+# The sandbox should still be running from the auto-wake. Send a few commands
+# to verify the router resets the timeout each time.
+for i in 1 2 3; do
+ PING=$(run_cmd "$SANDBOX_ID" "echo pong-${i}" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null || echo "")
+ check "Rolling timeout ping $i" "pong-${i}" "$PING"
+done
+echo ""
+
# --- Cleanup ---
bold "Cleaning up..."
-api POST "/api/sandboxes/${SANDBOX_ID}/commands" '{"cmd": "kill", "args": ["1"]}' > /dev/null 2>&1 || true
+api DELETE "/api/sandboxes/${SANDBOX_ID}" > /dev/null 2>&1 || true
# --- Summary ---
echo ""
bold "========================================="
bold " Results: $PASS passed, $FAIL failed"
-bold " Hibernate: ~${HIBERNATE_DURATION:-?}s"
-bold " Wake: ~${WAKE_DURATION}s"
+bold " Hibernate: ~${HIBERNATE_DURATION:-?}s"
+bold " Explicit Wake: ~${WAKE_DURATION}s"
+bold " Auto-wake+Exec: ~${AUTOWAKE_DURATION:-?}s"
bold "========================================="
if [[ $FAIL -gt 0 ]]; then