An open-source, faster Devin alternative
TypeScript
initial hibernation flow
Brian Reardona20d942db98c
diff --git a/Makefile b/Makefileindex c1ac1a20..2c589270 100644--- a/Makefile+++ b/Makefile@@ -152,6 +152,10 @@ test:test-unit:go test ./... -v -count=1 -short+## test-hibernation: Run hibernation integration test (requires: server running with S3)+test-hibernation:+ @./scripts/test-hibernation.sh+## fmt: Format codefmt:go fmt ./...diff --git a/cmd/server/main.go b/cmd/server/main.goindex 1684500f..cc2e0f94 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -16,6 +16,7 @@ import ("github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/podman""github.com/opensandbox/opensandbox/internal/sandbox"+ "github.com/opensandbox/opensandbox/internal/storage""github.com/opensandbox/opensandbox/internal/template")@@ -114,6 +115,33 @@ func main() {log.Println("opensandbox: WorkOS authentication configured")}+ // Initialize S3 checkpoint store for hibernation (if configured)+ if cfg.S3Bucket != "" {+ checkpointStore, err := storage.NewCheckpointStore(storage.S3Config{+ Endpoint: cfg.S3Endpoint,+ Bucket: cfg.S3Bucket,+ Region: cfg.S3Region,+ AccessKeyID: cfg.S3AccessKeyID,+ SecretAccessKey: cfg.S3SecretAccessKey,+ ForcePathStyle: cfg.S3ForcePathStyle,+ })+ if err != nil {+ log.Printf("opensandbox: failed to initialize checkpoint store: %v (continuing without hibernation)", err)+ } 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 Redis worker registry in server modeif cfg.Mode == "server" && cfg.RedisURL != "" {redisRegistry, err := controlplane.NewRedisWorkerRegistry(cfg.RedisURL)diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 2b8de6f7..9003497e 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -14,6 +14,7 @@ import ("github.com/opensandbox/opensandbox/internal/metrics""github.com/opensandbox/opensandbox/internal/podman""github.com/opensandbox/opensandbox/internal/sandbox"+ "github.com/opensandbox/opensandbox/internal/storage""github.com/opensandbox/opensandbox/internal/worker")@@ -56,13 +57,38 @@ func main() {}jwtIssuer := auth.NewJWTIssuer(cfg.JWTSecret)+ // Initialize S3 checkpoint store for hibernation (if configured)+ var checkpointStore *storage.CheckpointStore+ if cfg.S3Bucket != "" {+ var err error+ checkpointStore, err = storage.NewCheckpointStore(storage.S3Config{+ Endpoint: cfg.S3Endpoint,+ Bucket: cfg.S3Bucket,+ Region: cfg.S3Region,+ AccessKeyID: cfg.S3AccessKeyID,+ SecretAccessKey: cfg.S3SecretAccessKey,+ ForcePathStyle: cfg.S3ForcePathStyle,+ })+ if err != nil {+ 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) {+ log.Printf("opensandbox-worker: sandbox %s auto-hibernated (key=%s, size=%d bytes)",+ sandboxID, result.CheckpointKey, result.SizeBytes)+ })+ }+// Start Prometheus metrics server on :9091metricsSrv := metrics.StartMetricsServer(":9091")defer metricsSrv.Close()log.Println("opensandbox-worker: metrics server started on :9091")// Start gRPC server for control plane communication- grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr)+ grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr, checkpointStore)grpcAddr := ":9090"log.Printf("opensandbox-worker: starting gRPC server on %s", grpcAddr)go func() {diff --git a/deploy/Dockerfile.worker b/deploy/Dockerfile.workerindex 098a262a..55a8880a 100644--- a/deploy/Dockerfile.worker+++ b/deploy/Dockerfile.worker@@ -12,6 +12,7 @@ FROM ubuntu:22.04RUN apt-get update && apt-get install -y --no-install-recommends \podman \crun \+ criu \uidmap \fuse-overlayfs \slirp4netns \diff --git a/go.mod b/go.modindex 0d60981f..ea1e94ca 100644--- a/go.mod+++ b/go.mod@@ -3,6 +3,9 @@ module github.com/opensandbox/opensandboxgo 1.23.0require (+ github.com/aws/aws-sdk-go-v2 v1.41.1+ github.com/aws/aws-sdk-go-v2/credentials v1.19.8+ github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0github.com/creack/pty v1.1.24github.com/golang-jwt/jwt/v5 v5.2.1github.com/google/uuid v1.6.0@@ -19,6 +22,15 @@ require ()require (+ github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirect+ github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 // indirect+ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 // indirect+ github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 // indirect+ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect+ github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8 // indirect+ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 // indirect+ github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17 // indirect+ github.com/aws/smithy-go v1.24.0 // indirectgithub.com/beorn7/perks v1.0.1 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirectgithub.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirectdiff --git a/go.sum b/go.sumindex a2eb0254..fde07db8 100644--- a/go.sum+++ b/go.sum@@ -1,3 +1,27 @@+github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU=+github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0=+github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=+github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4/go.mod h1:IOAPF6oT9KCsceNTvvYMNHy0+kMF8akOjeDvPENWxp4=+github.com/aws/aws-sdk-go-v2/credentials v1.19.8 h1:Jp2JYH1lRT3KhX4mshHPvVYsR5qqRec3hGvEarNYoR0=+github.com/aws/aws-sdk-go-v2/credentials v1.19.8/go.mod h1:fZG9tuvyVfxknv1rKibIz3DobRaFw1Poe8IKtXB3XYY=+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U=+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ=+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik=+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM=+github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 h1:JqcdRG//czea7Ppjb+g/n4o8i/R50aTBHkA7vu0lK+k=+github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17/go.mod h1:CO+WeGmIdj/MlPel2KwID9Gt7CNq4M65HUfBW97liM0=+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E=+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow=+github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8 h1:Z5EiPIzXKewUQK0QTMkutjiaPVeVYXX7KIqhXu/0fXs=+github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8/go.mod h1:FsTpJtvC4U1fyDXk7c71XoDv3HlRm8V3NiYLeYLh5YE=+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 h1:RuNSMoozM8oXlgLG/n6WLaFGoea7/CddrCfIiSA+xdY=+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17/go.mod h1:F2xxQ9TZz5gDWsclCtPQscGpP0VUOc8RqgFM3vDENmU=+github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17 h1:bGeHBsGZx0Dvu/eJC0Lh9adJa3M1xREcndxLNZlve2U=+github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17/go.mod h1:dcW24lbU0CzHusTE8LLHhRLI42ejmINN8Lcr22bwh/g=+github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0 h1:oeu8VPlOre74lBA/PMhxa5vewaMIMmILM+RraSyB8KA=+github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0/go.mod h1:5jggDlZ2CLQhwJBiZJb4vfk4f0GxWdEDruWKEJ1xOdo=+github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk=+github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=diff --git a/internal/api/router.go b/internal/api/router.goindex 7902f003..d9208c1c 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -14,6 +14,7 @@ import ("github.com/opensandbox/opensandbox/internal/controlplane""github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/sandbox"+ "github.com/opensandbox/opensandbox/internal/storage")var errSandboxNotAvailable = map[string]string{@@ -32,9 +33,10 @@ type Server struct {workerID string // this worker's IDregion string // this worker's regionhttpAddr string // public HTTP address for direct access- sandboxDBs *sandbox.SandboxDBManager // per-sandbox SQLite manager- workos *auth.WorkOSMiddleware // nil if WorkOS not configured- workerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode+ sandboxDBs *sandbox.SandboxDBManager // per-sandbox SQLite manager+ workos *auth.WorkOSMiddleware // nil if WorkOS not configured+ workerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode+ checkpointStore *storage.CheckpointStore // nil if hibernation not configured}// ServerOpts holds optional dependencies for the API server.@@ -46,8 +48,9 @@ type ServerOpts struct {Region stringHTTPAddr stringSandboxDBs *sandbox.SandboxDBManager- WorkOSConfig *auth.WorkOSConfig // nil if WorkOS not configured- WorkerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker 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}// NewServer creates a new API server with all routes configured.@@ -71,6 +74,7 @@ func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string,s.httpAddr = opts.HTTPAddrs.sandboxDBs = opts.SandboxDBss.workerRegistry = opts.WorkerRegistry+ s.checkpointStore = opts.CheckpointStore}// Global middleware@@ -95,6 +99,10 @@ func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string,api.DELETE("/sandboxes/:id", s.killSandbox)api.POST("/sandboxes/:id/timeout", s.setTimeout)+ // Hibernation+ api.POST("/sandboxes/:id/hibernate", s.hibernateSandbox)+ api.POST("/sandboxes/:id/wake", s.wakeSandbox)+// Commandsapi.POST("/sandboxes/:id/commands", s.runCommand)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 18a46e5b..078ef6b2 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -220,6 +220,17 @@ func (s *Server) getSandboxRemote(c echo.Context, sandboxID string) error {})}+ // Hibernated sandboxes have no worker+ if session.Status == "hibernated" {+ return c.JSON(http.StatusOK, map[string]interface{}{+ "sandboxID": sandboxID,+ "status": "hibernated",+ "region": session.Region,+ "template": session.Template,+ "startedAt": session.StartedAt,+ })+ }+// Look up worker addressworker := s.workerRegistry.GetWorker(session.WorkerID)connectURL := ""@@ -427,6 +438,236 @@ func (s *Server) setTimeout(c echo.Context) error {return c.NoContent(http.StatusNoContent)}+func (s *Server) hibernateSandbox(c echo.Context) error {+ id := c.Param("id")+ ctx := c.Request().Context()++ // Server mode: dispatch to worker via gRPC+ if s.workerRegistry != nil {+ return s.hibernateSandboxRemote(c, id)+ }++ // Combined mode: hibernate locally+ if s.manager == nil || s.checkpointStore == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "hibernation not available",+ })+ }++ result, err := s.manager.Hibernate(ctx, id, s.checkpointStore)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ // Record checkpoint in PG+ orgID, hasOrg := auth.GetOrgID(c)+ if s.store != nil && hasOrg {+ session, _ := s.store.GetSandboxSession(ctx, id)+ cfg := json.RawMessage("{}")+ if session != nil {+ cfg = session.Config+ }+ template := "base"+ region := s.region+ if session != nil {+ template = session.Template+ region = session.Region+ }+ _, _ = s.store.CreateCheckpoint(ctx, id, orgID, result.CheckpointKey, result.SizeBytes, region, template, cfg)+ _ = s.store.UpdateSandboxSessionStatus(ctx, id, "hibernated", nil)+ }++ if s.sandboxDBs != nil {+ _ = s.sandboxDBs.Remove(id)+ }++ return c.JSON(http.StatusOK, map[string]interface{}{+ "sandboxID": id,+ "status": "hibernated",+ "checkpointKey": result.CheckpointKey,+ "sizeBytes": result.SizeBytes,+ })+}++func (s *Server) hibernateSandboxRemote(c echo.Context, sandboxID string) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "database not configured",+ })+ }++ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }+ if session.Status != "running" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandbox is not running"})+ }++ client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)+ if err != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker unreachable"})+ }++ grpcCtx, cancel := context.WithTimeout(c.Request().Context(), 60*time.Second)+ defer cancel()++ grpcResp, err := client.HibernateSandbox(grpcCtx, &pb.HibernateSandboxRequest{+ SandboxId: sandboxID,+ })+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "hibernate failed: " + err.Error(),+ })+ }++ // Record checkpoint in PG+ orgID, _ := auth.GetOrgID(c)+ _, _ = s.store.CreateCheckpoint(c.Request().Context(), sandboxID, orgID,+ grpcResp.CheckpointKey, grpcResp.SizeBytes,+ session.Region, session.Template, session.Config)+ _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "hibernated", nil)++ return c.JSON(http.StatusOK, map[string]interface{}{+ "sandboxID": sandboxID,+ "status": "hibernated",+ "checkpointKey": grpcResp.CheckpointKey,+ "sizeBytes": grpcResp.SizeBytes,+ })+}++func (s *Server) wakeSandbox(c echo.Context) error {+ id := c.Param("id")+ ctx := c.Request().Context()++ var req types.WakeRequest+ _ = c.Bind(&req)++ // Server mode: pick any worker, dispatch via gRPC+ if s.workerRegistry != nil {+ return s.wakeSandboxRemote(c, id, req)+ }++ // Combined mode: wake locally+ if s.manager == nil || s.checkpointStore == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "hibernation not available",+ })+ }++ // Get checkpoint key from PG+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "database not configured",+ })+ }++ checkpoint, err := s.store.GetActiveCheckpoint(ctx, id)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "no active checkpoint found"})+ }++ sb, err := s.manager.Wake(ctx, id, checkpoint.CheckpointKey, s.checkpointStore, req.Timeout)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ _ = s.store.MarkCheckpointRestored(ctx, id)+ _ = s.store.UpdateSandboxSessionForWake(ctx, id, s.workerID)++ // Issue fresh JWT+ orgID, _ := auth.GetOrgID(c)+ if s.jwtIssuer != nil {+ timeout := req.Timeout+ if timeout <= 0 {+ timeout = 300+ }+ token, err := s.jwtIssuer.IssueSandboxToken(orgID, id, s.workerID, time.Duration(timeout)*time.Second)+ if err == nil {+ sb.Token = token+ }+ }++ sb.ConnectURL = s.httpAddr++ return c.JSON(http.StatusOK, sb)+}++func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.WakeRequest) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "database not configured",+ })+ }++ checkpoint, err := s.store.GetActiveCheckpoint(c.Request().Context(), sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "no active checkpoint found"})+ }++ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox session not found"})+ }+ if session.Status != "hibernated" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandbox is not hibernated"})+ }++ // Pick ANY worker in the same region+ region := checkpoint.Region+ worker, grpcClient, err := s.workerRegistry.GetLeastLoadedWorker(region)+ if err != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "no workers available in region " + region,+ })+ }++ grpcCtx, cancel := context.WithTimeout(c.Request().Context(), 60*time.Second)+ defer cancel()++ grpcResp, err := grpcClient.WakeSandbox(grpcCtx, &pb.WakeSandboxRequest{+ SandboxId: sandboxID,+ CheckpointKey: checkpoint.CheckpointKey,+ Timeout: int32(req.Timeout),+ })+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "wake failed: " + err.Error(),+ })+ }++ // Mark checkpoint as restored, update session+ _ = s.store.MarkCheckpointRestored(c.Request().Context(), sandboxID)+ _ = s.store.UpdateSandboxSessionForWake(c.Request().Context(), sandboxID, worker.ID)++ // Issue fresh JWT+ orgID, _ := auth.GetOrgID(c)+ timeout := req.Timeout+ if timeout <= 0 {+ timeout = 300+ }+ var token string+ if s.jwtIssuer != nil {+ t, err := s.jwtIssuer.IssueSandboxToken(orgID, sandboxID, worker.ID, time.Duration(timeout)*time.Second)+ if err == nil {+ token = t+ }+ }++ return c.JSON(http.StatusOK, map[string]interface{}{+ "sandboxID": sandboxID,+ "connectURL": worker.HTTPAddr,+ "token": token,+ "status": grpcResp.Status,+ "region": region,+ "workerID": worker.ID,+ })+}+// listSessions returns session history from PostgreSQL.func (s *Server) listSessions(c echo.Context) error {if s.store == nil {diff --git a/internal/config/config.go b/internal/config/config.goindex 04a35153..7b450a4a 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -41,6 +41,14 @@ type Config struct {// Worker capacityMaxCapacity int++ // S3-compatible object storage for checkpoint hibernation+ S3Endpoint string // e.g. "https://<account>.r2.cloudflarestorage.com"+ S3Bucket string // e.g. "opensandbox-checkpoints"+ S3Region string // defaults to Region if not set+ S3AccessKeyID string+ S3SecretAccessKey string+ S3ForcePathStyle bool // true for R2/MinIO}// Load reads configuration from environment variables with sensible defaults.@@ -69,6 +77,18 @@ func Load() (*Config, error) {RedisURL: os.Getenv("OPENSANDBOX_REDIS_URL"),MaxCapacity: envOrDefaultInt("OPENSANDBOX_MAX_CAPACITY", 50),++ S3Endpoint: os.Getenv("OPENSANDBOX_S3_ENDPOINT"),+ S3Bucket: os.Getenv("OPENSANDBOX_S3_BUCKET"),+ S3Region: os.Getenv("OPENSANDBOX_S3_REGION"),+ S3AccessKeyID: os.Getenv("OPENSANDBOX_S3_ACCESS_KEY_ID"),+ S3SecretAccessKey: os.Getenv("OPENSANDBOX_S3_SECRET_ACCESS_KEY"),+ S3ForcePathStyle: os.Getenv("OPENSANDBOX_S3_FORCE_PATH_STYLE") == "true",+ }++ // Default S3 region to worker region for same-region storage+ if cfg.S3Region == "" {+ cfg.S3Region = cfg.Region}if portStr := os.Getenv("OPENSANDBOX_PORT"); portStr != "" {diff --git a/internal/db/migrations/003_checkpoint_hibernation.up.sql b/internal/db/migrations/003_checkpoint_hibernation.up.sqlnew file mode 100644index 00000000..d2ba6420--- /dev/null+++ b/internal/db/migrations/003_checkpoint_hibernation.up.sql@@ -0,0 +1,18 @@+-- Checkpoint storage for hibernated sandboxes+CREATE TABLE sandbox_checkpoints (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ sandbox_id TEXT NOT NULL,+ org_id UUID NOT NULL REFERENCES orgs(id),+ checkpoint_key TEXT NOT NULL,+ size_bytes BIGINT NOT NULL DEFAULT 0,+ region TEXT NOT NULL,+ template TEXT NOT NULL,+ sandbox_config JSONB NOT NULL DEFAULT '{}',+ hibernated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ restored_at TIMESTAMPTZ,+ expired_at TIMESTAMPTZ+);++CREATE INDEX idx_checkpoints_sandbox ON sandbox_checkpoints(sandbox_id);+CREATE INDEX idx_checkpoints_org ON sandbox_checkpoints(org_id);+CREATE UNIQUE INDEX idx_checkpoints_active ON sandbox_checkpoints(sandbox_id) WHERE restored_at IS NULL AND expired_at IS NULL;diff --git a/internal/db/store.go b/internal/db/store.goindex e6932ea8..dac49bad 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -66,6 +66,7 @@ func (s *Store) Migrate(ctx context.Context) error {}{{1, "migrations/001_initial.up.sql"},{2, "migrations/002_user_sessions.up.sql"},+ {3, "migrations/003_checkpoint_hibernation.up.sql"},}for _, m := range migrations {@@ -317,6 +318,10 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statuif status == "stopped" || status == "error" {query = `UPDATE sandbox_sessions SET status = $1, stopped_at = now(), error_msg = $2 WHERE sandbox_id = $3 AND status = 'running'`args = []interface{}{status, errorMsg, sandboxID}+ } else if status == "hibernated" {+ // Hibernated sandboxes are not stopped — don't set stopped_at+ query = `UPDATE sandbox_sessions SET status = $1 WHERE sandbox_id = $2 AND status = 'running'`+ args = []interface{}{status, sandboxID}} else {query = `UPDATE sandbox_sessions SET status = $1 WHERE sandbox_id = $2 AND status = 'running'`args = []interface{}{status, sandboxID}@@ -512,3 +517,69 @@ func (s *Store) DeleteAccessTokensForUser(ctx context.Context, userID uuid.UUID)func (s *Store) Pool() *pgxpool.Pool {return s.pool}++// --- Checkpoint operations ---++// SandboxCheckpoint represents a hibernated sandbox's checkpoint record.+type SandboxCheckpoint struct {+ ID uuid.UUID `json:"id"`+ SandboxID string `json:"sandboxId"`+ OrgID uuid.UUID `json:"orgId"`+ CheckpointKey string `json:"checkpointKey"`+ SizeBytes int64 `json:"sizeBytes"`+ Region string `json:"region"`+ Template string `json:"template"`+ SandboxConfig json.RawMessage `json:"sandboxConfig"`+ HibernatedAt time.Time `json:"hibernatedAt"`+ RestoredAt *time.Time `json:"restoredAt,omitempty"`+ ExpiredAt *time.Time `json:"expiredAt,omitempty"`+}++// CreateCheckpoint inserts a new checkpoint record.+func (s *Store) CreateCheckpoint(ctx context.Context, sandboxID string, orgID uuid.UUID, checkpointKey string, sizeBytes int64, region, template string, sandboxConfig json.RawMessage) (*SandboxCheckpoint, error) {+ cp := &SandboxCheckpoint{}+ err := s.pool.QueryRow(ctx,+ `INSERT INTO sandbox_checkpoints (sandbox_id, org_id, checkpoint_key, size_bytes, region, template, sandbox_config)+ VALUES ($1, $2, $3, $4, $5, $6, $7)+ RETURNING id, sandbox_id, org_id, checkpoint_key, size_bytes, region, template, sandbox_config, hibernated_at`,+ sandboxID, orgID, checkpointKey, sizeBytes, region, template, sandboxConfig,+ ).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.CheckpointKey, &cp.SizeBytes,+ &cp.Region, &cp.Template, &cp.SandboxConfig, &cp.HibernatedAt)+ if err != nil {+ return nil, fmt.Errorf("failed to create checkpoint: %w", err)+ }+ return cp, nil+}++// GetActiveCheckpoint returns the active (not restored, not expired) checkpoint for a sandbox.+func (s *Store) GetActiveCheckpoint(ctx context.Context, sandboxID string) (*SandboxCheckpoint, error) {+ cp := &SandboxCheckpoint{}+ err := s.pool.QueryRow(ctx,+ `SELECT id, sandbox_id, org_id, checkpoint_key, size_bytes, region, template, sandbox_config, hibernated_at, restored_at, expired_at+ FROM sandbox_checkpoints+ WHERE sandbox_id = $1 AND restored_at IS NULL AND expired_at IS NULL`, sandboxID,+ ).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.CheckpointKey, &cp.SizeBytes,+ &cp.Region, &cp.Template, &cp.SandboxConfig, &cp.HibernatedAt, &cp.RestoredAt, &cp.ExpiredAt)+ if err != nil {+ return nil, fmt.Errorf("active checkpoint not found: %w", err)+ }+ return cp, nil+}++// MarkCheckpointRestored marks the active checkpoint for a sandbox as restored.+func (s *Store) MarkCheckpointRestored(ctx context.Context, sandboxID string) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_checkpoints SET restored_at = now()+ WHERE sandbox_id = $1 AND restored_at IS NULL AND expired_at IS NULL`,+ sandboxID)+ return err+}++// UpdateSandboxSessionForWake changes a hibernated session back to running on a new worker.+func (s *Store) UpdateSandboxSessionForWake(ctx context.Context, sandboxID, newWorkerID string) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_sessions SET status = 'running', worker_id = $1, stopped_at = NULL+ WHERE sandbox_id = $2 AND status = 'hibernated'`,+ newWorkerID, sandboxID)+ return err+}diff --git a/internal/podman/client.go b/internal/podman/client.goindex 1a8d2cc9..54d61959 100644--- a/internal/podman/client.go+++ b/internal/podman/client.go@@ -5,16 +5,20 @@ import ("context""encoding/json""fmt"+ "io""os""os/exec""path/filepath"+ "runtime""strings"+ "syscall")// Client wraps the podman CLI for container operations.type Client struct {binaryPath stringauthFile string // dedicated auth file to avoid Docker credential helper conflicts+ useSSH bool // true when checkpoint/restore must run inside a Podman machine VM (macOS)}// NewClient creates a new Podman client. It verifies podman is available.@@ -31,7 +35,15 @@ func NewClient() (*Client, error) {return nil, fmt.Errorf("failed to set up podman auth: %w", err)}- return &Client{binaryPath: path, authFile: authFile}, nil+ client := &Client{binaryPath: path, authFile: authFile}++ // Detect if we're on macOS (remote podman). Checkpoint/restore requires+ // running inside the VM via "podman machine ssh".+ if runtime.GOOS == "darwin" {+ client.useSSH = true+ }++ return client, nil}// AuthFile returns the path to the dedicated auth file.@@ -106,6 +118,193 @@ func (c *Client) RunJSON(ctx context.Context, dest interface{}, args ...string)return nil}+// runSSH executes a command inside the Podman machine VM via "podman machine ssh".+func (c *Client) runSSH(ctx context.Context, sshCmd string) (*ExecResult, error) {+ cmd := exec.CommandContext(ctx, c.binaryPath, "machine", "ssh", sshCmd)+ var stdout, stderr bytes.Buffer+ cmd.Stdout = &stdout+ cmd.Stderr = &stderr++ err := cmd.Run()++ result := &ExecResult{+ Stdout: stdout.String(),+ Stderr: stderr.String(),+ }++ if err != nil {+ if exitErr, ok := err.(*exec.ExitError); ok {+ result.ExitCode = exitErr.ExitCode()+ return result, nil+ }+ return result, fmt.Errorf("podman machine ssh failed: %w", err)+ }++ return result, nil+}++// CheckpointContainer checkpoints a running container and exports to a tar archive.+// Uses zstd compression for optimized checkpoint size.+// On macOS, checkpoint runs inside the Podman machine VM via SSH because+// the remote podman client doesn't support CRIU checkpoint operations.+func (c *Client) CheckpointContainer(ctx context.Context, nameOrID, exportPath string) error {+ if c.useSSH {+ // exportPath is a VM-local path (e.g. /tmp/...) since we'll copy it out separately+ sshCmd := fmt.Sprintf("podman container checkpoint --export %s --compress zstd %s", exportPath, nameOrID)+ result, err := c.runSSH(ctx, sshCmd)+ if err != nil {+ return fmt.Errorf("failed to checkpoint container %s: %w", nameOrID, err)+ }+ if result.ExitCode != 0 {+ return fmt.Errorf("podman checkpoint failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))+ }+ return nil+ }++ result, err := c.Run(ctx, "container", "checkpoint", "--export", exportPath, "--compress", "zstd", nameOrID)+ if err != nil {+ return fmt.Errorf("failed to checkpoint container %s: %w", nameOrID, err)+ }+ if result.ExitCode != 0 {+ return fmt.Errorf("podman checkpoint failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))+ }+ return nil+}++// RestoreContainer restores a container from a checkpoint archive on disk.+// On macOS, restore runs inside the Podman machine VM via SSH.+func (c *Client) RestoreContainer(ctx context.Context, importPath, name string) error {+ if c.useSSH {+ sshCmd := fmt.Sprintf("podman container restore --import %s --name %s", importPath, name)+ result, err := c.runSSH(ctx, sshCmd)+ if err != nil {+ return fmt.Errorf("failed to restore container %s: %w", name, err)+ }+ if result.ExitCode != 0 {+ return fmt.Errorf("podman restore failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))+ }+ return nil+ }++ result, err := c.Run(ctx, "container", "restore", "--import", importPath, "--name", name)+ if err != nil {+ return fmt.Errorf("failed to restore container %s: %w", name, err)+ }+ if result.ExitCode != 0 {+ return fmt.Errorf("podman restore failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))+ }+ return nil+}++// CopyFromVM copies a file from the Podman machine VM to the local host (macOS only).+func (c *Client) CopyFromVM(ctx context.Context, vmPath, localPath string) error {+ // podman machine ssh "cat <vmPath>" > localPath+ cmd := exec.CommandContext(ctx, c.binaryPath, "machine", "ssh", "cat "+vmPath)+ outFile, err := os.Create(localPath)+ if err != nil {+ return fmt.Errorf("failed to create local file %s: %w", localPath, err)+ }+ defer outFile.Close()+ cmd.Stdout = outFile+ var stderr bytes.Buffer+ cmd.Stderr = &stderr+ if err := cmd.Run(); err != nil {+ return fmt.Errorf("failed to copy from VM: %s", strings.TrimSpace(stderr.String()))+ }+ return nil+}++// CopyToVM copies a file from the local host to the Podman machine VM (macOS only).+func (c *Client) CopyToVM(ctx context.Context, localPath, vmPath string) error {+ // cat localPath | podman machine ssh "cat > <vmPath>"+ inFile, err := os.Open(localPath)+ if err != nil {+ return fmt.Errorf("failed to open local file %s: %w", localPath, err)+ }+ defer inFile.Close()+ cmd := exec.CommandContext(ctx, c.binaryPath, "machine", "ssh", "cat > "+vmPath)+ cmd.Stdin = inFile+ var stderr bytes.Buffer+ cmd.Stderr = &stderr+ if err := cmd.Run(); err != nil {+ return fmt.Errorf("failed to copy to VM: %s", strings.TrimSpace(stderr.String()))+ }+ return nil+}++// RemoveVMFile removes a file inside the Podman machine VM (macOS only).+func (c *Client) RemoveVMFile(ctx context.Context, vmPath string) error {+ _, err := c.runSSH(ctx, "rm -f "+vmPath)+ return err+}++// UseSSH returns whether the client routes checkpoint/restore through VM SSH.+func (c *Client) UseSSH() bool {+ return c.useSSH+}++// RestoreContainerFromStream restores a container by piping a checkpoint archive+// from an io.Reader (e.g., S3 download body) into podman via a named FIFO pipe.+// This avoids writing the full checkpoint to local disk.+// On macOS, streams through the VM: write to local temp file, copy to VM, restore from VM path.+func (c *Client) RestoreContainerFromStream(ctx context.Context, reader io.Reader, name string) error {+ if c.useSSH {+ // On macOS, we can't use FIFOs across the VM boundary.+ // Write to local temp, copy into VM, restore from VM path.+ tmpFile, err := os.CreateTemp("", "osb-restore-*.tar.zst")+ if err != nil {+ return fmt.Errorf("failed to create temp file: %w", err)+ }+ localPath := tmpFile.Name()+ defer os.Remove(localPath)++ if _, err := io.Copy(tmpFile, reader); err != nil {+ tmpFile.Close()+ return fmt.Errorf("failed to write checkpoint to temp file: %w", err)+ }+ tmpFile.Close()++ vmPath := "/tmp/osb-restore-" + filepath.Base(localPath)+ if err := c.CopyToVM(ctx, localPath, vmPath); err != nil {+ return fmt.Errorf("failed to copy checkpoint to VM: %w", err)+ }+ defer c.RemoveVMFile(ctx, vmPath)++ return c.RestoreContainer(ctx, vmPath, name)+ }++ tmpDir, err := os.MkdirTemp("", "osb-restore-")+ if err != nil {+ return fmt.Errorf("failed to create temp dir: %w", err)+ }+ defer os.RemoveAll(tmpDir)++ fifoPath := filepath.Join(tmpDir, "checkpoint.tar.zst")+ if err := syscall.Mkfifo(fifoPath, 0600); err != nil {+ return fmt.Errorf("failed to create FIFO: %w", err)+ }++ // Start podman restore reading from the FIFO (blocks until data is available)+ errCh := make(chan error, 1)+ go func() {+ errCh <- c.RestoreContainer(ctx, fifoPath, name)+ }()++ // Open FIFO for writing and copy stream data into it+ fifo, err := os.OpenFile(fifoPath, os.O_WRONLY, 0)+ if err != nil {+ return fmt.Errorf("failed to open FIFO for writing: %w", err)+ }+ if _, err := io.Copy(fifo, reader); err != nil {+ fifo.Close()+ return fmt.Errorf("failed to stream checkpoint to FIFO: %w", err)+ }+ fifo.Close() // Signal EOF to podman++ // Wait for podman restore to complete+ return <-errCh+}+// Version returns the podman version string.func (c *Client) Version(ctx context.Context) (string, error) {result, err := c.Run(ctx, "version", "--format", "{{.Client.Version}}")diff --git a/internal/podman/container.go b/internal/podman/container.goindex 979973b6..b96eea99 100644--- a/internal/podman/container.go+++ b/internal/podman/container.go@@ -37,10 +37,8 @@ func DefaultContainerConfig(name, image string) ContainerConfig {CPUs: "1",PidsLimit: 256,NetworkMode: "none",- ReadOnly: true,- TmpFS: map[string]string{- "/tmp": "rw,size=100m",- },+ ReadOnly: false,+ TmpFS: map[string]string{},CapDrop: []string{"ALL"},SecurityOpts: []string{"no-new-privileges"},UserNS: "",diff --git a/internal/sandbox/hibernate.go b/internal/sandbox/hibernate.gonew file mode 100644index 00000000..6c6eacd1--- /dev/null+++ b/internal/sandbox/hibernate.go@@ -0,0 +1,122 @@+package sandbox++import (+ "context"+ "fmt"+ "os"+ "path/filepath"+ "time"++ "github.com/opensandbox/opensandbox/internal/podman"+ "github.com/opensandbox/opensandbox/internal/storage"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// HibernateResult holds the result of a hibernate operation.+type HibernateResult struct {+ SandboxID string `json:"sandboxId"`+ CheckpointKey string `json:"checkpointKey"`+ SizeBytes int64 `json:"sizeBytes"`+}++// Hibernate checkpoints a running sandbox, uploads to S3, and removes the container.+func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (*HibernateResult, error) {+ name := m.ContainerName(sandboxID)++ // 1. Trim memory before checkpoint (best-effort)+ m.trimBeforeCheckpoint(ctx, name)++ // 2. Checkpoint to temp file with zstd compression+ tmpDir, err := os.MkdirTemp("", "osb-checkpoint-")+ if err != nil {+ return nil, fmt.Errorf("failed to create temp dir: %w", err)+ }+ defer os.RemoveAll(tmpDir)+ localPath := filepath.Join(tmpDir, "checkpoint.tar.zst")++ if m.podman.UseSSH() {+ // On macOS: checkpoint inside VM, then copy archive to host for S3 upload+ vmPath := fmt.Sprintf("/tmp/osb-checkpoint-%s.tar.zst", sandboxID)+ if err := m.podman.CheckpointContainer(ctx, name, vmPath); err != nil {+ return nil, fmt.Errorf("checkpoint failed for sandbox %s: %w", sandboxID, err)+ }+ defer m.podman.RemoveVMFile(ctx, vmPath)++ if err := m.podman.CopyFromVM(ctx, vmPath, localPath); err != nil {+ return nil, fmt.Errorf("failed to copy checkpoint from VM for sandbox %s: %w", sandboxID, err)+ }+ } else {+ // On Linux: checkpoint directly to local path+ if err := m.podman.CheckpointContainer(ctx, name, localPath); err != nil {+ return nil, fmt.Errorf("checkpoint failed for sandbox %s: %w", sandboxID, err)+ }+ }++ // 3. Upload to S3+ s3Key := storage.CheckpointKey(sandboxID)+ sizeBytes, err := checkpointStore.Upload(ctx, s3Key, localPath)+ if err != nil {+ return nil, fmt.Errorf("failed to upload checkpoint for sandbox %s: %w", sandboxID, err)+ }++ // 4. Remove the container (checkpoint --export already stopped it)+ m.cancelTimeout(sandboxID)+ _ = m.podman.RemoveContainer(ctx, name, true)++ return &HibernateResult{+ SandboxID: sandboxID,+ CheckpointKey: s3Key,+ SizeBytes: sizeBytes,+ }, nil+}++// Wake restores a hibernated sandbox from its S3 checkpoint.+// The checkpoint is streamed directly into podman restore.+func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error) {+ name := m.ContainerName(sandboxID)++ // 1. Download checkpoint as a stream from S3+ reader, err := checkpointStore.Download(ctx, checkpointKey)+ if err != nil {+ return nil, fmt.Errorf("failed to download checkpoint for sandbox %s: %w", sandboxID, err)+ }+ defer reader.Close()++ // 2. Stream restore via FIFO+ if err := m.podman.RestoreContainerFromStream(ctx, reader, name); err != nil {+ 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+ info, err := m.podman.InspectContainer(ctx, name)+ if err != nil {+ return nil, fmt.Errorf("failed to inspect restored sandbox %s: %w", sandboxID, err)+ }++ return containerInfoToSandbox(info), nil+}++// trimBeforeCheckpoint reduces the container's memory footprint before checkpointing.+// Best-effort: errors are ignored since the container may lack permissions.+func (m *Manager) trimBeforeCheckpoint(ctx context.Context, containerName string) {+ trimCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()++ commands := [][]string{+ {"/bin/sh", "-c", "sync"},+ {"/bin/sh", "-c", "echo 3 > /proc/sys/vm/drop_caches 2>/dev/null || true"},+ }++ for _, cmd := range commands {+ _, _ = m.podman.ExecInContainer(trimCtx, podman.ExecConfig{+ Container: containerName,+ Command: cmd,+ })+ }+}diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.goindex 93985754..b2e71479 100644--- a/internal/sandbox/manager.go+++ b/internal/sandbox/manager.go@@ -3,12 +3,14 @@ package sandboximport ("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,9 +30,11 @@ const (// Manager handles sandbox lifecycle operations.type Manager struct {- podman *podman.Client- mu sync.RWMutex- timers map[string]*time.Timer // sandbox ID -> timeout timer+ 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}// NewManager creates a new sandbox manager.@@ -41,6 +45,17 @@ func NewManager(client *podman.Client) *Manager {}}+// 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]@@ -199,9 +214,26 @@ func (m *Manager) scheduleTimeout(id, name string, d time.Duration) {}m.timers[id] = time.AfterFunc(d, func() {- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()- _ = m.podman.RemoveContainer(ctx, name, true)+ // 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)diff --git a/internal/storage/s3.go b/internal/storage/s3.gonew file mode 100644index 00000000..e0a39d44--- /dev/null+++ b/internal/storage/s3.go@@ -0,0 +1,111 @@+package storage++import (+ "context"+ "fmt"+ "io"+ "os"+ "time"++ "github.com/aws/aws-sdk-go-v2/aws"+ "github.com/aws/aws-sdk-go-v2/credentials"+ "github.com/aws/aws-sdk-go-v2/service/s3"+)++// S3Config holds the configuration for the S3 storage backend.+type S3Config struct {+ Endpoint string+ Bucket string+ Region string+ AccessKeyID string+ SecretAccessKey string+ ForcePathStyle bool+}++// CheckpointStore manages checkpoint archives in S3-compatible object storage.+type CheckpointStore struct {+ client *s3.Client+ bucket string+}++// NewCheckpointStore creates a new S3 checkpoint store.+func NewCheckpointStore(cfg S3Config) (*CheckpointStore, error) {+ opts := []func(*s3.Options){+ func(o *s3.Options) {+ o.Region = cfg.Region+ o.Credentials = credentials.NewStaticCredentialsProvider(+ cfg.AccessKeyID, cfg.SecretAccessKey, "",+ )+ if cfg.ForcePathStyle {+ o.UsePathStyle = true+ }+ if cfg.Endpoint != "" {+ o.BaseEndpoint = aws.String(cfg.Endpoint)+ }+ },+ }++ client := s3.New(s3.Options{}, opts...)++ return &CheckpointStore{+ client: client,+ bucket: cfg.Bucket,+ }, nil+}++// CheckpointKey returns the S3 key for a checkpoint archive.+func CheckpointKey(sandboxID string) string {+ return fmt.Sprintf("checkpoints/%s/%d.tar.zst", sandboxID, time.Now().UnixNano())+}++// Upload uploads a checkpoint archive from a local file to S3.+// Returns the size in bytes.+func (s *CheckpointStore) Upload(ctx context.Context, key, localPath string) (int64, error) {+ f, err := os.Open(localPath)+ if err != nil {+ return 0, fmt.Errorf("failed to open checkpoint file: %w", err)+ }+ defer f.Close()++ stat, err := f.Stat()+ if err != nil {+ return 0, fmt.Errorf("failed to stat checkpoint file: %w", err)+ }++ _, err = s.client.PutObject(ctx, &s3.PutObjectInput{+ Bucket: aws.String(s.bucket),+ Key: aws.String(key),+ Body: f,+ ContentLength: aws.Int64(stat.Size()),+ })+ if err != nil {+ return 0, fmt.Errorf("failed to upload checkpoint to S3: %w", err)+ }++ return stat.Size(), nil+}++// Download returns an io.ReadCloser streaming the checkpoint from S3.+// The caller must close the reader when done.+func (s *CheckpointStore) Download(ctx context.Context, key string) (io.ReadCloser, error) {+ resp, err := s.client.GetObject(ctx, &s3.GetObjectInput{+ Bucket: aws.String(s.bucket),+ Key: aws.String(key),+ })+ if err != nil {+ return nil, fmt.Errorf("failed to download checkpoint from S3: %w", err)+ }+ return resp.Body, nil+}++// Delete removes a checkpoint archive from S3.+func (s *CheckpointStore) Delete(ctx context.Context, key string) error {+ _, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{+ Bucket: aws.String(s.bucket),+ Key: aws.String(key),+ })+ if err != nil {+ return fmt.Errorf("failed to delete checkpoint from S3: %w", err)+ }+ return nil+}diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex fa0464de..32e2e2a0 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -8,6 +8,7 @@ import ("google.golang.org/grpc""github.com/opensandbox/opensandbox/internal/sandbox"+ "github.com/opensandbox/opensandbox/internal/storage""github.com/opensandbox/opensandbox/pkg/types"pb "github.com/opensandbox/opensandbox/proto/worker")@@ -15,19 +16,21 @@ import (// GRPCServer implements the SandboxWorker gRPC service for control plane communication.type GRPCServer struct {pb.UnimplementedSandboxWorkerServer- manager *sandbox.Manager- ptyManager *sandbox.PTYManager- sandboxDBs *sandbox.SandboxDBManager- server *grpc.Server+ manager *sandbox.Manager+ ptyManager *sandbox.PTYManager+ sandboxDBs *sandbox.SandboxDBManager+ checkpointStore *storage.CheckpointStore+ server *grpc.Server}// NewGRPCServer creates a new gRPC server wrapping the sandbox manager.-func NewGRPCServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager) *GRPCServer {+func NewGRPCServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore) *GRPCServer {s := &GRPCServer{- manager: mgr,- ptyManager: ptyMgr,- sandboxDBs: sandboxDBs,- server: grpc.NewServer(),+ manager: mgr,+ ptyManager: ptyMgr,+ sandboxDBs: sandboxDBs,+ checkpointStore: checkpointStore,+ server: grpc.NewServer(),}pb.RegisterSandboxWorkerServer(s.server, s)return s@@ -208,3 +211,51 @@ func (s *GRPCServer) CreatePTY(ctx context.Context, req *pb.CreatePTYRequest) (*func (s *GRPCServer) PTYStream(_ pb.SandboxWorker_PTYStreamServer) error {return fmt.Errorf("PTY streaming not implemented via gRPC, use WebSocket API directly")}++func (s *GRPCServer) HibernateSandbox(ctx context.Context, req *pb.HibernateSandboxRequest) (*pb.HibernateSandboxResponse, error) {+ if s.checkpointStore == nil {+ return nil, fmt.Errorf("hibernation not configured on this worker")+ }++ result, err := s.manager.Hibernate(ctx, req.SandboxId, s.checkpointStore)+ if err != nil {+ return nil, fmt.Errorf("failed to hibernate sandbox: %w", err)+ }++ // Clean up per-sandbox SQLite+ if s.sandboxDBs != nil {+ _ = s.sandboxDBs.Remove(req.SandboxId)+ }++ return &pb.HibernateSandboxResponse{+ SandboxId: result.SandboxID,+ CheckpointKey: result.CheckpointKey,+ SizeBytes: result.SizeBytes,+ }, nil+}++func (s *GRPCServer) WakeSandbox(ctx context.Context, req *pb.WakeSandboxRequest) (*pb.WakeSandboxResponse, error) {+ if s.checkpointStore == nil {+ return nil, fmt.Errorf("hibernation not configured on this worker")+ }++ sb, err := s.manager.Wake(ctx, req.SandboxId, req.CheckpointKey, s.checkpointStore, int(req.Timeout))+ if err != nil {+ return nil, fmt.Errorf("failed to wake sandbox: %w", err)+ }++ // Re-initialize per-sandbox SQLite+ if s.sandboxDBs != nil {+ sdb, err := s.sandboxDBs.Get(sb.ID)+ if err == nil {+ _ = sdb.LogEvent("woke", map[string]string{+ "sandbox_id": sb.ID,+ })+ }+ }++ return &pb.WakeSandboxResponse{+ SandboxId: sb.ID,+ Status: string(sb.Status),+ }, nil+}diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.goindex ea9bd839..17e1ded7 100644--- a/pkg/types/sandbox.go+++ b/pkg/types/sandbox.go@@ -6,9 +6,10 @@ import "time"type SandboxStatus stringconst (- SandboxStatusRunning SandboxStatus = "running"- SandboxStatusStopped SandboxStatus = "stopped"- SandboxStatusError SandboxStatus = "error"+ SandboxStatusRunning SandboxStatus = "running"+ SandboxStatusStopped SandboxStatus = "stopped"+ SandboxStatusError SandboxStatus = "error"+ SandboxStatusHibernated SandboxStatus = "hibernated")// Sandbox represents a running sandbox instance.@@ -49,3 +50,18 @@ type SandboxListResponse struct {type TimeoutRequest struct {Timeout int `json:"timeout"` // seconds}++// CheckpointInfo holds metadata about a hibernated sandbox's checkpoint.+type CheckpointInfo struct {+ SandboxID string `json:"sandboxId"`+ CheckpointKey string `json:"checkpointKey"`+ SizeBytes int64 `json:"sizeBytes"`+ Region string `json:"region"`+ Template string `json:"template"`+ HibernatedAt time.Time `json:"hibernatedAt"`+}++// WakeRequest is the request body for waking a hibernated sandbox.+type WakeRequest struct {+ Timeout int `json:"timeout,omitempty"` // new timeout in seconds after wake+}diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.goindex a66605d5..a2549f72 100644--- a/proto/worker/worker.pb.go+++ b/proto/worker/worker.pb.go@@ -1,7 +1,7 @@// Code generated by protoc-gen-go. DO NOT EDIT.// versions:// protoc-gen-go v1.36.11-// protoc v5.29.3+// protoc v6.33.4// source: proto/worker/worker.protopackage worker@@ -1341,6 +1341,222 @@ func (x *PTYOutput) GetData() []byte {return nil}+type HibernateSandboxRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *HibernateSandboxRequest) Reset() {+ *x = HibernateSandboxRequest{}+ mi := &file_proto_worker_worker_proto_msgTypes[23]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *HibernateSandboxRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*HibernateSandboxRequest) ProtoMessage() {}++func (x *HibernateSandboxRequest) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[23]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use HibernateSandboxRequest.ProtoReflect.Descriptor instead.+func (*HibernateSandboxRequest) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{23}+}++func (x *HibernateSandboxRequest) GetSandboxId() string {+ if x != nil {+ return x.SandboxId+ }+ return ""+}++type HibernateSandboxResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`+ CheckpointKey string `protobuf:"bytes,2,opt,name=checkpoint_key,json=checkpointKey,proto3" json:"checkpoint_key,omitempty"`+ SizeBytes int64 `protobuf:"varint,3,opt,name=size_bytes,json=sizeBytes,proto3" json:"size_bytes,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *HibernateSandboxResponse) Reset() {+ *x = HibernateSandboxResponse{}+ mi := &file_proto_worker_worker_proto_msgTypes[24]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *HibernateSandboxResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*HibernateSandboxResponse) ProtoMessage() {}++func (x *HibernateSandboxResponse) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[24]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use HibernateSandboxResponse.ProtoReflect.Descriptor instead.+func (*HibernateSandboxResponse) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{24}+}++func (x *HibernateSandboxResponse) GetSandboxId() string {+ if x != nil {+ return x.SandboxId+ }+ return ""+}++func (x *HibernateSandboxResponse) GetCheckpointKey() string {+ if x != nil {+ return x.CheckpointKey+ }+ return ""+}++func (x *HibernateSandboxResponse) GetSizeBytes() int64 {+ if x != nil {+ return x.SizeBytes+ }+ return 0+}++type WakeSandboxRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`+ CheckpointKey string `protobuf:"bytes,2,opt,name=checkpoint_key,json=checkpointKey,proto3" json:"checkpoint_key,omitempty"`+ Timeout int32 `protobuf:"varint,3,opt,name=timeout,proto3" json:"timeout,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *WakeSandboxRequest) Reset() {+ *x = WakeSandboxRequest{}+ mi := &file_proto_worker_worker_proto_msgTypes[25]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *WakeSandboxRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*WakeSandboxRequest) ProtoMessage() {}++func (x *WakeSandboxRequest) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[25]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use WakeSandboxRequest.ProtoReflect.Descriptor instead.+func (*WakeSandboxRequest) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{25}+}++func (x *WakeSandboxRequest) GetSandboxId() string {+ if x != nil {+ return x.SandboxId+ }+ return ""+}++func (x *WakeSandboxRequest) GetCheckpointKey() string {+ if x != nil {+ return x.CheckpointKey+ }+ return ""+}++func (x *WakeSandboxRequest) GetTimeout() int32 {+ if x != nil {+ return x.Timeout+ }+ return 0+}++type WakeSandboxResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`+ Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *WakeSandboxResponse) Reset() {+ *x = WakeSandboxResponse{}+ mi := &file_proto_worker_worker_proto_msgTypes[26]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *WakeSandboxResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*WakeSandboxResponse) ProtoMessage() {}++func (x *WakeSandboxResponse) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[26]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use WakeSandboxResponse.ProtoReflect.Descriptor instead.+func (*WakeSandboxResponse) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{26}+}++func (x *WakeSandboxResponse) GetSandboxId() string {+ if x != nil {+ return x.SandboxId+ }+ return ""+}++func (x *WakeSandboxResponse) GetStatus() string {+ if x != nil {+ return x.Status+ }+ return ""+}+var File_proto_worker_worker_proto protoreflect.FileDescriptorconst file_proto_worker_worker_proto_rawDesc = "" +@@ -1445,7 +1661,25 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\tPTYOutput\x12\x1d\n" +"\n" +"session_id\x18\x01 \x01(\tR\tsessionId\x12\x12\n" +- "\x04data\x18\x02 \x01(\fR\x04data2\x8a\x06\n" ++ "\x04data\x18\x02 \x01(\fR\x04data\"8\n" ++ "\x17HibernateSandboxRequest\x12\x1d\n" ++ "\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\"\x7f\n" ++ "\x18HibernateSandboxResponse\x12\x1d\n" ++ "\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12%\n" ++ "\x0echeckpoint_key\x18\x02 \x01(\tR\rcheckpointKey\x12\x1d\n" ++ "\n" ++ "size_bytes\x18\x03 \x01(\x03R\tsizeBytes\"t\n" ++ "\x12WakeSandboxRequest\x12\x1d\n" ++ "\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12%\n" ++ "\x0echeckpoint_key\x18\x02 \x01(\tR\rcheckpointKey\x12\x18\n" ++ "\atimeout\x18\x03 \x01(\x05R\atimeout\"L\n" ++ "\x13WakeSandboxResponse\x12\x1d\n" ++ "\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x16\n" ++ "\x06status\x18\x02 \x01(\tR\x06status2\xa9\a\n" +"\rSandboxWorker\x12L\n" +"\rCreateSandbox\x12\x1c.worker.CreateSandboxRequest\x1a\x1d.worker.CreateSandboxResponse\x12O\n" +"\x0eDestroySandbox\x12\x1d.worker.DestroySandboxRequest\x1a\x1e.worker.DestroySandboxResponse\x12C\n" +@@ -1458,7 +1692,9 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\tWriteFile\x12\x18.worker.WriteFileRequest\x1a\x19.worker.WriteFileResponse\x12:\n" +"\aListDir\x12\x16.worker.ListDirRequest\x1a\x17.worker.ListDirResponse\x12@\n" +"\tCreatePTY\x12\x18.worker.CreatePTYRequest\x1a\x19.worker.CreatePTYResponse\x124\n" +- "\tPTYStream\x12\x10.worker.PTYInput\x1a\x11.worker.PTYOutput(\x010\x01B1Z/github.com/opensandbox/opensandbox/proto/workerb\x06proto3"+ "\tPTYStream\x12\x10.worker.PTYInput\x1a\x11.worker.PTYOutput(\x010\x01\x12U\n" ++ "\x10HibernateSandbox\x12\x1f.worker.HibernateSandboxRequest\x1a .worker.HibernateSandboxResponse\x12F\n" ++ "\vWakeSandbox\x12\x1a.worker.WakeSandboxRequest\x1a\x1b.worker.WakeSandboxResponseB1Z/github.com/opensandbox/opensandbox/proto/workerb\x06proto3"var (file_proto_worker_worker_proto_rawDescOnce sync.Once@@ -1473,39 +1709,43 @@ func file_proto_worker_worker_proto_rawDescGZIP() []byte {}var file_proto_worker_worker_proto_enumTypes = make([]protoimpl.EnumInfo, 1)-var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 25)+var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 29)var file_proto_worker_worker_proto_goTypes = []any{- (ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream- (*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest- (*CreateSandboxResponse)(nil), // 2: worker.CreateSandboxResponse- (*DestroySandboxRequest)(nil), // 3: worker.DestroySandboxRequest- (*DestroySandboxResponse)(nil), // 4: worker.DestroySandboxResponse- (*GetSandboxRequest)(nil), // 5: worker.GetSandboxRequest- (*GetSandboxResponse)(nil), // 6: worker.GetSandboxResponse- (*ListSandboxesRequest)(nil), // 7: worker.ListSandboxesRequest- (*ListSandboxesResponse)(nil), // 8: worker.ListSandboxesResponse- (*ExecCommandRequest)(nil), // 9: worker.ExecCommandRequest- (*ExecCommandResponse)(nil), // 10: worker.ExecCommandResponse- (*ExecOutputChunk)(nil), // 11: worker.ExecOutputChunk- (*ReadFileRequest)(nil), // 12: worker.ReadFileRequest- (*ReadFileResponse)(nil), // 13: worker.ReadFileResponse- (*WriteFileRequest)(nil), // 14: worker.WriteFileRequest- (*WriteFileResponse)(nil), // 15: worker.WriteFileResponse- (*ListDirRequest)(nil), // 16: worker.ListDirRequest- (*DirEntry)(nil), // 17: worker.DirEntry- (*ListDirResponse)(nil), // 18: worker.ListDirResponse- (*CreatePTYRequest)(nil), // 19: worker.CreatePTYRequest- (*CreatePTYResponse)(nil), // 20: worker.CreatePTYResponse- (*PTYInput)(nil), // 21: worker.PTYInput- (*PTYResize)(nil), // 22: worker.PTYResize- (*PTYOutput)(nil), // 23: worker.PTYOutput- nil, // 24: worker.CreateSandboxRequest.EnvsEntry- nil, // 25: worker.ExecCommandRequest.EnvsEntry+ (ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream+ (*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest+ (*CreateSandboxResponse)(nil), // 2: worker.CreateSandboxResponse+ (*DestroySandboxRequest)(nil), // 3: worker.DestroySandboxRequest+ (*DestroySandboxResponse)(nil), // 4: worker.DestroySandboxResponse+ (*GetSandboxRequest)(nil), // 5: worker.GetSandboxRequest+ (*GetSandboxResponse)(nil), // 6: worker.GetSandboxResponse+ (*ListSandboxesRequest)(nil), // 7: worker.ListSandboxesRequest+ (*ListSandboxesResponse)(nil), // 8: worker.ListSandboxesResponse+ (*ExecCommandRequest)(nil), // 9: worker.ExecCommandRequest+ (*ExecCommandResponse)(nil), // 10: worker.ExecCommandResponse+ (*ExecOutputChunk)(nil), // 11: worker.ExecOutputChunk+ (*ReadFileRequest)(nil), // 12: worker.ReadFileRequest+ (*ReadFileResponse)(nil), // 13: worker.ReadFileResponse+ (*WriteFileRequest)(nil), // 14: worker.WriteFileRequest+ (*WriteFileResponse)(nil), // 15: worker.WriteFileResponse+ (*ListDirRequest)(nil), // 16: worker.ListDirRequest+ (*DirEntry)(nil), // 17: worker.DirEntry+ (*ListDirResponse)(nil), // 18: worker.ListDirResponse+ (*CreatePTYRequest)(nil), // 19: worker.CreatePTYRequest+ (*CreatePTYResponse)(nil), // 20: worker.CreatePTYResponse+ (*PTYInput)(nil), // 21: worker.PTYInput+ (*PTYResize)(nil), // 22: worker.PTYResize+ (*PTYOutput)(nil), // 23: worker.PTYOutput+ (*HibernateSandboxRequest)(nil), // 24: worker.HibernateSandboxRequest+ (*HibernateSandboxResponse)(nil), // 25: worker.HibernateSandboxResponse+ (*WakeSandboxRequest)(nil), // 26: worker.WakeSandboxRequest+ (*WakeSandboxResponse)(nil), // 27: worker.WakeSandboxResponse+ nil, // 28: worker.CreateSandboxRequest.EnvsEntry+ nil, // 29: worker.ExecCommandRequest.EnvsEntry}var file_proto_worker_worker_proto_depIdxs = []int32{- 24, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry+ 28, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry6, // 1: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse- 25, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry+ 29, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry0, // 3: worker.ExecOutputChunk.stream:type_name -> worker.ExecOutputChunk.Stream17, // 4: worker.ListDirResponse.entries:type_name -> worker.DirEntry22, // 5: worker.PTYInput.resize:type_name -> worker.PTYResize@@ -1520,19 +1760,23 @@ var file_proto_worker_worker_proto_depIdxs = []int32{16, // 14: worker.SandboxWorker.ListDir:input_type -> worker.ListDirRequest19, // 15: worker.SandboxWorker.CreatePTY:input_type -> worker.CreatePTYRequest21, // 16: worker.SandboxWorker.PTYStream:input_type -> worker.PTYInput- 2, // 17: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse- 4, // 18: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse- 6, // 19: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse- 8, // 20: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse- 10, // 21: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse- 11, // 22: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk- 13, // 23: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse- 15, // 24: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse- 18, // 25: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse- 20, // 26: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse- 23, // 27: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput- 17, // [17:28] is the sub-list for method output_type- 6, // [6:17] is the sub-list for method input_type+ 24, // 17: worker.SandboxWorker.HibernateSandbox:input_type -> worker.HibernateSandboxRequest+ 26, // 18: worker.SandboxWorker.WakeSandbox:input_type -> worker.WakeSandboxRequest+ 2, // 19: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse+ 4, // 20: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse+ 6, // 21: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse+ 8, // 22: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse+ 10, // 23: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse+ 11, // 24: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk+ 13, // 25: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse+ 15, // 26: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse+ 18, // 27: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse+ 20, // 28: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse+ 23, // 29: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput+ 25, // 30: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse+ 27, // 31: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse+ 19, // [19:32] is the sub-list for method output_type+ 6, // [6:19] is the sub-list for method input_type6, // [6:6] is the sub-list for extension type_name6, // [6:6] is the sub-list for extension extendee0, // [0:6] is the sub-list for field type_name@@ -1553,7 +1797,7 @@ func file_proto_worker_worker_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_worker_worker_proto_rawDesc), len(file_proto_worker_worker_proto_rawDesc)),NumEnums: 1,- NumMessages: 25,+ NumMessages: 29,NumExtensions: 0,NumServices: 1,},diff --git a/proto/worker/worker.proto b/proto/worker/worker.protoindex 696dd79f..0ed2ec31 100644--- a/proto/worker/worker.proto+++ b/proto/worker/worker.proto@@ -19,6 +19,9 @@ service SandboxWorker {rpc CreatePTY(CreatePTYRequest) returns (CreatePTYResponse);rpc PTYStream(stream PTYInput) returns (stream PTYOutput);++ rpc HibernateSandbox(HibernateSandboxRequest) returns (HibernateSandboxResponse);+ rpc WakeSandbox(WakeSandboxRequest) returns (WakeSandboxResponse);}message CreateSandboxRequest {@@ -144,3 +147,24 @@ message PTYOutput {string session_id = 1;bytes data = 2;}++message HibernateSandboxRequest {+ string sandbox_id = 1;+}++message HibernateSandboxResponse {+ string sandbox_id = 1;+ string checkpoint_key = 2;+ int64 size_bytes = 3;+}++message WakeSandboxRequest {+ string sandbox_id = 1;+ string checkpoint_key = 2;+ int32 timeout = 3;+}++message WakeSandboxResponse {+ string sandbox_id = 1;+ string status = 2;+}diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.goindex df5a73b7..5fc8353d 100644--- a/proto/worker/worker_grpc.pb.go+++ b/proto/worker/worker_grpc.pb.go@@ -1,7 +1,7 @@// Code generated by protoc-gen-go-grpc. DO NOT EDIT.// versions:// - protoc-gen-go-grpc v1.6.1-// - protoc v5.29.3+// - protoc v6.33.4// source: proto/worker/worker.protopackage worker@@ -30,6 +30,8 @@ const (SandboxWorker_ListDir_FullMethodName = "/worker.SandboxWorker/ListDir"SandboxWorker_CreatePTY_FullMethodName = "/worker.SandboxWorker/CreatePTY"SandboxWorker_PTYStream_FullMethodName = "/worker.SandboxWorker/PTYStream"+ SandboxWorker_HibernateSandbox_FullMethodName = "/worker.SandboxWorker/HibernateSandbox"+ SandboxWorker_WakeSandbox_FullMethodName = "/worker.SandboxWorker/WakeSandbox")// SandboxWorkerClient is the client API for SandboxWorker service.@@ -47,6 +49,8 @@ type SandboxWorkerClient interface {ListDir(ctx context.Context, in *ListDirRequest, opts ...grpc.CallOption) (*ListDirResponse, error)CreatePTY(ctx context.Context, in *CreatePTYRequest, opts ...grpc.CallOption) (*CreatePTYResponse, error)PTYStream(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[PTYInput, PTYOutput], error)+ HibernateSandbox(ctx context.Context, in *HibernateSandboxRequest, opts ...grpc.CallOption) (*HibernateSandboxResponse, error)+ WakeSandbox(ctx context.Context, in *WakeSandboxRequest, opts ...grpc.CallOption) (*WakeSandboxResponse, error)}type sandboxWorkerClient struct {@@ -179,6 +183,26 @@ func (c *sandboxWorkerClient) PTYStream(ctx context.Context, opts ...grpc.CallOp// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.type SandboxWorker_PTYStreamClient = grpc.BidiStreamingClient[PTYInput, PTYOutput]+func (c *sandboxWorkerClient) HibernateSandbox(ctx context.Context, in *HibernateSandboxRequest, opts ...grpc.CallOption) (*HibernateSandboxResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(HibernateSandboxResponse)+ err := c.cc.Invoke(ctx, SandboxWorker_HibernateSandbox_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *sandboxWorkerClient) WakeSandbox(ctx context.Context, in *WakeSandboxRequest, opts ...grpc.CallOption) (*WakeSandboxResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(WakeSandboxResponse)+ err := c.cc.Invoke(ctx, SandboxWorker_WakeSandbox_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+// SandboxWorkerServer is the server API for SandboxWorker service.// All implementations must embed UnimplementedSandboxWorkerServer// for forward compatibility.@@ -194,6 +218,8 @@ type SandboxWorkerServer interface {ListDir(context.Context, *ListDirRequest) (*ListDirResponse, error)CreatePTY(context.Context, *CreatePTYRequest) (*CreatePTYResponse, error)PTYStream(grpc.BidiStreamingServer[PTYInput, PTYOutput]) error+ HibernateSandbox(context.Context, *HibernateSandboxRequest) (*HibernateSandboxResponse, error)+ WakeSandbox(context.Context, *WakeSandboxRequest) (*WakeSandboxResponse, error)mustEmbedUnimplementedSandboxWorkerServer()}@@ -237,6 +263,12 @@ func (UnimplementedSandboxWorkerServer) CreatePTY(context.Context, *CreatePTYReqfunc (UnimplementedSandboxWorkerServer) PTYStream(grpc.BidiStreamingServer[PTYInput, PTYOutput]) error {return status.Error(codes.Unimplemented, "method PTYStream not implemented")}+func (UnimplementedSandboxWorkerServer) HibernateSandbox(context.Context, *HibernateSandboxRequest) (*HibernateSandboxResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method HibernateSandbox not implemented")+}+func (UnimplementedSandboxWorkerServer) WakeSandbox(context.Context, *WakeSandboxRequest) (*WakeSandboxResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method WakeSandbox not implemented")+}func (UnimplementedSandboxWorkerServer) mustEmbedUnimplementedSandboxWorkerServer() {}func (UnimplementedSandboxWorkerServer) testEmbeddedByValue() {}@@ -438,6 +470,42 @@ func _SandboxWorker_PTYStream_Handler(srv interface{}, stream grpc.ServerStream)// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.type SandboxWorker_PTYStreamServer = grpc.BidiStreamingServer[PTYInput, PTYOutput]+func _SandboxWorker_HibernateSandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(HibernateSandboxRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SandboxWorkerServer).HibernateSandbox(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SandboxWorker_HibernateSandbox_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SandboxWorkerServer).HibernateSandbox(ctx, req.(*HibernateSandboxRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _SandboxWorker_WakeSandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(WakeSandboxRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SandboxWorkerServer).WakeSandbox(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SandboxWorker_WakeSandbox_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SandboxWorkerServer).WakeSandbox(ctx, req.(*WakeSandboxRequest))+ }+ return interceptor(ctx, in, info, handler)+}+// SandboxWorker_ServiceDesc is the grpc.ServiceDesc for SandboxWorker service.// It's only intended for direct use with grpc.RegisterService,// and not to be introspected or modified (even as a copy)@@ -481,6 +549,14 @@ var SandboxWorker_ServiceDesc = grpc.ServiceDesc{MethodName: "CreatePTY",Handler: _SandboxWorker_CreatePTY_Handler,},+ {+ MethodName: "HibernateSandbox",+ Handler: _SandboxWorker_HibernateSandbox_Handler,+ },+ {+ MethodName: "WakeSandbox",+ Handler: _SandboxWorker_WakeSandbox_Handler,+ },},Streams: []grpc.StreamDesc{{diff --git a/scripts/test-hibernation.sh b/scripts/test-hibernation.shnew file mode 100755index 00000000..b2094aba--- /dev/null+++ b/scripts/test-hibernation.sh@@ -0,0 +1,171 @@+#!/usr/bin/env bash+set -euo pipefail++# Test hibernation: file persistence, process preservation, and timing+# Usage: ./scripts/test-hibernation.sh [api_url] [api_key]++API_URL="${1:-http://localhost:8080}"+API_KEY="${2:-test-key}"+PASS=0+FAIL=0++green() { printf "\033[32m%s\033[0m\n" "$*"; }+red() { printf "\033[31m%s\033[0m\n" "$*"; }+yellow() { printf "\033[33m%s\033[0m\n" "$*"; }+bold() { printf "\033[1m%s\033[0m\n" "$*"; }++check() {+ local desc="$1" expected="$2" actual="$3"+ if [[ "$actual" == *"$expected"* ]]; then+ green " PASS: $desc"+ PASS=$((PASS + 1))+ else+ red " FAIL: $desc (expected '$expected', got '$actual')"+ FAIL=$((FAIL + 1))+ fi+}++api() {+ local method="$1" path="$2" body="${3:-}"+ if [[ -n "$body" ]]; then+ curl -s -X "$method" "${API_URL}${path}" \+ -H "X-API-Key: ${API_KEY}" \+ -H "Content-Type: application/json" \+ -d "$body"+ else+ curl -s -X "$method" "${API_URL}${path}" \+ -H "X-API-Key: ${API_KEY}"+ fi+}++run_cmd() {+ local sandbox_id="$1" cmd="$2"+ 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..."+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');" \+ 2>/dev/null | grep -q "UPDATE" && green " Cleaned up stale sessions" || yellow " No stale sessions"+echo ""++# --- Create sandbox ---+bold "[1/7] 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+ red "Failed to create sandbox: $CREATE_RESP"+ exit 1+fi+green " Created sandbox: $SANDBOX_ID"+echo ""++# --- Write file state ---+bold "[2/7] 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++# Verify files exist+PROOF=$(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=$(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=$(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)+check "/tmp/proof.txt before hibernate" "hibernation-proof-42" "$PROOF"+check "/root/hello.txt before hibernate" "hello-world" "$HELLO"+check "/var/data/test.txt before hibernate" "persistent-data" "$DATA"+echo ""++# --- Check PID 1 process ---+bold "[3/7] 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..."+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())')+HIBERNATE_DURATION=$(python3 -c "print(f'{${HIB_END} - ${HIB_START}:.3f}')")+yellow " TIME: Hibernate = ${HIBERNATE_DURATION}s"++HIB_KEY=$(echo "$HIB_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('checkpointKey',''))" 2>/dev/null)+HIB_SIZE=$(echo "$HIB_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'{d.get(\"sizeBytes\",0)/1024/1024:.1f}MB')" 2>/dev/null)+if [[ -n "$HIB_KEY" ]]; then+ green " Checkpoint: $HIB_KEY ($HIB_SIZE)"+else+ red " Hibernate failed: $HIB_RESP"+fi++CONTAINER_CHECK=$(podman ps --format '{{.Names}}' 2>/dev/null | grep "osb-${SANDBOX_ID}" || true)+check "Container removed after hibernate" "" "$CONTAINER_CHECK"+echo ""++# --- Wake ---+bold "[5/7] Waking sandbox..."+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())')+WAKE_DURATION=$(python3 -c "print(f'{${WAKE_END} - ${WAKE_START}:.3f}')")+yellow " TIME: Wake = ${WAKE_DURATION}s"++WAKE_STATUS=$(echo "$WAKE_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null)+check "Wake status" "running" "$WAKE_STATUS"+echo ""++# --- Verify file state ---+bold "[6/7] 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)+check "/tmp/proof.txt after wake" "hibernation-proof-42" "$PROOF_AFTER"+check "/root/hello.txt after wake" "hello-world" "$HELLO_AFTER"+check "/var/data/test.txt after wake" "persistent-data" "$DATA_AFTER"+echo ""++# --- Verify process state ---+bold "[7/7] 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")+check "PID 1 still exists after wake" "yes" "$PID1_EXISTS"++# Verify we can still run commands (container is functional)+ECHO_TEST=$(run_cmd "$SANDBOX_ID" "echo alive" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null || echo "dead")+check "Container is functional after wake" "alive" "$ECHO_TEST"+echo ""++# --- Cleanup ---+bold "Cleaning up..."+api POST "/api/sandboxes/${SANDBOX_ID}/commands" '{"cmd": "kill", "args": ["1"]}' > /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 "========================================="++if [[ $FAIL -gt 0 ]]; then+ exit 1+fi