An open-source, faster Devin alternative
TypeScript
Add save-as-template feature for creating templates from running sandboxes
Brian Reardon3cccc342975f
diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex e61ef3f2..a1bd7736 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -241,7 +241,7 @@ func main() {}// Start gRPC server for control plane communication- grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr, checkpointStore, sbRouter, builder)+ grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr, checkpointStore, sbRouter, builder, store)grpcAddr := ":9090"log.Printf("opensandbox-worker: starting gRPC server on %s", grpcAddr)go func() {diff --git a/internal/api/dashboard.go b/internal/api/dashboard.goindex 4497ed98..c43899cf 100644--- a/internal/api/dashboard.go+++ b/internal/api/dashboard.go@@ -456,20 +456,25 @@ func (s *Server) dashboardListTemplates(c echo.Context) error {})}- // Strip internal image refs from dashboard response+ // Strip internal fields from dashboard responsetype safeTemplate struct {- ID uuid.UUID `json:"id"`- OrgID *uuid.UUID `json:"orgId,omitempty"`- Name string `json:"name"`- Tag string `json:"tag"`- IsPublic bool `json:"isPublic"`- CreatedAt time.Time `json:"createdAt"`+ ID uuid.UUID `json:"id"`+ OrgID *uuid.UUID `json:"orgId,omitempty"`+ Name string `json:"name"`+ Tag string `json:"tag"`+ IsPublic bool `json:"isPublic"`+ TemplateType string `json:"templateType"`+ CreatedBySandboxID *string `json:"createdBySandboxId,omitempty"`+ Status string `json:"status"`+ CreatedAt time.Time `json:"createdAt"`}safe := make([]safeTemplate, len(templates))for i, t := range templates {safe[i] = safeTemplate{ID: t.ID, OrgID: t.OrgID, Name: t.Name,- Tag: t.Tag, IsPublic: t.IsPublic, CreatedAt: t.CreatedAt,+ Tag: t.Tag, IsPublic: t.IsPublic,+ TemplateType: t.TemplateType, CreatedBySandboxID: t.CreatedBySandboxID,+ Status: t.Status, CreatedAt: t.CreatedAt,}}@@ -513,6 +518,139 @@ func (s *Server) dashboardDeleteTemplate(c echo.Context) error {return c.NoContent(http.StatusNoContent)}+// dashboardSaveAsTemplate snapshots a running sandbox's drives and creates a new template record.+// The VM is briefly paused on the worker while drives are copied, then resumed.+// The S3 upload and template DB record creation happen in the same call (upload is async on the worker).+func (s *Server) dashboardSaveAsTemplate(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "database not configured",+ })+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{+ "error": "org context required",+ })+ }++ sandboxID := c.Param("sandboxId")+ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{+ "error": "session not found",+ })+ }+ if session.OrgID != orgID {+ return c.JSON(http.StatusForbidden, map[string]string{+ "error": "session does not belong to this organization",+ })+ }+ if session.Status != "running" {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "sandbox must be running to save as template",+ })+ }++ var req struct {+ Name string `json:"name"`+ Tag string `json:"tag"`+ }+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "invalid request body",+ })+ }+ if req.Name == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "name is required",+ })+ }+ if req.Tag == "" {+ req.Tag = "latest"+ }++ ctx := c.Request().Context()++ // Reserve a template UUID upfront so the worker can use it for S3 key naming.+ templateID := uuid.New()++ // Dispatch SaveAsTemplate gRPC call to the worker that owns the sandbox.+ var rootfsKey, workspaceKey string+ if s.workerRegistry != nil {+ grpcClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)+ if err != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "worker not available: " + err.Error(),+ })+ }++ // Give 2 minutes: SyncFS + pause + file copy + resume (upload is async on the worker)+ grpcCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)+ defer cancel()++ resp, err := grpcClient.SaveAsTemplate(grpcCtx, &pb.SaveAsTemplateRequest{+ SandboxId: sandboxID,+ TemplateId: templateID.String(),+ })+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "save-as-template failed: " + err.Error(),+ })+ }+ rootfsKey = resp.RootfsS3Key+ workspaceKey = resp.WorkspaceS3Key+ } else if s.manager != nil {+ // Combined/worker mode: call directly+ if s.checkpointStore == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "checkpoint store not configured",+ })+ }+ onReady := func() {+ if err := s.store.SetTemplateReady(context.Background(), templateID); err != nil {+ log.Printf("dashboard: failed to mark template %s ready: %v", templateID, err)+ } else {+ log.Printf("dashboard: template %s is now ready", templateID)+ }+ }+ rootfsKey, workspaceKey, err = s.manager.SaveAsTemplate(ctx, sandboxID, templateID.String(), s.checkpointStore, onReady)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "save-as-template failed: " + err.Error(),+ })+ }+ } else {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "no sandbox manager available",+ })+ }++ // Create template record in DB (status=processing for sandbox templates)+ tmpl, err := s.store.CreateSandboxTemplate(ctx, templateID, &orgID, req.Name, req.Tag, rootfsKey, workspaceKey, sandboxID)+ if err != nil {+ log.Printf("dashboard: template snapshot succeeded but DB insert failed for sandbox %s: %v", sandboxID, err)+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "failed to save template record: " + err.Error(),+ })+ }++ // Label the sandbox session with the new template+ _ = s.store.UpdateSandboxSessionTemplate(ctx, sandboxID, tmpl.ID)++ log.Printf("dashboard: saved sandbox %s as template %s (%s)", sandboxID, tmpl.Name, tmpl.ID)++ return c.JSON(http.StatusCreated, map[string]interface{}{+ "id": tmpl.ID,+ "name": tmpl.Name,+ "tag": tmpl.Tag,+ "templateType": tmpl.TemplateType,+ "status": tmpl.Status,+ "createdAt": tmpl.CreatedAt,+ })+}+// dashboardGetSession returns detailed info for a single session.func (s *Server) dashboardGetSession(c echo.Context) error {if s.store == nil {diff --git a/internal/api/router.go b/internal/api/router.goindex 44955600..578ace77 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -152,6 +152,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.GET("/templates", s.listTemplates)api.GET("/templates/:name", s.getTemplate)api.DELETE("/templates/:name", s.deleteTemplate)+ api.POST("/sandboxes/:sandboxId/save-as-template", s.dashboardSaveAsTemplate)// Workers (server mode only — queries worker registry)api.GET("/workers", s.listWorkers)@@ -193,6 +194,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o// Session detail + statsdash.GET("/sessions/:sandboxId", s.dashboardGetSession)dash.GET("/sessions/:sandboxId/stats", s.dashboardGetSessionStats)+ dash.POST("/sessions/:sandboxId/save-as-template", s.dashboardSaveAsTemplate)// PTY (terminal)dash.POST("/sessions/:sandboxId/pty", s.dashboardCreatePTY)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 648b68f6..e217261c 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -147,26 +147,45 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty// Resolve template image from DB (org-scoped lookup with public fallback)var imageRef string+ var templateRootfsKey, templateWorkspaceKey string+ var templateID *uuid.UUIDif s.store != nil && hasOrg {tmpl, err := s.store.GetTemplateByName(ctx, orgID, cfg.Template)if err == nil {imageRef = tmpl.ImageRef+ templateID = &tmpl.ID+ log.Printf("sandbox: resolved template %q (type=%s, id=%s)", cfg.Template, tmpl.TemplateType, tmpl.ID)+ // Sandbox-type templates provide S3 drive keys instead of ECR image refs+ if tmpl.TemplateType == "sandbox" && tmpl.RootfsS3Key != nil && tmpl.WorkspaceS3Key != nil {+ templateRootfsKey = *tmpl.RootfsS3Key+ templateWorkspaceKey = *tmpl.WorkspaceS3Key+ log.Printf("sandbox: using snapshot template drives: rootfs=%s, workspace=%s", templateRootfsKey, templateWorkspaceKey)+ }+ } else {+ log.Printf("sandbox: template %q lookup failed: %v", cfg.Template, err)}}- // Dispatch via persistent gRPC connection- grpcCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ // Dispatch via persistent gRPC connection.+ // Template-based creation needs more time for S3 download + decompression of drives.+ grpcTimeout := 30 * time.Second+ if templateRootfsKey != "" {+ grpcTimeout = 120 * time.Second+ }+ grpcCtx, cancel := context.WithTimeout(ctx, grpcTimeout)defer cancel()grpcResp, err := grpcClient.CreateSandbox(grpcCtx, &pb.CreateSandboxRequest{- Template: cfg.Template,- Timeout: int32(cfg.Timeout),- Envs: cfg.Envs,- MemoryMb: int32(cfg.MemoryMB),- CpuCount: int32(cfg.CpuCount),- NetworkEnabled: cfg.NetworkEnabled,- ImageRef: imageRef,- Port: int32(cfg.Port),+ Template: cfg.Template,+ Timeout: int32(cfg.Timeout),+ Envs: cfg.Envs,+ MemoryMb: int32(cfg.MemoryMB),+ CpuCount: int32(cfg.CpuCount),+ NetworkEnabled: cfg.NetworkEnabled,+ ImageRef: imageRef,+ Port: int32(cfg.Port),+ TemplateRootfsKey: templateRootfsKey,+ TemplateWorkspaceKey: templateWorkspaceKey,})if err != nil {return c.JSON(http.StatusInternalServerError, map[string]string{@@ -194,6 +213,9 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg tycfgJSON, _ := json.Marshal(cfg)metadataJSON, _ := json.Marshal(cfg.Metadata)_, _ = s.store.CreateSandboxSession(ctx, grpcResp.SandboxId, orgID, nil, template, region, worker.ID, cfgJSON, metadataJSON)+ if templateID != nil {+ _ = s.store.UpdateSandboxSessionTemplate(ctx, grpcResp.SandboxId, *templateID)+ }}resp := map[string]interface{}{diff --git a/internal/db/migrations/009_sandbox_templates.up.sql b/internal/db/migrations/009_sandbox_templates.up.sqlnew file mode 100644index 00000000..cefdcaab--- /dev/null+++ b/internal/db/migrations/009_sandbox_templates.up.sql@@ -0,0 +1,14 @@+-- Extend templates table for sandbox snapshot templates.+-- Adds template_type ('dockerfile' vs 'sandbox'), S3 keys for snapshot templates,+-- and tracks which sandbox was the source.+ALTER TABLE templates ADD COLUMN IF NOT EXISTS template_type TEXT NOT NULL DEFAULT 'dockerfile';+ALTER TABLE templates ADD COLUMN IF NOT EXISTS rootfs_s3_key TEXT;+ALTER TABLE templates ADD COLUMN IF NOT EXISTS workspace_s3_key TEXT;+ALTER TABLE templates ADD COLUMN IF NOT EXISTS created_by_sandbox_id TEXT;++-- Make image_ref optional (snapshot templates don't have a Docker image ref).+ALTER TABLE templates ALTER COLUMN image_ref DROP NOT NULL;+ALTER TABLE templates ALTER COLUMN image_ref SET DEFAULT '';++-- Track which template a sandbox session was based on (set when creating from a snapshot template).+ALTER TABLE sandbox_sessions ADD COLUMN IF NOT EXISTS based_on_template_id UUID REFERENCES templates(id);diff --git a/internal/db/migrations/010_template_status.up.sql b/internal/db/migrations/010_template_status.up.sqlnew file mode 100644index 00000000..3f945205--- /dev/null+++ b/internal/db/migrations/010_template_status.up.sql@@ -0,0 +1,2 @@+-- Add status column to templates (processing while snapshot is being prepared, ready when usable)+ALTER TABLE templates ADD COLUMN IF NOT EXISTS status text NOT NULL DEFAULT 'ready';diff --git a/internal/db/store.go b/internal/db/store.goindex ecfc8c3c..314d9cda 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -72,6 +72,8 @@ func (s *Store) Migrate(ctx context.Context) error {{6, "migrations/006_sandbox_preview_urls.up.sql"},{7, "migrations/007_preview_urls_port.up.sql"},{8, "migrations/008_default_template.up.sql"},+ {9, "migrations/009_sandbox_templates.up.sql"},+ {10, "migrations/010_template_status.up.sql"},}for _, m := range migrations {@@ -732,42 +734,95 @@ func (s *Store) UpsertWorkspaceBackup(ctx context.Context, sandboxID string, org// DBTemplate represents a template record in the database.type DBTemplate struct {- ID uuid.UUID `json:"id"`- OrgID *uuid.UUID `json:"orgId,omitempty"`- Name string `json:"name"`- Tag string `json:"tag"`- ImageRef string `json:"imageRef"`- Dockerfile *string `json:"dockerfile,omitempty"`- IsPublic bool `json:"isPublic"`- CreatedAt time.Time `json:"createdAt"`+ ID uuid.UUID `json:"id"`+ OrgID *uuid.UUID `json:"orgId,omitempty"`+ Name string `json:"name"`+ Tag string `json:"tag"`+ ImageRef string `json:"-"`+ Dockerfile *string `json:"dockerfile,omitempty"`+ IsPublic bool `json:"isPublic"`+ TemplateType string `json:"templateType"` // "dockerfile" or "sandbox"+ RootfsS3Key *string `json:"-"`+ WorkspaceS3Key *string `json:"-"`+ CreatedBySandboxID *string `json:"createdBySandboxId,omitempty"`+ Status string `json:"status"` // "ready" or "processing"+ CreatedAt time.Time `json:"createdAt"`}-// CreateTemplate inserts a new template record.+// templateColumns is the standard column list for template queries.+const templateColumns = `id, org_id, name, tag, COALESCE(image_ref,''), dockerfile, is_public, template_type, rootfs_s3_key, workspace_s3_key, created_by_sandbox_id, COALESCE(status,'ready'), created_at`++func scanTemplate(row interface{ Scan(...any) error }, t *DBTemplate) error {+ return row.Scan(&t.ID, &t.OrgID, &t.Name, &t.Tag, &t.ImageRef, &t.Dockerfile, &t.IsPublic, &t.TemplateType, &t.RootfsS3Key, &t.WorkspaceS3Key, &t.CreatedBySandboxID, &t.Status, &t.CreatedAt)+}++// CreateTemplate inserts a new dockerfile-based template record.func (s *Store) CreateTemplate(ctx context.Context, orgID *uuid.UUID, name, tag, imageRef string, dockerfile *string, isPublic bool) (*DBTemplate, error) {t := &DBTemplate{}- err := s.pool.QueryRow(ctx,- `INSERT INTO templates (org_id, name, tag, image_ref, dockerfile, is_public)- VALUES ($1, $2, $3, $4, $5, $6)- RETURNING id, org_id, name, tag, image_ref, dockerfile, is_public, created_at`,+ err := scanTemplate(s.pool.QueryRow(ctx,+ `INSERT INTO templates (org_id, name, tag, image_ref, dockerfile, is_public, template_type)+ VALUES ($1, $2, $3, $4, $5, $6, 'dockerfile')+ RETURNING `+templateColumns,orgID, name, tag, imageRef, dockerfile, isPublic,- ).Scan(&t.ID, &t.OrgID, &t.Name, &t.Tag, &t.ImageRef, &t.Dockerfile, &t.IsPublic, &t.CreatedAt)+ ), t)if err != nil {return nil, fmt.Errorf("failed to create template: %w", err)}return t, nil}+// CreateSandboxTemplate inserts a new sandbox-snapshot template record (status=processing).+func (s *Store) CreateSandboxTemplate(ctx context.Context, id uuid.UUID, orgID *uuid.UUID, name, tag, rootfsS3Key, workspaceS3Key, createdBySandboxID string) (*DBTemplate, error) {+ t := &DBTemplate{}+ err := scanTemplate(s.pool.QueryRow(ctx,+ `INSERT INTO templates (id, org_id, name, tag, image_ref, is_public, template_type, rootfs_s3_key, workspace_s3_key, created_by_sandbox_id, status)+ VALUES ($1, $2, $3, $4, '', false, 'sandbox', $5, $6, $7, 'processing')+ RETURNING `+templateColumns,+ id, orgID, name, tag, rootfsS3Key, workspaceS3Key, createdBySandboxID,+ ), t)+ if err != nil {+ return nil, fmt.Errorf("failed to create sandbox template: %w", err)+ }+ return t, nil+}++// SetTemplateReady marks a template as ready for use.+func (s *Store) SetTemplateReady(ctx context.Context, id uuid.UUID) error {+ _, err := s.pool.Exec(ctx, `UPDATE templates SET status = 'ready' WHERE id = $1`, id)+ return err+}++// GetTemplateByID finds a template by its UUID.+func (s *Store) GetTemplateByID(ctx context.Context, id uuid.UUID) (*DBTemplate, error) {+ t := &DBTemplate{}+ err := scanTemplate(s.pool.QueryRow(ctx,+ `SELECT `+templateColumns+` FROM templates WHERE id = $1`, id,+ ), t)+ if err != nil {+ return nil, fmt.Errorf("template %s not found: %w", id, err)+ }+ return t, nil+}++// UpdateSandboxSessionTemplate sets the based_on_template_id for a sandbox session.+func (s *Store) UpdateSandboxSessionTemplate(ctx context.Context, sandboxID string, templateID uuid.UUID) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_sessions SET based_on_template_id = $1 WHERE sandbox_id = $2`,+ templateID, sandboxID)+ return err+}+// GetTemplateByName finds a template by name, preferring org-specific over public.func (s *Store) GetTemplateByName(ctx context.Context, orgID uuid.UUID, name string) (*DBTemplate, error) {t := &DBTemplate{}- err := s.pool.QueryRow(ctx,- `SELECT id, org_id, name, tag, image_ref, dockerfile, is_public, created_at+ err := scanTemplate(s.pool.QueryRow(ctx,+ `SELECT `+templateColumns+`FROM templatesWHERE name = $1 AND (org_id = $2 OR (is_public = true AND org_id IS NULL))ORDER BY org_id IS NULL ASCLIMIT 1`,name, orgID,- ).Scan(&t.ID, &t.OrgID, &t.Name, &t.Tag, &t.ImageRef, &t.Dockerfile, &t.IsPublic, &t.CreatedAt)+ ), t)if err != nil {return nil, fmt.Errorf("template %q not found: %w", name, err)}@@ -777,7 +832,7 @@ func (s *Store) GetTemplateByName(ctx context.Context, orgID uuid.UUID, name str// ListTemplates returns all templates visible to an org (org-specific + public).func (s *Store) ListTemplates(ctx context.Context, orgID uuid.UUID) ([]DBTemplate, error) {rows, err := s.pool.Query(ctx,- `SELECT id, org_id, name, tag, image_ref, dockerfile, is_public, created_at+ `SELECT `+templateColumns+`FROM templatesWHERE org_id = $1 OR (is_public = true AND org_id IS NULL)ORDER BY is_public DESC, name ASC`,@@ -790,7 +845,7 @@ func (s *Store) ListTemplates(ctx context.Context, orgID uuid.UUID) ([]DBTemplatvar templates []DBTemplatefor rows.Next() {var t DBTemplate- if err := rows.Scan(&t.ID, &t.OrgID, &t.Name, &t.Tag, &t.ImageRef, &t.Dockerfile, &t.IsPublic, &t.CreatedAt); err != nil {+ if err := scanTemplate(rows, &t); err != nil {return nil, err}templates = append(templates, t)diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.goindex 120ffb03..7108fd63 100644--- a/internal/firecracker/manager.go+++ b/internal/firecracker/manager.go@@ -153,30 +153,46 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sreturn nil, fmt.Errorf("mkdir sandbox dir: %w", err)}- // Resolve base image+ // Resolve template name (used for logging and cold-boot recovery)template := cfg.Template- if template == "" {- template = "ubuntu"- }- baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, template)- if err != nil {- os.RemoveAll(sandboxDir)- return nil, fmt.Errorf("resolve base image: %w", err)+ if template == "" || template == "base" {+ template = "default"}- // Prepare rootfs (reflink copy)rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")- if err := PrepareRootfs(baseImage, rootfsPath); err != nil {- os.RemoveAll(sandboxDir)- return nil, fmt.Errorf("prepare rootfs: %w", err)- }-- // Create workspace- diskMB := m.cfg.DefaultDiskMBworkspacePath := filepath.Join(sandboxDir, "workspace.ext4")- if err := CreateWorkspace(workspacePath, diskMB); err != nil {- os.RemoveAll(sandboxDir)- return nil, fmt.Errorf("create workspace: %w", err)++ if cfg.TemplateRootfsKey != "" {+ // Sandbox snapshot template: gRPC handler extracted template drives to local paths+ // encoded as "local://<absolute-path>" in TemplateRootfsKey / TemplateWorkspaceKey.+ srcRootfs := strings.TrimPrefix(cfg.TemplateRootfsKey, "local://")+ srcWorkspace := strings.TrimPrefix(cfg.TemplateWorkspaceKey, "local://")+ log.Printf("firecracker: create %s from snapshot template (rootfs=%s, workspace=%s)", id, srcRootfs, srcWorkspace)+ if err := copyFileReflink(srcRootfs, rootfsPath); err != nil {+ os.RemoveAll(sandboxDir)+ return nil, fmt.Errorf("copy template rootfs: %w", err)+ }+ if err := copyFileReflink(srcWorkspace, workspacePath); err != nil {+ os.RemoveAll(sandboxDir)+ return nil, fmt.Errorf("copy template workspace: %w", err)+ }+ } else {+ // Standard base image + fresh workspace+ baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, template)+ if err != nil {+ os.RemoveAll(sandboxDir)+ return nil, fmt.Errorf("resolve base image: %w", err)+ }+ if err := PrepareRootfs(baseImage, rootfsPath); err != nil {+ os.RemoveAll(sandboxDir)+ return nil, fmt.Errorf("prepare rootfs: %w", err)+ }++ diskMB := m.cfg.DefaultDiskMB+ if err := CreateWorkspace(workspacePath, diskMB); err != nil {+ os.RemoveAll(sandboxDir)+ return nil, fmt.Errorf("create workspace: %w", err)+ }}// Allocate network@@ -786,6 +802,15 @@ func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey strireturn m.doWake(ctx, sandboxID, checkpointKey, checkpointStore, timeout)}+// SaveAsTemplate snapshots a running sandbox's drives for use as a template.+func (m *Manager) SaveAsTemplate(ctx context.Context, sandboxID, templateID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error) {+ vm, err := m.getVM(sandboxID)+ if err != nil {+ return "", "", err+ }+ return m.doSaveAsTemplate(ctx, vm, templateID, checkpointStore, onReady)+}+// getVM retrieves a VM by ID (read-locked).func (m *Manager) getVM(id string) (*VMInstance, error) {m.mu.RLock()diff --git a/internal/firecracker/snapshot.go b/internal/firecracker/snapshot.goindex c13ce4a5..dce29f89 100644--- a/internal/firecracker/snapshot.go+++ b/internal/firecracker/snapshot.go@@ -13,6 +13,7 @@ import ("time""github.com/opensandbox/opensandbox/internal/sandbox"+ "github.com/opensandbox/opensandbox/internal/sparse""github.com/opensandbox/opensandbox/internal/storage""github.com/opensandbox/opensandbox/pkg/types")@@ -708,3 +709,186 @@ func fileExists(path string) bool {info, err := os.Stat(path)return err == nil && !info.IsDir()}++// --- Save as Template ---++// doSaveAsTemplate snapshots a running sandbox's drives for use as a reusable template.+// The VM is briefly paused while the drives are copied, then resumed. The user's sandbox+// continues running uninterrupted; the copied drives are compressed and uploaded to S3 async.+//+// Template drives are cached locally at {DataDir}/templates/{templateID}/ so that creating+// new sandboxes from this template is a fast reflink copy (no S3 download needed on the+// same worker). S3 is the durable backup for cross-worker use.+//+// Flow:+// 1. SyncFS via agent (flush disk buffers — agent stays alive)+// 2. Close gRPC connection (vsock must be inactive for pause)+// 3. Pause VM+// 4. Copy rootfs.ext4 and workspace.ext4 to template cache dir (reflink — instant on XFS)+// 5. Resume VM+// 6. Reconnect agent+// 7. (async) Compress cached drives → upload to S3 (cache stays on disk)+func (m *Manager) doSaveAsTemplate(ctx context.Context, vm *VMInstance, templateID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error) {+ t0 := time.Now()++ rootfsKey = fmt.Sprintf("templates/%s/rootfs.tar.zst", templateID)+ workspaceKey = fmt.Sprintf("templates/%s/workspace.sparse.zst", templateID)++ srcRootfs := filepath.Join(vm.sandboxDir, "rootfs.ext4")+ srcWorkspace := filepath.Join(vm.sandboxDir, "workspace.ext4")++ // Cache template drives locally for fast reflink-based creation+ cacheDir := m.templateCacheDir(templateID)+ if err := os.MkdirAll(cacheDir, 0755); err != nil {+ return "", "", fmt.Errorf("create template cache dir: %w", err)+ }+ cachedRootfs := filepath.Join(cacheDir, "rootfs.ext4")+ cachedWorkspace := filepath.Join(cacheDir, "workspace.ext4")++ // Step 1: SyncFS (agent stays alive — only the gRPC connection needs to be closed for pause)+ if vm.agent != nil {+ syncCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ if syncErr := vm.agent.SyncFS(syncCtx); syncErr != nil {+ log.Printf("firecracker: SaveAsTemplate %s: SyncFS warning: %v", vm.ID, syncErr)+ }+ cancel()+ }++ // Step 2: Close gRPC connection (vsock must be inactive before Firecracker pause)+ if vm.agent != nil {+ vm.agent.Close()+ vm.agent = nil+ }++ // Step 3: Pause the VM+ if err = vm.fcClient.PauseVM(); err != nil {+ // Try to reconnect agent even on error so the VM stays usable+ if agent, reconnErr := m.waitForAgent(ctx, vm.vsockPath, 5*time.Second); reconnErr == nil {+ vm.agent = agent+ }+ os.RemoveAll(cacheDir)+ return "", "", fmt.Errorf("pause VM for template snapshot: %w", err)+ }+ log.Printf("firecracker: SaveAsTemplate %s: VM paused (%dms)", vm.ID, time.Since(t0).Milliseconds())++ // Step 4: Copy drive files while VM is paused (drives are stable)+ copyErr := copyFileReflink(srcRootfs, cachedRootfs)+ if copyErr == nil {+ copyErr = copyFileReflink(srcWorkspace, cachedWorkspace)+ if copyErr != nil {+ os.Remove(cachedRootfs)+ }+ }++ // Step 5: Resume the VM regardless of copy result+ resumeErr := vm.fcClient.ResumeVM()+ if resumeErr != nil {+ log.Printf("firecracker: SaveAsTemplate %s: CRITICAL: resume failed: %v", vm.ID, resumeErr)+ os.RemoveAll(cacheDir)+ return "", "", fmt.Errorf("resume VM after template snapshot: %w", resumeErr)+ }+ log.Printf("firecracker: SaveAsTemplate %s: VM resumed (%dms)", vm.ID, time.Since(t0).Milliseconds())++ if copyErr != nil {+ // Reconnect agent since VM is running again+ if agent, reconnErr := m.waitForAgent(ctx, vm.vsockPath, 10*time.Second); reconnErr == nil {+ vm.agent = agent+ }+ os.RemoveAll(cacheDir)+ return "", "", fmt.Errorf("copy drives for template: %w", copyErr)+ }++ // Step 6: Reconnect agent (it was running inside the VM the whole time — just paused)+ agent, reconnErr := m.waitForAgent(ctx, vm.vsockPath, 10*time.Second)+ if reconnErr != nil {+ log.Printf("firecracker: SaveAsTemplate %s: agent reconnect failed: %v (VM still running)", vm.ID, reconnErr)+ } else {+ vm.agent = agent+ }++ // Step 7: Async compress + upload (cached drives stay on disk for fast local creation)+ sandboxID := vm.ID+ m.uploadWg.Add(1)+ go func() {+ defer m.uploadWg.Done()++ uploadCtx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)+ defer cancel()++ t1 := time.Now()+ if err := compressAndUploadFile(uploadCtx, cachedRootfs, rootfsKey, checkpointStore); err != nil {+ log.Printf("firecracker: template %s: rootfs upload failed for sandbox %s: %v", templateID, sandboxID, err)+ return+ }+ log.Printf("firecracker: template %s: rootfs uploaded (%dms)", templateID, time.Since(t1).Milliseconds())++ t2 := time.Now()+ if err := sparseCompressAndUpload(uploadCtx, cachedWorkspace, workspaceKey, checkpointStore); err != nil {+ log.Printf("firecracker: template %s: workspace upload failed for sandbox %s: %v", templateID, sandboxID, err)+ return+ }+ log.Printf("firecracker: template %s: ready (%dms, total=%dms)", templateID, time.Since(t2).Milliseconds(), time.Since(t0).Milliseconds())+ if onReady != nil {+ onReady()+ }+ }()++ return rootfsKey, workspaceKey, nil+}++// templateCacheDir returns the local cache directory for a template's ext4 drives.+func (m *Manager) templateCacheDir(templateID string) string {+ return filepath.Join(m.cfg.DataDir, "templates", templateID)+}++// TemplateCachePath returns the local path to a cached template drive, or "" if not cached.+func (m *Manager) TemplateCachePath(templateID, filename string) string {+ p := filepath.Join(m.templateCacheDir(templateID), filename)+ if _, err := os.Stat(p); err == nil {+ return p+ }+ return ""+}++// copyFileReflink copies a file using cp --reflink=auto (instant on XFS reflink, fallback to full copy).+func copyFileReflink(src, dst string) error {+ cmd := exec.Command("cp", "--reflink=auto", src, dst)+ if out, err := cmd.CombinedOutput(); err != nil {+ return fmt.Errorf("cp %s → %s: %w (%s)", src, dst, err, strings.TrimSpace(string(out)))+ }+ return nil+}++// sparseCompressAndUpload creates a sparse archive of a file and uploads it to S3.+// Only non-zero 4KB blocks are stored, making archive size proportional to actual content.+func sparseCompressAndUpload(ctx context.Context, srcPath, s3Key string, store *storage.CheckpointStore) error {+ archivePath := srcPath + ".sparse.zst"+ blocks, err := sparse.Create(srcPath, archivePath)+ if err != nil {+ return fmt.Errorf("sparse compress: %w", err)+ }+ defer os.Remove(archivePath)++ info, _ := os.Stat(archivePath)+ log.Printf("firecracker: sparse archive %s: %d non-zero blocks, %d KB compressed",+ filepath.Base(srcPath), blocks, info.Size()/1024)++ if _, err := store.Upload(ctx, s3Key, archivePath); err != nil {+ return fmt.Errorf("upload to %s: %w", s3Key, err)+ }+ return nil+}++// compressAndUploadFile compresses a single file as a tar.zst archive and uploads it to S3.+func compressAndUploadFile(ctx context.Context, srcPath, s3Key string, store *storage.CheckpointStore) error {+ archivePath := srcPath + ".tar.zst"+ if err := createArchive(archivePath, filepath.Dir(srcPath), []string{filepath.Base(srcPath)}); err != nil {+ return fmt.Errorf("compress: %w", err)+ }+ defer os.Remove(archivePath)++ if _, err := store.Upload(ctx, s3Key, archivePath); err != nil {+ return fmt.Errorf("upload to %s: %w", s3Key, err)+ }+ return nil+}diff --git a/internal/sandbox/hibernate.go b/internal/sandbox/hibernate.goindex 48022564..ba1d2256 100644--- a/internal/sandbox/hibernate.go+++ b/internal/sandbox/hibernate.go@@ -351,3 +351,13 @@ func dirExists(path string) bool {info, err := os.Stat(path)return err == nil && info.IsDir()}++// SaveAsTemplate is not supported on the Podman backend (Firecracker only).+func (m *PodmanManager) SaveAsTemplate(_ context.Context, _, _ string, _ *storage.CheckpointStore, _ func()) (string, string, error) {+ return "", "", fmt.Errorf("save-as-template is only supported on Firecracker backend")+}++// TemplateCachePath always returns "" on the Podman backend (Firecracker only).+func (m *PodmanManager) TemplateCachePath(_, _ string) string {+ return ""+}diff --git a/internal/sandbox/interface.go b/internal/sandbox/interface.goindex a42fb45a..7668528f 100644--- a/internal/sandbox/interface.go+++ b/internal/sandbox/interface.go@@ -55,4 +55,13 @@ type Manager interface {// HibernationHibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (*HibernateResult, error)Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error)++ // SaveAsTemplate snapshots a running sandbox's drives (rootfs + workspace) for use as a+ // template. The VM is briefly paused during file copy then resumed. Archive upload is async.+ // Returns the pre-computed storage keys immediately. onReady is called when the async upload finishes (may be nil).+ SaveAsTemplate(ctx context.Context, sandboxID, templateID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error)++ // TemplateCachePath returns the local path to a cached template drive file (e.g., "rootfs.ext4"),+ // or "" if the template is not cached locally. Used to skip S3 download when creating from template.+ TemplateCachePath(templateID, filename string) string}diff --git a/internal/sparse/sparse.go b/internal/sparse/sparse.gonew file mode 100644index 00000000..91594b16--- /dev/null+++ b/internal/sparse/sparse.go@@ -0,0 +1,198 @@+// Package sparse implements a block-level sparse file archive format.+//+// Large ext4 disk images (e.g., 20GB workspace.ext4) are mostly zeros (sparse).+// tar.zst compresses well but on extraction writes the full 20GB — slow.+// This format stores only non-zero 4KB blocks with their offsets, making both+// archive size and restore time proportional to actual content, not disk size.+//+// Format (.sparse.zst):+// - All data is wrapped in a zstd stream+// - Header: magic [8]byte "OSBSPAR1" + fileSize uint64 (little-endian)+// - Blocks: repeated (offset uint64 + data [4096]byte) for each non-zero block+// - EOF: end of zstd stream+//+// Restore:+// 1. truncate file to fileSize (instant — creates sparse file)+// 2. Read blocks, pwrite each at its offset (only writes real data)+package sparse++import (+ "encoding/binary"+ "fmt"+ "io"+ "log"+ "os"+ "time"++ "github.com/klauspost/compress/zstd"+)++const (+ BlockSize = 4096+ Magic = "OSBSPAR1"+)++// Create scans srcPath for non-zero blocks and writes a sparse archive to dstPath.+// Returns the number of non-zero blocks written.+func Create(srcPath, dstPath string) (int, error) {+ src, err := os.Open(srcPath)+ if err != nil {+ return 0, fmt.Errorf("open source: %w", err)+ }+ defer src.Close()++ info, err := src.Stat()+ if err != nil {+ return 0, fmt.Errorf("stat source: %w", err)+ }+ fileSize := uint64(info.Size())++ dst, err := os.Create(dstPath)+ if err != nil {+ return 0, fmt.Errorf("create archive: %w", err)+ }+ defer dst.Close()++ zw, err := zstd.NewWriter(dst, zstd.WithEncoderLevel(zstd.SpeedDefault))+ if err != nil {+ return 0, fmt.Errorf("create zstd writer: %w", err)+ }++ // Write header: magic + file size+ if _, err := zw.Write([]byte(Magic)); err != nil {+ zw.Close()+ return 0, fmt.Errorf("write magic: %w", err)+ }+ var sizeBuf [8]byte+ binary.LittleEndian.PutUint64(sizeBuf[:], fileSize)+ if _, err := zw.Write(sizeBuf[:]); err != nil {+ zw.Close()+ return 0, fmt.Errorf("write file size: %w", err)+ }++ // Scan blocks+ buf := make([]byte, BlockSize)+ var offsetBuf [8]byte+ blocks := 0+ var offset uint64++ for offset = 0; offset < fileSize; offset += BlockSize {+ n, err := io.ReadFull(src, buf)+ if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF {+ zw.Close()+ return 0, fmt.Errorf("read block at offset %d: %w", offset, err)+ }+ if n == 0 {+ break+ }++ // Check if block is all zeros+ if isZero(buf[:n]) {+ continue+ }++ // Write offset + data+ binary.LittleEndian.PutUint64(offsetBuf[:], offset)+ if _, err := zw.Write(offsetBuf[:]); err != nil {+ zw.Close()+ return 0, fmt.Errorf("write offset: %w", err)+ }+ if _, err := zw.Write(buf[:n]); err != nil {+ zw.Close()+ return 0, fmt.Errorf("write block data: %w", err)+ }+ blocks+++ }++ if err := zw.Close(); err != nil {+ return 0, fmt.Errorf("close zstd: %w", err)+ }+ return blocks, nil+}++// Restore reads a sparse archive and reconstructs the original file at dstPath.+// The file is created as a sparse file (truncated to full size, only non-zero blocks written).+func Restore(archivePath, dstPath string) error {+ t0 := time.Now()++ src, err := os.Open(archivePath)+ if err != nil {+ return fmt.Errorf("open archive: %w", err)+ }+ defer src.Close()++ zr, err := zstd.NewReader(src)+ if err != nil {+ return fmt.Errorf("create zstd reader: %w", err)+ }+ defer zr.Close()++ // Read header+ var header [8]byte+ if _, err := io.ReadFull(zr, header[:]); err != nil {+ return fmt.Errorf("read magic: %w", err)+ }+ if string(header[:]) != Magic {+ return fmt.Errorf("invalid magic: %q (expected %q)", header[:], Magic)+ }++ var sizeBuf [8]byte+ if _, err := io.ReadFull(zr, sizeBuf[:]); err != nil {+ return fmt.Errorf("read file size: %w", err)+ }+ fileSize := binary.LittleEndian.Uint64(sizeBuf[:])++ // Create sparse file+ dst, err := os.Create(dstPath)+ if err != nil {+ return fmt.Errorf("create output file: %w", err)+ }+ defer dst.Close()++ if err := dst.Truncate(int64(fileSize)); err != nil {+ return fmt.Errorf("truncate to %d: %w", fileSize, err)+ }++ // Read and write blocks+ var offsetBuf [8]byte+ buf := make([]byte, BlockSize)+ blocks := 0++ for {+ // Read offset+ _, err := io.ReadFull(zr, offsetBuf[:])+ if err == io.EOF || err == io.ErrUnexpectedEOF {+ break+ }+ if err != nil {+ return fmt.Errorf("read block offset: %w", err)+ }+ offset := binary.LittleEndian.Uint64(offsetBuf[:])++ // Read block data+ n, err := io.ReadFull(zr, buf)+ if err != nil && err != io.ErrUnexpectedEOF {+ return fmt.Errorf("read block data at offset %d: %w", offset, err)+ }++ // Write at offset (pwrite — doesn't affect file position for other blocks)+ if _, err := dst.WriteAt(buf[:n], int64(offset)); err != nil {+ return fmt.Errorf("write block at offset %d: %w", offset, err)+ }+ blocks+++ }++ log.Printf("sparse: restored %s (%d blocks, %d MB apparent, %dms)",+ dstPath, blocks, fileSize/1024/1024, time.Since(t0).Milliseconds())+ return nil+}++// isZero returns true if all bytes in b are zero.+func isZero(b []byte) bool {+ for _, v := range b {+ if v != 0 {+ return false+ }+ }+ return true+}diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex a68fbbe8..c6a26557 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -3,13 +3,21 @@ package workerimport ("context""fmt"+ "log""net"+ "os"+ "os/exec"+ "path/filepath"+ "strings""time"+ "github.com/google/uuid""google.golang.org/grpc""google.golang.org/grpc/keepalive"+ "github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/sandbox"+ "github.com/opensandbox/opensandbox/internal/sparse""github.com/opensandbox/opensandbox/internal/storage""github.com/opensandbox/opensandbox/internal/template""github.com/opensandbox/opensandbox/pkg/types"@@ -25,11 +33,12 @@ type GRPCServer struct {sandboxDBs *sandbox.SandboxDBManagercheckpointStore *storage.CheckpointStorebuilder *template.Builder+ store *db.Store // nil if no DB configuredserver *grpc.Server}// NewGRPCServer creates a new gRPC server wrapping the sandbox manager.-func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder *template.Builder) *GRPCServer {+func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder *template.Builder, store *db.Store) *GRPCServer {s := &GRPCServer{manager: mgr,router: router,@@ -37,6 +46,7 @@ func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandboxDBs: sandboxDBs,checkpointStore: checkpointStore,builder: builder,+ store: store,server: grpc.NewServer(grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{MinTime: 5 * time.Second,@@ -78,6 +88,16 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReqPort: int(req.Port),}+ // Handle sandbox snapshot template: resolve S3 keys to local paths.+ if req.TemplateRootfsKey != "" && req.TemplateWorkspaceKey != "" {+ localRootfs, localWorkspace, err := s.resolveTemplateDrives(ctx, req.TemplateRootfsKey, req.TemplateWorkspaceKey)+ if err != nil {+ return nil, fmt.Errorf("resolve template drives: %w", err)+ }+ cfg.TemplateRootfsKey = "local://" + localRootfs+ cfg.TemplateWorkspaceKey = "local://" + localWorkspace+ }+sb, err := s.manager.Create(ctx, cfg)if err != nil {return nil, fmt.Errorf("failed to create sandbox: %w", err)@@ -374,6 +394,144 @@ func (s *GRPCServer) BuildTemplate(ctx context.Context, req *pb.BuildTemplateReq}, nil}+func (s *GRPCServer) SaveAsTemplate(ctx context.Context, req *pb.SaveAsTemplateRequest) (*pb.SaveAsTemplateResponse, error) {+ if s.checkpointStore == nil {+ return nil, fmt.Errorf("checkpoint store not configured on this worker")+ }++ templateID := req.TemplateId+ if _, err := uuid.Parse(templateID); err != nil {+ return nil, fmt.Errorf("invalid template ID: %w", err)+ }++ // The onReady callback marks the template as ready in the DB when the async S3 upload completes.+ var onReady func()+ if s.store != nil {+ tid, _ := uuid.Parse(templateID)+ onReady = func() {+ if err := s.store.SetTemplateReady(context.Background(), tid); err != nil {+ log.Printf("grpc: SaveAsTemplate: failed to mark template %s ready: %v", templateID, err)+ } else {+ log.Printf("grpc: SaveAsTemplate: template %s is now ready", templateID)+ }+ }+ }++ rootfsKey, workspaceKey, err := s.manager.SaveAsTemplate(ctx, req.SandboxId, templateID, s.checkpointStore, onReady)+ if err != nil {+ return nil, fmt.Errorf("save-as-template failed: %w", err)+ }++ return &pb.SaveAsTemplateResponse{+ RootfsS3Key: rootfsKey,+ WorkspaceS3Key: workspaceKey,+ }, nil+}++// resolveTemplateDrives resolves S3 template keys to local file paths.+// Uses local template cache when available (instant reflink), otherwise downloads from S3.+func (s *GRPCServer) resolveTemplateDrives(ctx context.Context, rootfsKey, workspaceKey string) (localRootfs, localWorkspace string, err error) {+ templateID := extractTemplateID(rootfsKey)+ if templateID == "" {+ return "", "", fmt.Errorf("cannot extract template ID from key: %s", rootfsKey)+ }++ // Fast path: check local template cache+ cachedRootfs := s.manager.TemplateCachePath(templateID, "rootfs.ext4")+ cachedWorkspace := s.manager.TemplateCachePath(templateID, "workspace.ext4")+ if cachedRootfs != "" && cachedWorkspace != "" {+ log.Printf("grpc: create from template %s: using local cache", templateID)+ return cachedRootfs, cachedWorkspace, nil+ }++ // Slow path: download from S3 and cache locally+ log.Printf("grpc: create from template %s: downloading from S3 (rootfs=%s, workspace=%s)", templateID, rootfsKey, workspaceKey)+ return s.downloadAndCacheTemplateDrives(ctx, templateID, rootfsKey, workspaceKey)+}++// extractTemplateID extracts the template ID from an S3 key like "templates/{id}/rootfs.tar.zst".+func extractTemplateID(s3Key string) string {+ parts := strings.Split(s3Key, "/")+ if len(parts) >= 2 && parts[0] == "templates" {+ return parts[1]+ }+ return ""+}++// downloadAndCacheTemplateDrives downloads template archives from S3, extracts them,+// and caches the ext4 drives locally for future use.+func (s *GRPCServer) downloadAndCacheTemplateDrives(ctx context.Context, templateID, rootfsKey, workspaceKey string) (string, string, error) {+ if s.checkpointStore == nil {+ return "", "", fmt.Errorf("checkpoint store not configured")+ }++ cacheDir := filepath.Join(s.manager.DataDir(), "templates", templateID)+ if err := os.MkdirAll(cacheDir, 0755); err != nil {+ return "", "", fmt.Errorf("create template cache dir: %w", err)+ }++ cachedRootfs := filepath.Join(cacheDir, "rootfs.ext4")+ cachedWorkspace := filepath.Join(cacheDir, "workspace.ext4")++ // Download and extract rootfs (tar.zst)+ if err := downloadAndExtract(ctx, s.checkpointStore, rootfsKey, cacheDir, extractArchiveCmd); err != nil {+ os.RemoveAll(cacheDir)+ return "", "", fmt.Errorf("download rootfs: %w", err)+ }++ // Download and extract workspace (sparse.zst)+ if err := downloadAndExtract(ctx, s.checkpointStore, workspaceKey, cachedWorkspace, extractSparseCmd); err != nil {+ os.RemoveAll(cacheDir)+ return "", "", fmt.Errorf("download workspace: %w", err)+ }++ log.Printf("grpc: template %s: cached locally at %s", templateID, cacheDir)+ return cachedRootfs, cachedWorkspace, nil+}++// extractFunc defines how to extract a downloaded archive to a destination path.+type extractFunc func(archivePath, destPath string) error++// extractArchiveCmd extracts a tar.zst archive to a directory.+func extractArchiveCmd(archivePath, destDir string) error {+ cmd := exec.Command("tar", "--zstd", "-xf", archivePath, "-C", destDir)+ if out, err := cmd.CombinedOutput(); err != nil {+ return fmt.Errorf("tar extract: %w (%s)", err, strings.TrimSpace(string(out)))+ }+ return nil+}++// extractSparseCmd extracts a sparse.zst archive to a file using the sparse restore format.+func extractSparseCmd(archivePath, destPath string) error {+ return sparse.Restore(archivePath, destPath)+}++// downloadAndExtract downloads an S3 object to a temp file, extracts it, and removes the temp file.+func downloadAndExtract(ctx context.Context, store *storage.CheckpointStore, s3Key, dest string, extract extractFunc) error {+ data, err := store.Download(ctx, s3Key)+ if err != nil {+ return fmt.Errorf("download %s: %w", s3Key, err)+ }++ tmpFile, err := os.CreateTemp("", "osb-template-*")+ if err != nil {+ data.Close()+ return fmt.Errorf("create temp file: %w", err)+ }+ tmpPath := tmpFile.Name()+ defer os.Remove(tmpPath)++ if _, err := tmpFile.ReadFrom(data); err != nil {+ tmpFile.Close()+ data.Close()+ return fmt.Errorf("write temp file: %w", err)+ }+ tmpFile.Close()+ data.Close()++ return extract(tmpPath, dest)+}+func (s *GRPCServer) GetSandboxStats(ctx context.Context, req *pb.GetSandboxStatsRequest) (*pb.GetSandboxStatsResponse, error) {stats, err := s.manager.Stats(ctx, req.SandboxId)if err != nil {diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.goindex bb66b32d..fbcb5229 100644--- a/pkg/types/sandbox.go+++ b/pkg/types/sandbox.go@@ -41,7 +41,11 @@ type SandboxConfig struct {Envs map[string]string `json:"envs,omitempty"`Port int `json:"port,omitempty"` // container port to expose via subdomain (default 80)NetworkEnabled bool `json:"networkEnabled,omitempty"`- ImageRef string `json:"imageRef,omitempty"` // resolved ECR URI for custom templates+ ImageRef string `json:"imageRef,omitempty"` // resolved ECR URI for custom templates+ // Sandbox snapshot template: S3 keys for rootfs and workspace drives.+ // When set, the sandbox boots from these drives instead of the standard base image.+ TemplateRootfsKey string `json:"templateRootfsKey,omitempty"`+ TemplateWorkspaceKey string `json:"templateWorkspaceKey,omitempty"`}// SandboxListResponse is the response for listing sandboxes.diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.goindex b6dae3ea..48f05372 100644--- a/proto/worker/worker.pb.go+++ b/proto/worker/worker.pb.go@@ -77,8 +77,11 @@ type CreateSandboxRequest struct {NetworkEnabled bool `protobuf:"varint,6,opt,name=network_enabled,json=networkEnabled,proto3" json:"network_enabled,omitempty"`ImageRef string `protobuf:"bytes,7,opt,name=image_ref,json=imageRef,proto3" json:"image_ref,omitempty"`Port int32 `protobuf:"varint,8,opt,name=port,proto3" json:"port,omitempty"` // container port to expose via subdomain (default 80)- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ // Sandbox snapshot template: if non-empty, boot from these S3 keys instead of base image.+ TemplateRootfsKey string `protobuf:"bytes,9,opt,name=template_rootfs_key,json=templateRootfsKey,proto3" json:"template_rootfs_key,omitempty"`+ TemplateWorkspaceKey string `protobuf:"bytes,10,opt,name=template_workspace_key,json=templateWorkspaceKey,proto3" json:"template_workspace_key,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *CreateSandboxRequest) Reset() {@@ -167,6 +170,20 @@ func (x *CreateSandboxRequest) GetPort() int32 {return 0}+func (x *CreateSandboxRequest) GetTemplateRootfsKey() string {+ if x != nil {+ return x.TemplateRootfsKey+ }+ return ""+}++func (x *CreateSandboxRequest) GetTemplateWorkspaceKey() string {+ if x != nil {+ return x.TemplateWorkspaceKey+ }+ return ""+}+type CreateSandboxResponse struct {state protoimpl.MessageState `protogen:"open.v1"`SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`@@ -1573,6 +1590,110 @@ func (x *WakeSandboxResponse) GetStatus() string {return ""}+type SaveAsTemplateRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`+ TemplateId string `protobuf:"bytes,2,opt,name=template_id,json=templateId,proto3" json:"template_id,omitempty"` // UUID assigned by control plane+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SaveAsTemplateRequest) Reset() {+ *x = SaveAsTemplateRequest{}+ mi := &file_proto_worker_worker_proto_msgTypes[27]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SaveAsTemplateRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SaveAsTemplateRequest) ProtoMessage() {}++func (x *SaveAsTemplateRequest) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[27]+ 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 SaveAsTemplateRequest.ProtoReflect.Descriptor instead.+func (*SaveAsTemplateRequest) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{27}+}++func (x *SaveAsTemplateRequest) GetSandboxId() string {+ if x != nil {+ return x.SandboxId+ }+ return ""+}++func (x *SaveAsTemplateRequest) GetTemplateId() string {+ if x != nil {+ return x.TemplateId+ }+ return ""+}++type SaveAsTemplateResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ RootfsS3Key string `protobuf:"bytes,1,opt,name=rootfs_s3_key,json=rootfsS3Key,proto3" json:"rootfs_s3_key,omitempty"`+ WorkspaceS3Key string `protobuf:"bytes,2,opt,name=workspace_s3_key,json=workspaceS3Key,proto3" json:"workspace_s3_key,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SaveAsTemplateResponse) Reset() {+ *x = SaveAsTemplateResponse{}+ mi := &file_proto_worker_worker_proto_msgTypes[28]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SaveAsTemplateResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SaveAsTemplateResponse) ProtoMessage() {}++func (x *SaveAsTemplateResponse) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[28]+ 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 SaveAsTemplateResponse.ProtoReflect.Descriptor instead.+func (*SaveAsTemplateResponse) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{28}+}++func (x *SaveAsTemplateResponse) GetRootfsS3Key() string {+ if x != nil {+ return x.RootfsS3Key+ }+ return ""+}++func (x *SaveAsTemplateResponse) GetWorkspaceS3Key() string {+ if x != nil {+ return x.WorkspaceS3Key+ }+ return ""+}+type BuildTemplateRequest struct {state protoimpl.MessageState `protogen:"open.v1"`Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`@@ -1585,7 +1706,7 @@ type BuildTemplateRequest struct {func (x *BuildTemplateRequest) Reset() {*x = BuildTemplateRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[27]+ mi := &file_proto_worker_worker_proto_msgTypes[29]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1597,7 +1718,7 @@ func (x *BuildTemplateRequest) String() string {func (*BuildTemplateRequest) ProtoMessage() {}func (x *BuildTemplateRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[27]+ mi := &file_proto_worker_worker_proto_msgTypes[29]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1610,7 +1731,7 @@ func (x *BuildTemplateRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use BuildTemplateRequest.ProtoReflect.Descriptor instead.func (*BuildTemplateRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{27}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{29}}func (x *BuildTemplateRequest) GetName() string {@@ -1651,7 +1772,7 @@ type BuildTemplateResponse struct {func (x *BuildTemplateResponse) Reset() {*x = BuildTemplateResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[28]+ mi := &file_proto_worker_worker_proto_msgTypes[30]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1663,7 +1784,7 @@ func (x *BuildTemplateResponse) String() string {func (*BuildTemplateResponse) ProtoMessage() {}func (x *BuildTemplateResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[28]+ mi := &file_proto_worker_worker_proto_msgTypes[30]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1676,7 +1797,7 @@ func (x *BuildTemplateResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use BuildTemplateResponse.ProtoReflect.Descriptor instead.func (*BuildTemplateResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{28}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{30}}func (x *BuildTemplateResponse) GetImageRef() string {@@ -1702,7 +1823,7 @@ type GetSandboxStatsRequest struct {func (x *GetSandboxStatsRequest) Reset() {*x = GetSandboxStatsRequest{}- mi := &file_proto_worker_worker_proto_msgTypes[29]+ mi := &file_proto_worker_worker_proto_msgTypes[31]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1714,7 +1835,7 @@ func (x *GetSandboxStatsRequest) String() string {func (*GetSandboxStatsRequest) ProtoMessage() {}func (x *GetSandboxStatsRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[29]+ mi := &file_proto_worker_worker_proto_msgTypes[31]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1727,7 +1848,7 @@ func (x *GetSandboxStatsRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use GetSandboxStatsRequest.ProtoReflect.Descriptor instead.func (*GetSandboxStatsRequest) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{29}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{31}}func (x *GetSandboxStatsRequest) GetSandboxId() string {@@ -1751,7 +1872,7 @@ type GetSandboxStatsResponse struct {func (x *GetSandboxStatsResponse) Reset() {*x = GetSandboxStatsResponse{}- mi := &file_proto_worker_worker_proto_msgTypes[30]+ mi := &file_proto_worker_worker_proto_msgTypes[32]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1763,7 +1884,7 @@ func (x *GetSandboxStatsResponse) String() string {func (*GetSandboxStatsResponse) ProtoMessage() {}func (x *GetSandboxStatsResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_worker_worker_proto_msgTypes[30]+ mi := &file_proto_worker_worker_proto_msgTypes[32]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1776,7 +1897,7 @@ func (x *GetSandboxStatsResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use GetSandboxStatsResponse.ProtoReflect.Descriptor instead.func (*GetSandboxStatsResponse) Descriptor() ([]byte, []int) {- return file_proto_worker_worker_proto_rawDescGZIP(), []int{30}+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{32}}func (x *GetSandboxStatsResponse) GetCpuPercent() float64 {@@ -1825,7 +1946,7 @@ var File_proto_worker_worker_proto protoreflect.FileDescriptorconst file_proto_worker_worker_proto_rawDesc = "" +"\n" +- "\x19proto/worker/worker.proto\x12\x06worker\"\xd5\x02\n" ++ "\x19proto/worker/worker.proto\x12\x06worker\"\xbb\x03\n" +"\x14CreateSandboxRequest\x12\x1a\n" +"\btemplate\x18\x01 \x01(\tR\btemplate\x12\x18\n" +"\atimeout\x18\x02 \x01(\x05R\atimeout\x12:\n" +@@ -1834,7 +1955,10 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\tcpu_count\x18\x05 \x01(\x05R\bcpuCount\x12'\n" +"\x0fnetwork_enabled\x18\x06 \x01(\bR\x0enetworkEnabled\x12\x1b\n" +"\timage_ref\x18\a \x01(\tR\bimageRef\x12\x12\n" +- "\x04port\x18\b \x01(\x05R\x04port\x1a7\n" ++ "\x04port\x18\b \x01(\x05R\x04port\x12.\n" ++ "\x13template_rootfs_key\x18\t \x01(\tR\x11templateRootfsKey\x124\n" ++ "\x16template_workspace_key\x18\n" ++ " \x01(\tR\x14templateWorkspaceKey\x1a7\n" +"\tEnvsEntry\x12\x10\n" +"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"N\n" +@@ -1945,7 +2069,15 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\x13WakeSandboxResponse\x12\x1d\n" +"\n" +"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x16\n" +- "\x06status\x18\x02 \x01(\tR\x06status\"\x80\x01\n" ++ "\x06status\x18\x02 \x01(\tR\x06status\"W\n" ++ "\x15SaveAsTemplateRequest\x12\x1d\n" ++ "\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x1f\n" ++ "\vtemplate_id\x18\x02 \x01(\tR\n" ++ "templateId\"f\n" ++ "\x16SaveAsTemplateResponse\x12\"\n" ++ "\rrootfs_s3_key\x18\x01 \x01(\tR\vrootfsS3Key\x12(\n" ++ "\x10workspace_s3_key\x18\x02 \x01(\tR\x0eworkspaceS3Key\"\x80\x01\n" +"\x14BuildTemplateRequest\x12\x12\n" +"\x04name\x18\x01 \x01(\tR\x04name\x12\x1e\n" +"\n" +@@ -1967,7 +2099,7 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\tnet_input\x18\x04 \x01(\x04R\bnetInput\x12\x1d\n" +"\n" +"net_output\x18\x05 \x01(\x04R\tnetOutput\x12\x12\n" +- "\x04pids\x18\x06 \x01(\x05R\x04pids2\xcb\b\n" ++ "\x04pids\x18\x06 \x01(\x05R\x04pids2\x9c\t\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" +@@ -1982,7 +2114,8 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\tCreatePTY\x12\x18.worker.CreatePTYRequest\x1a\x19.worker.CreatePTYResponse\x124\n" +"\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.WakeSandboxResponse\x12L\n" ++ "\vWakeSandbox\x12\x1a.worker.WakeSandboxRequest\x1a\x1b.worker.WakeSandboxResponse\x12O\n" ++ "\x0eSaveAsTemplate\x12\x1d.worker.SaveAsTemplateRequest\x1a\x1e.worker.SaveAsTemplateResponse\x12L\n" +"\rBuildTemplate\x12\x1c.worker.BuildTemplateRequest\x1a\x1d.worker.BuildTemplateResponse\x12R\n" +"\x0fGetSandboxStats\x12\x1e.worker.GetSandboxStatsRequest\x1a\x1f.worker.GetSandboxStatsResponseB1Z/github.com/opensandbox/opensandbox/proto/workerb\x06proto3"@@ -1999,7 +2132,7 @@ 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, 33)+var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 35)var file_proto_worker_worker_proto_goTypes = []any{(ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream(*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest@@ -2029,17 +2162,19 @@ var file_proto_worker_worker_proto_goTypes = []any{(*HibernateSandboxResponse)(nil), // 25: worker.HibernateSandboxResponse(*WakeSandboxRequest)(nil), // 26: worker.WakeSandboxRequest(*WakeSandboxResponse)(nil), // 27: worker.WakeSandboxResponse- (*BuildTemplateRequest)(nil), // 28: worker.BuildTemplateRequest- (*BuildTemplateResponse)(nil), // 29: worker.BuildTemplateResponse- (*GetSandboxStatsRequest)(nil), // 30: worker.GetSandboxStatsRequest- (*GetSandboxStatsResponse)(nil), // 31: worker.GetSandboxStatsResponse- nil, // 32: worker.CreateSandboxRequest.EnvsEntry- nil, // 33: worker.ExecCommandRequest.EnvsEntry+ (*SaveAsTemplateRequest)(nil), // 28: worker.SaveAsTemplateRequest+ (*SaveAsTemplateResponse)(nil), // 29: worker.SaveAsTemplateResponse+ (*BuildTemplateRequest)(nil), // 30: worker.BuildTemplateRequest+ (*BuildTemplateResponse)(nil), // 31: worker.BuildTemplateResponse+ (*GetSandboxStatsRequest)(nil), // 32: worker.GetSandboxStatsRequest+ (*GetSandboxStatsResponse)(nil), // 33: worker.GetSandboxStatsResponse+ nil, // 34: worker.CreateSandboxRequest.EnvsEntry+ nil, // 35: worker.ExecCommandRequest.EnvsEntry}var file_proto_worker_worker_proto_depIdxs = []int32{- 32, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry+ 34, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry6, // 1: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse- 33, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry+ 35, // 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@@ -2056,25 +2191,27 @@ var file_proto_worker_worker_proto_depIdxs = []int32{21, // 16: worker.SandboxWorker.PTYStream:input_type -> worker.PTYInput24, // 17: worker.SandboxWorker.HibernateSandbox:input_type -> worker.HibernateSandboxRequest26, // 18: worker.SandboxWorker.WakeSandbox:input_type -> worker.WakeSandboxRequest- 28, // 19: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest- 30, // 20: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest- 2, // 21: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse- 4, // 22: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse- 6, // 23: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse- 8, // 24: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse- 10, // 25: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse- 11, // 26: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk- 13, // 27: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse- 15, // 28: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse- 18, // 29: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse- 20, // 30: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse- 23, // 31: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput- 25, // 32: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse- 27, // 33: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse- 29, // 34: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse- 31, // 35: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse- 21, // [21:36] is the sub-list for method output_type- 6, // [6:21] is the sub-list for method input_type+ 28, // 19: worker.SandboxWorker.SaveAsTemplate:input_type -> worker.SaveAsTemplateRequest+ 30, // 20: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest+ 32, // 21: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest+ 2, // 22: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse+ 4, // 23: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse+ 6, // 24: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse+ 8, // 25: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse+ 10, // 26: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse+ 11, // 27: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk+ 13, // 28: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse+ 15, // 29: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse+ 18, // 30: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse+ 20, // 31: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse+ 23, // 32: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput+ 25, // 33: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse+ 27, // 34: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse+ 29, // 35: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse+ 31, // 36: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse+ 33, // 37: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse+ 22, // [22:38] is the sub-list for method output_type+ 6, // [6:22] 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@@ -2095,7 +2232,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: 33,+ NumMessages: 35,NumExtensions: 0,NumServices: 1,},diff --git a/proto/worker/worker.proto b/proto/worker/worker.protoindex d10b24c0..de9915aa 100644--- a/proto/worker/worker.proto+++ b/proto/worker/worker.proto@@ -23,6 +23,8 @@ service SandboxWorker {rpc HibernateSandbox(HibernateSandboxRequest) returns (HibernateSandboxResponse);rpc WakeSandbox(WakeSandboxRequest) returns (WakeSandboxResponse);+ rpc SaveAsTemplate(SaveAsTemplateRequest) returns (SaveAsTemplateResponse);+rpc BuildTemplate(BuildTemplateRequest) returns (BuildTemplateResponse);rpc GetSandboxStats(GetSandboxStatsRequest) returns (GetSandboxStatsResponse);@@ -37,6 +39,9 @@ message CreateSandboxRequest {bool network_enabled = 6;string image_ref = 7;int32 port = 8; // container port to expose via subdomain (default 80)+ // Sandbox snapshot template: if non-empty, boot from these S3 keys instead of base image.+ string template_rootfs_key = 9;+ string template_workspace_key = 10;}message CreateSandboxResponse {@@ -175,6 +180,16 @@ message WakeSandboxResponse {string status = 2;}+message SaveAsTemplateRequest {+ string sandbox_id = 1;+ string template_id = 2; // UUID assigned by control plane+}++message SaveAsTemplateResponse {+ string rootfs_s3_key = 1;+ string workspace_s3_key = 2;+}+message BuildTemplateRequest {string name = 1;string dockerfile = 2;diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.goindex e2277a05..71f4bf1e 100644--- a/proto/worker/worker_grpc.pb.go+++ b/proto/worker/worker_grpc.pb.go@@ -32,6 +32,7 @@ const (SandboxWorker_PTYStream_FullMethodName = "/worker.SandboxWorker/PTYStream"SandboxWorker_HibernateSandbox_FullMethodName = "/worker.SandboxWorker/HibernateSandbox"SandboxWorker_WakeSandbox_FullMethodName = "/worker.SandboxWorker/WakeSandbox"+ SandboxWorker_SaveAsTemplate_FullMethodName = "/worker.SandboxWorker/SaveAsTemplate"SandboxWorker_BuildTemplate_FullMethodName = "/worker.SandboxWorker/BuildTemplate"SandboxWorker_GetSandboxStats_FullMethodName = "/worker.SandboxWorker/GetSandboxStats")@@ -53,6 +54,7 @@ type SandboxWorkerClient interface {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)+ SaveAsTemplate(ctx context.Context, in *SaveAsTemplateRequest, opts ...grpc.CallOption) (*SaveAsTemplateResponse, error)BuildTemplate(ctx context.Context, in *BuildTemplateRequest, opts ...grpc.CallOption) (*BuildTemplateResponse, error)GetSandboxStats(ctx context.Context, in *GetSandboxStatsRequest, opts ...grpc.CallOption) (*GetSandboxStatsResponse, error)}@@ -207,6 +209,16 @@ func (c *sandboxWorkerClient) WakeSandbox(ctx context.Context, in *WakeSandboxRereturn out, nil}+func (c *sandboxWorkerClient) SaveAsTemplate(ctx context.Context, in *SaveAsTemplateRequest, opts ...grpc.CallOption) (*SaveAsTemplateResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(SaveAsTemplateResponse)+ err := c.cc.Invoke(ctx, SandboxWorker_SaveAsTemplate_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+func (c *sandboxWorkerClient) BuildTemplate(ctx context.Context, in *BuildTemplateRequest, opts ...grpc.CallOption) (*BuildTemplateResponse, error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)out := new(BuildTemplateResponse)@@ -244,6 +256,7 @@ type SandboxWorkerServer interface {PTYStream(grpc.BidiStreamingServer[PTYInput, PTYOutput]) errorHibernateSandbox(context.Context, *HibernateSandboxRequest) (*HibernateSandboxResponse, error)WakeSandbox(context.Context, *WakeSandboxRequest) (*WakeSandboxResponse, error)+ SaveAsTemplate(context.Context, *SaveAsTemplateRequest) (*SaveAsTemplateResponse, error)BuildTemplate(context.Context, *BuildTemplateRequest) (*BuildTemplateResponse, error)GetSandboxStats(context.Context, *GetSandboxStatsRequest) (*GetSandboxStatsResponse, error)mustEmbedUnimplementedSandboxWorkerServer()@@ -295,6 +308,9 @@ func (UnimplementedSandboxWorkerServer) HibernateSandbox(context.Context, *Hiberfunc (UnimplementedSandboxWorkerServer) WakeSandbox(context.Context, *WakeSandboxRequest) (*WakeSandboxResponse, error) {return nil, status.Error(codes.Unimplemented, "method WakeSandbox not implemented")}+func (UnimplementedSandboxWorkerServer) SaveAsTemplate(context.Context, *SaveAsTemplateRequest) (*SaveAsTemplateResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method SaveAsTemplate not implemented")+}func (UnimplementedSandboxWorkerServer) BuildTemplate(context.Context, *BuildTemplateRequest) (*BuildTemplateResponse, error) {return nil, status.Error(codes.Unimplemented, "method BuildTemplate not implemented")}@@ -538,6 +554,24 @@ func _SandboxWorker_WakeSandbox_Handler(srv interface{}, ctx context.Context, dereturn interceptor(ctx, in, info, handler)}+func _SandboxWorker_SaveAsTemplate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(SaveAsTemplateRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SandboxWorkerServer).SaveAsTemplate(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SandboxWorker_SaveAsTemplate_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SandboxWorkerServer).SaveAsTemplate(ctx, req.(*SaveAsTemplateRequest))+ }+ return interceptor(ctx, in, info, handler)+}+func _SandboxWorker_BuildTemplate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {in := new(BuildTemplateRequest)if err := dec(in); err != nil {@@ -625,6 +659,10 @@ var SandboxWorker_ServiceDesc = grpc.ServiceDesc{MethodName: "WakeSandbox",Handler: _SandboxWorker_WakeSandbox_Handler,},+ {+ MethodName: "SaveAsTemplate",+ Handler: _SandboxWorker_SaveAsTemplate_Handler,+ },{MethodName: "BuildTemplate",Handler: _SandboxWorker_BuildTemplate_Handler,diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex afba6969..6c88d5c2 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -115,6 +115,9 @@ export interface Template {tag: stringdockerfile?: stringisPublic: boolean+ templateType?: string+ createdBySandboxId?: string+ status?: stringcreatedAt: string}diff --git a/web/src/pages/Templates.tsx b/web/src/pages/Templates.tsxindex 314ffaee..0ec12d75 100644--- a/web/src/pages/Templates.tsx+++ b/web/src/pages/Templates.tsx@@ -127,6 +127,7 @@ export default function Templates() {<th>Name</th><th>Tag</th><th>Type</th>+ <th>Status</th><th>Created</th><th style={{ width: 80 }}></th></tr>@@ -153,6 +154,23 @@ export default function Templates() {{t.isPublic ? 'Built-in' : 'Custom'}</span></td>+ <td>+ <span style={{+ fontSize: 11,+ fontWeight: 600,+ padding: '2px 8px',+ borderRadius: 10,+ background: t.status === 'ready'+ ? 'rgba(34, 197, 94, 0.08)'+ : 'rgba(234, 179, 8, 0.08)',+ color: t.status === 'ready'+ ? 'var(--accent-green)'+ : '#eab308',+ border: `1px solid ${t.status === 'ready' ? 'rgba(34, 197, 94, 0.15)' : 'rgba(234, 179, 8, 0.15)'}`,+ }}>+ {t.status === 'ready' ? 'Ready' : 'Processing'}+ </span>+ </td><td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>{new Date(t.createdAt).toLocaleString()}</td>@@ -174,7 +192,7 @@ export default function Templates() {))}{(templates ?? []).length === 0 && (<tr>- <td colSpan={5} style={{ textAlign: 'center', padding: 32, color: 'var(--text-tertiary)' }}>+ <td colSpan={6} style={{ textAlign: 'center', padding: 32, color: 'var(--text-tertiary)' }}>No templates yet</td></tr>