Skip to content

An open-source, faster Devin alternative

TypeScript

S3-compatible global object store abstraction + Tigris cutover runbook

Brian Reardonfa842772eb04
diff --git a/cmd/worker/golden_upload.go b/cmd/worker/golden_upload.go
new file mode 100644
index 00000000..3a742cd0
--- /dev/null
+++ b/cmd/worker/golden_upload.go
@@ -0,0 +1,101 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "os"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/blobstore"
+ "github.com/opensandbox/opensandbox/internal/config"
+ qm "github.com/opensandbox/opensandbox/internal/qemu"
+)
+
+// uploadGolden is invoked by the `opensandbox-worker golden-upload <path>`
+// subcommand. It pushes the local default.ext4 to the configured global blob
+// store under two keys:
+//
+// {GoldensBucket}/default.ext4 — the "current" pointer
+// {GoldensBucket}/bases/{hash}/default.ext4 — versioned by content hash
+//
+// Workers default to fetching `default.ext4` on cache miss; cross-golden
+// migrations look up `bases/{hash}/default.ext4` by hash. Uploading both
+// covers both call sites in one shot.
+//
+// Used as:
+// - One-shot bootstrap on dev2: ssh in, run this once, populate Tigris
+// - Future Packer post-processor: run after the AMI build's rootfs step
+//
+// Reads OPENSANDBOX_GLOBAL_BLOB_* env vars for endpoint + creds. Fails loud
+// if blobstore isn't configured.
+func uploadGolden(path string) error {
+ // Bootstrap from KV the same way the main worker does — so this
+ // subcommand picks up worker-global-blob-* secrets when run on a
+ // host whose worker.env points at a KV. Without this, the user
+ // would have to manually export every Tigris env var inline.
+ if err := config.LoadSecretsFromKeyVault(); err != nil {
+ return fmt.Errorf("keyvault bootstrap: %w", err)
+ }
+ cfg, err := config.Load()
+ if err != nil {
+ return fmt.Errorf("config load: %w", err)
+ }
+ if cfg.GlobalBlobEndpoint == "" || cfg.GlobalBlobAccessKeyID == "" {
+ return fmt.Errorf("OPENSANDBOX_GLOBAL_BLOB_ENDPOINT and _ACCESS_KEY_ID required")
+ }
+ if cfg.GlobalBlobGoldensBucket == "" {
+ return fmt.Errorf("OPENSANDBOX_GLOBAL_BLOB_GOLDENS_BUCKET required")
+ }
+
+ st, err := os.Stat(path)
+ if err != nil {
+ return fmt.Errorf("stat %s: %w", path, err)
+ }
+ hash, err := qm.ComputeGoldenVersion(path)
+ if err != nil {
+ return fmt.Errorf("compute hash: %w", err)
+ }
+
+ store, err := blobstore.NewS3(blobstore.S3Config{
+ Name: cfg.GlobalBlobName,
+ Endpoint: cfg.GlobalBlobEndpoint,
+ Region: cfg.GlobalBlobRegion,
+ AccessKeyID: cfg.GlobalBlobAccessKeyID,
+ SecretAccessKey: cfg.GlobalBlobSecretAccessKey,
+ UsePathStyle: cfg.GlobalBlobUsePathStyle,
+ })
+ if err != nil {
+ return fmt.Errorf("blobstore init: %w", err)
+ }
+ if store == nil {
+ return fmt.Errorf("blobstore returned nil — check endpoint/access-key env vars")
+ }
+
+ versionedKey := fmt.Sprintf("bases/%s/default.ext4", hash)
+ bucket := cfg.GlobalBlobGoldensBucket
+
+ log.Printf("uploading %s (%.1fMB, hash=%s) to %s://%s/{default.ext4, %s}",
+ path, float64(st.Size())/(1024*1024), hash, store.Name(), bucket, versionedKey)
+ t0 := time.Now()
+
+ // Long timeout — multi-GB upload over residential or cross-region network.
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
+ defer cancel()
+
+ // Upload versioned key first — it's idempotent (hash-named), so a later
+ // retry won't double-charge if the second upload fails.
+ if err := blobstore.Upload(ctx, store, bucket, versionedKey, path); err != nil {
+ return fmt.Errorf("upload %s: %w", versionedKey, err)
+ }
+ log.Printf("uploaded %s (%dms)", versionedKey, time.Since(t0).Milliseconds())
+
+ t1 := time.Now()
+ if err := blobstore.Upload(ctx, store, bucket, "default.ext4", path); err != nil {
+ return fmt.Errorf("upload default.ext4: %w", err)
+ }
+ log.Printf("uploaded default.ext4 (%dms)", time.Since(t1).Milliseconds())
+
+ log.Printf("done in %s", time.Since(t0).Round(time.Millisecond))
+ return nil
+}
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index f0c06969..5d72fbbb 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -15,6 +15,7 @@ import (
"github.com/opensandbox/opensandbox/internal/analytics"
"github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/blobstore"
"github.com/opensandbox/opensandbox/internal/config"
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/metrics"
@@ -56,6 +57,25 @@ func main() {
return
}
+ // "golden-upload <path-to-default.ext4>" pushes the file to the global
+ // blob store at {GoldensBucket}/default.ext4 AND {GoldensBucket}/bases/{hash}/default.ext4.
+ // One-shot bootstrap path: a fresh dev cell whose AMI baked an ext4 can
+ // upload it so other cells (especially in different clouds) can pull
+ // the same canonical bytes on cache miss. Future Packer pipelines can
+ // run this at AMI-build time. Reads OPENSANDBOX_GLOBAL_BLOB_* env vars
+ // for the destination.
+ if len(os.Args) >= 2 && os.Args[1] == "golden-upload" {
+ if len(os.Args) != 3 {
+ fmt.Fprintln(os.Stderr, "usage: opensandbox-worker golden-upload <path-to-default.ext4>")
+ os.Exit(2)
+ }
+ if err := uploadGolden(os.Args[2]); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ return
+ }
+
// Load secrets from Azure Key Vault if configured (before config.Load reads env vars).
if err := config.LoadSecretsFromKeyVault(); err != nil {
log.Fatalf("failed to load secrets from Key Vault: %v", err)
@@ -142,16 +162,57 @@ func main() {
}
// QEMU backend
{
+ // Construct global blob store (Tigris primary + optional fallback).
+ // Returns nil if endpoint+access-key are unset → manager runs in
+ // local-only mode, no cache-miss fetch.
+ blobPrimary, blobErr := blobstore.NewS3(blobstore.S3Config{
+ Name: cfg.GlobalBlobName,
+ Endpoint: cfg.GlobalBlobEndpoint,
+ Region: cfg.GlobalBlobRegion,
+ AccessKeyID: cfg.GlobalBlobAccessKeyID,
+ SecretAccessKey: cfg.GlobalBlobSecretAccessKey,
+ UsePathStyle: cfg.GlobalBlobUsePathStyle,
+ })
+ if blobErr != nil {
+ log.Fatalf("opensandbox-worker: global blob store init failed: %v", blobErr)
+ }
+ blobFallback, fbErr := blobstore.NewS3(blobstore.S3Config{
+ Name: cfg.GlobalBlobFallbackName,
+ Endpoint: cfg.GlobalBlobFallbackEndpoint,
+ Region: cfg.GlobalBlobFallbackRegion,
+ AccessKeyID: cfg.GlobalBlobFallbackAccessKeyID,
+ SecretAccessKey: cfg.GlobalBlobFallbackSecretAccessKey,
+ UsePathStyle: cfg.GlobalBlobFallbackUsePathStyle,
+ })
+ if fbErr != nil {
+ log.Fatalf("opensandbox-worker: global blob fallback init failed: %v", fbErr)
+ }
+ var globalBlob blobstore.Store
+ if blobPrimary != nil {
+ if blobFallback != nil {
+ globalBlob, _ = blobstore.NewFallback(blobPrimary, blobFallback)
+ log.Printf("opensandbox-worker: global blob store: %s primary, %s fallback", blobPrimary.Name(), blobFallback.Name())
+ } else {
+ globalBlob = blobPrimary
+ log.Printf("opensandbox-worker: global blob store: %s (no fallback)", blobPrimary.Name())
+ }
+ } else {
+ log.Println("opensandbox-worker: global blob store disabled (endpoint unset) — local-only goldens")
+ }
+
qmCfg := qm.Config{
- DataDir: cfg.DataDir,
- KernelPath: cfg.KernelPath,
- ImagesDir: cfg.ImagesDir,
- QEMUBin: cfg.QEMUBin,
- AgentBinaryPath: "/usr/local/bin/osb-agent",
- AgentVersion: AgentVersion,
- DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,
- DefaultCPUs: cfg.DefaultSandboxCPUs,
- DefaultDiskMB: cfg.DefaultSandboxDiskMB,
+ DataDir: cfg.DataDir,
+ KernelPath: cfg.KernelPath,
+ ImagesDir: cfg.ImagesDir,
+ QEMUBin: cfg.QEMUBin,
+ AgentBinaryPath: "/usr/local/bin/osb-agent",
+ AgentVersion: AgentVersion,
+ DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,
+ DefaultCPUs: cfg.DefaultSandboxCPUs,
+ DefaultDiskMB: cfg.DefaultSandboxDiskMB,
+ GlobalBlob: globalBlob,
+ GlobalBlobGoldensBucket: cfg.GlobalBlobGoldensBucket,
+ GlobalBlobGoldenKey: "default.ext4",
}
qmMgr, err := qm.NewManager(qmCfg)
diff --git a/docs/blobstore-tigris-cutover.md b/docs/blobstore-tigris-cutover.md
new file mode 100644
index 00000000..0f4fc50b
--- /dev/null
+++ b/docs/blobstore-tigris-cutover.md
@@ -0,0 +1,173 @@
+# Tigris cutover runbook
+
+Zero-downtime migration of all object storage (checkpoints, hibernation archives,
+templates, goldens) from Azure Blob to Tigris using Tigris **shadow buckets** for
+read-through fallback. No bulk pre-copy required; lazy migration handles cold
+data over time. No code-level fallback wrapper required; Tigris does the
+fallback server-side.
+
+## What this covers
+
+| Data | Path | Current backend | Migration strategy |
+|---|---|---|---|
+| Checkpoints | `checkpoints/<sandbox>/<cp>/...` | Azure Blob | Endpoint flip; shadow reads |
+| Hibernation archives | Same path tree | Azure Blob | Endpoint flip; shadow reads |
+| Templates | `templates/<id>/...` | Azure Blob | Endpoint flip; shadow reads |
+| Goldens | `bases/<version>/default.ext4` | Azure Blob (ad-hoc) | New `internal/blobstore` abstraction + endpoint flip |
+| pg-backups | `pg-backups/...` | Azure Blob | Separate decision (out of scope) |
+
+Existing `internal/storage/` already auto-detects Azure vs S3 from the endpoint
+(see `internal/storage/blob.go`); pointing at Tigris is just an env rotation.
+
+New `internal/blobstore/` is a small S3-compatible abstraction added in this PR
+specifically for the global goldens path, which wasn't previously abstracted.
+
+## Pre-flight inventory
+
+At time of writing:
+- `checkpoints` container: ~1,834 blobs, ~2 TB
+- `pg-backups` container: 6 blobs, 0.25 GB
+- Estimated one-time Azure egress cost during drain: ~$180
+
+Lazy migration via shadow bucket avoids paying egress on cold objects that are
+never accessed.
+
+## Phase 0 — Pre-flight (zero prod impact)
+
+1. **Provision Tigris buckets** matching the Azure layout:
+ ```
+ tigris buckets create opencomputer-checkpoints
+ tigris buckets create opencomputer-goldens
+ tigris buckets create opencomputer-templates # if separate from checkpoints
+ ```
+2. **Configure shadow source** on each Tigris bucket, pointing at the
+ corresponding Azure container. Use `--write-through` so any writes to
+ Tigris during cutover also land in Azure (safety net):
+ ```
+ tigris buckets set-migration opencomputer-checkpoints \
+ --bucket checkpoints \
+ --endpoint https://occkpt3ccf3c31.blob.core.windows.net \
+ --region eastus2 \
+ --access-key "$AZURE_STORAGE_ACCOUNT_NAME" \
+ --secret-key "$AZURE_STORAGE_KEY" \
+ --write-through
+ ```
+ Repeat for `opencomputer-goldens`, etc.
+3. **Stash Tigris credentials in prod KV** under the existing and new env-var
+ names (workers don't read them yet):
+ - Existing path (checkpoints/hibernation/templates):
+ - `OPENSANDBOX_S3_ENDPOINT` → `https://t3.storage.dev`
+ - `OPENSANDBOX_S3_ACCESS_KEY_ID`, `OPENSANDBOX_S3_SECRET_ACCESS_KEY` → Tigris values
+ - `OPENSANDBOX_S3_REGION` → `auto`
+ - `OPENSANDBOX_S3_FORCE_PATH_STYLE` → `true`
+ - `OPENSANDBOX_S3_BUCKET` → `opencomputer-checkpoints`
+ - New path (goldens, this PR):
+ - `OPENSANDBOX_GLOBAL_BLOB_NAME` → `tigris`
+ - `OPENSANDBOX_GLOBAL_BLOB_ENDPOINT` → `https://t3.storage.dev`
+ - `OPENSANDBOX_GLOBAL_BLOB_REGION` → `auto`
+ - `OPENSANDBOX_GLOBAL_BLOB_ACCESS_KEY_ID`, `OPENSANDBOX_GLOBAL_BLOB_SECRET_ACCESS_KEY` → Tigris values
+ - `OPENSANDBOX_GLOBAL_BLOB_USE_PATH_STYLE` → `true`
+ - `OPENSANDBOX_GLOBAL_BLOB_GOLDENS_BUCKET` → `opencomputer-goldens`
+
+## Phase 1 — Merge + deploy (additive, no behavior change)
+
+1. Merge this PR.
+2. Bake new worker AMI containing the `internal/blobstore` code.
+3. Roll out via existing rolling-replace process.
+
+After this phase, workers contain the blobstore code but still read/write Azure
+because the new env vars and `OPENSANDBOX_S3_*` haven't been rotated yet. Zero
+behavior change.
+
+## Phase 2 — Seed goldens (optional, makes Phase 3 instant for new cells)
+
+Use the new `golden-upload` subcommand to push the canonical `default.ext4`
+into the goldens bucket (via the Tigris shadow which will also cache it):
+
+```
+# On any worker with the env vars set:
+opensandbox-worker golden-upload /data/firecracker/images/default.ext4
+```
+
+This puts the bytes at `opencomputer-goldens/default.ext4` AND
+`opencomputer-goldens/bases/<hash>/default.ext4`. Skip if you're fine with
+the first new cell to come up paying a one-time fetch latency.
+
+## Phase 3 — Atomic flip (no downtime)
+
+1. Rotate prod KV: secrets we stashed in Phase 0 become active.
+2. Trigger rolling-replace of workers (existing process). Each worker that
+ cycles starts using Tigris for new writes; reads of cold keys
+ transparently fetch from Azure via Tigris shadow (and warm Tigris in the
+ process).
+3. Monitor worker logs for the line
+ `storage: using S3-compat backend (endpoint=https://t3.storage.dev, bucket=opencomputer-checkpoints)`
+ to confirm the new endpoint is in effect.
+4. Smoke-check: create a sandbox, take a checkpoint, fork it on a different
+ worker. Both writes (checkpoint upload) and reads (fork download) exercise
+ the Tigris path.
+
+No downtime because:
+- Existing checkpoints are still readable via Tigris's shadow fallback to Azure
+- New checkpoints land in Tigris directly
+- Goldens fetch from Tigris (and shadow-fall-back if cold)
+
+## Phase 4 — Drain (background, optional)
+
+Optionally pull all remaining Azure data into Tigris so the shadow can be
+disabled cleanly:
+
+```
+tigris buckets drain opencomputer-checkpoints
+tigris buckets drain opencomputer-goldens
+```
+
+This runs in the Tigris control plane; no impact on serving traffic. Can be
+left running for days. Skip this if you're fine with lazy migration (only
+accessed keys ever move to Tigris).
+
+## Phase 5 — Soak
+
+Run with Tigris primary + Azure shadow for **1-2 weeks**. Monitor:
+- Tigris dashboard: cold-fetch rate (shadow reads). Should trend down over time
+ as the working set warms.
+- Worker logs: no `blob: object not found` errors from the checkpoint store.
+- Latency: cold-fetch first-byte > Tigris-native, but should remain within
+ acceptable bounds.
+
+## Phase 6 — Cut shadow
+
+Once drained (or after sufficient soak with lazy migration):
+
+```
+tigris buckets set-migration opencomputer-checkpoints --disable
+# repeat for other buckets
+```
+
+Workers now read/write Tigris-only.
+
+## Phase 7 — Decom Azure
+
+After the retention window (suggest 30 days) and zero observed reads from
+Azure side:
+
+```
+az storage container delete --account-name occkpt3ccf3c31 -n checkpoints
+az storage account delete -g opencomputer-prod -n occkpt3ccf3c31
+```
+
+## Rollback
+
+At any point through Phase 5, rollback is one env rotation back to Azure
+endpoints + roll workers. Data is dual-written (write-through) so neither
+side falls behind. Past Phase 6 (shadow disabled), rolling back means
+either:
+- Re-enabling shadow (Tigris keeps the writes; Azure is stale; would need a
+ reverse copy to make Azure authoritative again)
+- Living with Tigris
+
+## Open question
+
+`pg-backups` (250 MB, 6 blobs) is outside the checkpoint store code path.
+Whether to migrate it is a separate operational decision — it doesn't block
+the rest of the cutover.
diff --git a/internal/blobstore/fallback.go b/internal/blobstore/fallback.go
new file mode 100644
index 00000000..199b3452
--- /dev/null
+++ b/internal/blobstore/fallback.go
@@ -0,0 +1,98 @@
+package blobstore
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+)
+
+// FallbackStore wraps a primary Store with one or more fallback Stores.
+// Read operations (Get, Exists) try the primary first; on transient
+// errors (network, 5xx) they cascade through fallbacks. NotFound is
+// authoritative — we don't try fallbacks for missing objects.
+//
+// Writes (Put) go to the primary only — multi-write would create
+// consistency challenges and is overkill for the use case.
+//
+// Use case: configure Tigris as primary, R2 as fallback. If Tigris has
+// an outage, golden pulls keep working from the R2 mirror (assuming
+// you've populated it; that's an upload-side concern out of scope here).
+type FallbackStore struct {
+ primary Store
+ fallbacks []Store
+}
+
+// NewFallback wraps primary with fallback Stores. Nil primary is an error;
+// nil entries in fallbacks are ignored (so callers can pass disabled
+// backends without filtering).
+func NewFallback(primary Store, fallbacks ...Store) (Store, error) {
+ if primary == nil {
+ return nil, errors.New("blobstore: FallbackStore requires non-nil primary")
+ }
+ cleaned := make([]Store, 0, len(fallbacks))
+ for _, f := range fallbacks {
+ if f != nil {
+ cleaned = append(cleaned, f)
+ }
+ }
+ if len(cleaned) == 0 {
+ return primary, nil // no fallbacks configured — just return primary
+ }
+ return &FallbackStore{primary: primary, fallbacks: cleaned}, nil
+}
+
+func (f *FallbackStore) Name() string {
+ names := f.primary.Name()
+ for _, b := range f.fallbacks {
+ names += "+" + b.Name()
+ }
+ return names
+}
+
+func (f *FallbackStore) Get(ctx context.Context, bucket, key string) (io.ReadCloser, error) {
+ r, err := f.primary.Get(ctx, bucket, key)
+ if err == nil {
+ return r, nil
+ }
+ if errors.Is(err, ErrNotFound) {
+ // Authoritative — primary says it doesn't exist. Don't ask fallbacks.
+ return nil, err
+ }
+ for i, fb := range f.fallbacks {
+ log.Printf("blobstore: primary %s failed (%v); trying fallback %s [%d/%d]",
+ f.primary.Name(), err, fb.Name(), i+1, len(f.fallbacks))
+ r2, err2 := fb.Get(ctx, bucket, key)
+ if err2 == nil {
+ return r2, nil
+ }
+ if errors.Is(err2, ErrNotFound) {
+ // Fallback also says missing — call it ErrNotFound. Probably means
+ // the fallback isn't populated; surface so caller can decide.
+ return nil, err2
+ }
+ err = err2
+ }
+ return nil, fmt.Errorf("blobstore: all backends failed: %w", err)
+}
+
+func (f *FallbackStore) Put(ctx context.Context, bucket, key string, body io.Reader, contentLength int64) error {
+ // Writes go only to primary. See package doc for rationale.
+ return f.primary.Put(ctx, bucket, key, body, contentLength)
+}
+
+func (f *FallbackStore) Exists(ctx context.Context, bucket, key string) (bool, error) {
+ ok, err := f.primary.Exists(ctx, bucket, key)
+ if err == nil {
+ return ok, nil
+ }
+ for _, fb := range f.fallbacks {
+ ok2, err2 := fb.Exists(ctx, bucket, key)
+ if err2 == nil {
+ return ok2, nil
+ }
+ err = err2
+ }
+ return false, err
+}
diff --git a/internal/blobstore/io.go b/internal/blobstore/io.go
new file mode 100644
index 00000000..a6b07089
--- /dev/null
+++ b/internal/blobstore/io.go
@@ -0,0 +1,51 @@
+package blobstore
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+)
+
+// writeAtomic streams r to destPath via destPath+".tmp" + rename. The
+// temp file is removed on any failure. Parent directories are created if
+// missing.
+func writeAtomic(destPath string, r io.Reader) error {
+ if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
+ return fmt.Errorf("blobstore: mkdir parent: %w", err)
+ }
+ tmp := destPath + ".tmp"
+ f, err := os.Create(tmp)
+ if err != nil {
+ return fmt.Errorf("blobstore: create tmp: %w", err)
+ }
+ if _, err := io.Copy(f, r); err != nil {
+ f.Close()
+ os.Remove(tmp)
+ return fmt.Errorf("blobstore: copy: %w", err)
+ }
+ if err := f.Close(); err != nil {
+ os.Remove(tmp)
+ return fmt.Errorf("blobstore: close tmp: %w", err)
+ }
+ if err := os.Rename(tmp, destPath); err != nil {
+ os.Remove(tmp)
+ return fmt.Errorf("blobstore: rename: %w", err)
+ }
+ return nil
+}
+
+// openSized opens srcPath and returns the file along with its size, ready
+// for streaming Put.
+func openSized(srcPath string) (*os.File, int64, error) {
+ f, err := os.Open(srcPath)
+ if err != nil {
+ return nil, 0, fmt.Errorf("blobstore: open src: %w", err)
+ }
+ st, err := f.Stat()
+ if err != nil {
+ f.Close()
+ return nil, 0, fmt.Errorf("blobstore: stat src: %w", err)
+ }
+ return f, st.Size(), nil
+}
diff --git a/internal/blobstore/s3.go b/internal/blobstore/s3.go
new file mode 100644
index 00000000..2f80a60e
--- /dev/null
+++ b/internal/blobstore/s3.go
@@ -0,0 +1,119 @@
+package blobstore
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+
+ "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 configures an S3-compatible backend. Works for Tigris, AWS S3,
+// CF R2, Azure Blob (via S3 compat), GCS (via interop), MinIO.
+type S3Config struct {
+ Name string // logging label: "tigris", "r2", "azure-blob"
+ Endpoint string // e.g. "https://t3.storage.dev". Empty = AWS default.
+ Region string // "auto" works for Tigris/R2; AWS needs a real region.
+ AccessKeyID string
+ SecretAccessKey string
+ UsePathStyle bool // true for R2/Tigris/MinIO; false for AWS S3.
+}
+
+// s3Store is an S3-compatible backend.
+type s3Store struct {
+ name string
+ s3 *s3.Client
+}
+
+// NewS3 constructs an S3-compatible Store. Returns nil, nil if Endpoint
+// and AccessKeyID are both empty (caller treats nil as "this backend
+// disabled, fall through to next").
+func NewS3(cfg S3Config) (Store, error) {
+ if cfg.Endpoint == "" && cfg.AccessKeyID == "" {
+ return nil, nil
+ }
+ if cfg.Region == "" {
+ cfg.Region = "auto"
+ }
+ if cfg.Name == "" {
+ cfg.Name = "s3"
+ }
+ awsCfg := aws.Config{
+ Region: cfg.Region,
+ Credentials: credentials.NewStaticCredentialsProvider(
+ cfg.AccessKeyID, cfg.SecretAccessKey, "",
+ ),
+ }
+ endpoint := cfg.Endpoint
+ client := s3.NewFromConfig(awsCfg, func(o *s3.Options) {
+ if endpoint != "" {
+ o.BaseEndpoint = &endpoint
+ }
+ o.UsePathStyle = cfg.UsePathStyle
+ })
+ return &s3Store{name: cfg.Name, s3: client}, nil
+}
+
+func (s *s3Store) Name() string { return s.name }
+
+func (s *s3Store) Get(ctx context.Context, bucket, key string) (io.ReadCloser, error) {
+ out, err := s.s3.GetObject(ctx, &s3.GetObjectInput{
+ Bucket: &bucket,
+ Key: &key,
+ })
+ if err != nil {
+ if isNotFound(err) {
+ return nil, fmt.Errorf("%s://%s/%s: %w", s.name, bucket, key, ErrNotFound)
+ }
+ return nil, fmt.Errorf("%s GetObject %s/%s: %w", s.name, bucket, key, err)
+ }
+ return out.Body, nil
+}
+
+func (s *s3Store) Put(ctx context.Context, bucket, key string, body io.Reader, contentLength int64) error {
+ _, err := s.s3.PutObject(ctx, &s3.PutObjectInput{
+ Bucket: &bucket,
+ Key: &key,
+ Body: body,
+ ContentLength: &contentLength,
+ })
+ if err != nil {
+ return fmt.Errorf("%s PutObject %s/%s: %w", s.name, bucket, key, err)
+ }
+ return nil
+}
+
+func (s *s3Store) Exists(ctx context.Context, bucket, key string) (bool, error) {
+ _, err := s.s3.HeadObject(ctx, &s3.HeadObjectInput{
+ Bucket: &bucket,
+ Key: &key,
+ })
+ if err == nil {
+ return true, nil
+ }
+ if isNotFound(err) {
+ return false, nil
+ }
+ return false, fmt.Errorf("%s HeadObject %s/%s: %w", s.name, bucket, key, err)
+}
+
+// isNotFound matches the various ways the v2 SDK signals 404. The typed
+// errors are nested in operation-specific wrapper types (NoSuchKey for
+// GetObject, NotFound for HeadObject) — match by code substring rather
+// than chase the type tree.
+func isNotFound(err error) bool {
+ if err == nil {
+ return false
+ }
+ if errors.Is(err, ErrNotFound) {
+ return true
+ }
+ msg := err.Error()
+ return strings.Contains(msg, "NoSuchKey") ||
+ strings.Contains(msg, "NotFound") ||
+ strings.Contains(msg, "status code: 404")
+}
diff --git a/internal/blobstore/store.go b/internal/blobstore/store.go
new file mode 100644
index 00000000..891b33da
--- /dev/null
+++ b/internal/blobstore/store.go
@@ -0,0 +1,70 @@
+// Package blobstore is the abstraction over the global object store that
+// holds canonical golden rootfs blobs, template blobs, and the events
+// archive.
+//
+// We currently use Tigris (Region Earth — automatic global replication),
+// but every implementation talks S3-compatible APIs, so swapping providers
+// (R2, AWS S3, Azure Blob via S3 compat, GCS via interop, MinIO) is a
+// config change — point at a different endpoint, supply different
+// credentials. Multi-backend failover composes Stores via FallbackStore.
+//
+// The package is intentionally small: just enough surface for downloading
+// goldens on cache miss, uploading from CI/Packer, and archiving events.
+// Anything richer (presigned URLs, multipart uploads >5GB, server-side
+// copy) belongs in a higher layer if/when we need it.
+package blobstore
+
+import (
+ "context"
+ "errors"
+ "io"
+)
+
+// ErrNotFound is returned by Get/Exists/Download when the object doesn't
+// exist. Distinguishable from transient errors so callers can fall back
+// to other behaviors (rebuild locally, try a different store, etc.).
+var ErrNotFound = errors.New("blobstore: object not found")
+
+// Store is the abstract interface every backend implements.
+//
+// Implementations should be safe for concurrent use — a single Store is
+// typically shared across goroutines (worker pool, async upload, etc.).
+type Store interface {
+ // Get streams the object at key from bucket. Caller closes the reader.
+ // Returns ErrNotFound if the object isn't present.
+ Get(ctx context.Context, bucket, key string) (io.ReadCloser, error)
+
+ // Put writes body of length contentLength bytes to bucket/key.
+ // Streams from the reader — no in-memory buffering of the full body.
+ Put(ctx context.Context, bucket, key string, body io.Reader, contentLength int64) error
+
+ // Exists returns true if the object is present at bucket/key.
+ // Returns (false, nil) on NotFound; (false, err) on other errors.
+ Exists(ctx context.Context, bucket, key string) (bool, error)
+
+ // Name returns a short identifier for logging ("tigris", "r2",
+ // "azure-blob"). Never empty.
+ Name() string
+}
+
+// Download is a convenience wrapper that streams an object to a local file
+// atomically (writes to dest+".tmp" and renames on success). Most callers
+// want this rather than the streaming Get.
+func Download(ctx context.Context, s Store, bucket, key, destPath string) error {
+ r, err := s.Get(ctx, bucket, key)
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+ return writeAtomic(destPath, r)
+}
+
+// Upload is a convenience wrapper that streams a local file to bucket/key.
+func Upload(ctx context.Context, s Store, bucket, key, srcPath string) error {
+ f, length, err := openSized(srcPath)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ return s.Put(ctx, bucket, key, f, length)
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index 7497551d..cedca8c7 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -146,6 +146,34 @@ type Config struct {
SentryEnvironment string
SentrySampleRate float64 // 0.0–1.0, default 1.0 (capture every error)
SentryTracesSampleRate float64 // 0.0–1.0, default 0.0 (tracing off)
+
+ // Global blob store — abstract S3-compatible backend for canonical golden
+ // rootfs blobs, template blobs, and the events archive. Currently Tigris
+ // (Region Earth global replication) but works with any S3-compatible
+ // endpoint (R2, AWS S3, GCS interop, Azure Blob via S3 compat). Switching
+ // providers is a config change; see internal/blobstore.
+ //
+ // Empty Endpoint disables — workers fall back to whatever's baked into
+ // the AMI / cloud-init copy.
+ GlobalBlobName string // logging label, e.g. "tigris" / "r2"
+ GlobalBlobEndpoint string // e.g. "https://t3.storage.dev"
+ GlobalBlobRegion string // "auto" for Tigris/R2; real region for AWS S3
+ GlobalBlobAccessKeyID string
+ GlobalBlobSecretAccessKey string
+ GlobalBlobUsePathStyle bool // true for R2/Tigris/MinIO; false for AWS S3
+ GlobalBlobGoldensBucket string
+ GlobalBlobTemplatesBucket string
+ GlobalBlobEventsBucket string
+
+ // Optional fallback backend used when the primary fails on transient errors
+ // (network / 5xx). NotFound from the primary is authoritative — fallbacks
+ // aren't consulted. Empty disables.
+ GlobalBlobFallbackName string
+ GlobalBlobFallbackEndpoint string
+ GlobalBlobFallbackRegion string
+ GlobalBlobFallbackAccessKeyID string
+ GlobalBlobFallbackSecretAccessKey string
+ GlobalBlobFallbackUsePathStyle bool
}
// Load reads configuration from environment variables with sensible defaults.
@@ -248,6 +276,23 @@ func Load() (*Config, error) {
SentryEnvironment: os.Getenv("OPENSANDBOX_SENTRY_ENVIRONMENT"),
SentrySampleRate: envOrDefaultFloat("OPENSANDBOX_SENTRY_SAMPLE_RATE", 1.0),
SentryTracesSampleRate: envOrDefaultFloat("OPENSANDBOX_SENTRY_TRACES_SAMPLE_RATE", 0.0),
+
+ GlobalBlobName: envOrDefault("OPENSANDBOX_GLOBAL_BLOB_NAME", "tigris"),
+ GlobalBlobEndpoint: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_ENDPOINT"),
+ GlobalBlobRegion: envOrDefault("OPENSANDBOX_GLOBAL_BLOB_REGION", "auto"),
+ GlobalBlobAccessKeyID: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_ACCESS_KEY_ID"),
+ GlobalBlobSecretAccessKey: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_SECRET_ACCESS_KEY"),
+ GlobalBlobUsePathStyle: envOrDefault("OPENSANDBOX_GLOBAL_BLOB_USE_PATH_STYLE", "true") == "true",
+ GlobalBlobGoldensBucket: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_GOLDENS_BUCKET"),
+ GlobalBlobTemplatesBucket: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_TEMPLATES_BUCKET"),
+ GlobalBlobEventsBucket: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_EVENTS_BUCKET"),
+
+ GlobalBlobFallbackName: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_FALLBACK_NAME"),
+ GlobalBlobFallbackEndpoint: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_FALLBACK_ENDPOINT"),
+ GlobalBlobFallbackRegion: envOrDefault("OPENSANDBOX_GLOBAL_BLOB_FALLBACK_REGION", "auto"),
+ GlobalBlobFallbackAccessKeyID: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_FALLBACK_ACCESS_KEY_ID"),
+ GlobalBlobFallbackSecretAccessKey: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_FALLBACK_SECRET_ACCESS_KEY"),
+ GlobalBlobFallbackUsePathStyle: envOrDefault("OPENSANDBOX_GLOBAL_BLOB_FALLBACK_USE_PATH_STYLE", "true") == "true",
}
if cfg.SentryEnvironment == "" {
diff --git a/internal/qemu/blobstore_fetch.go b/internal/qemu/blobstore_fetch.go
new file mode 100644
index 00000000..3e3f35b0
--- /dev/null
+++ b/internal/qemu/blobstore_fetch.go
@@ -0,0 +1,80 @@
+package qemu
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/blobstore"
+)
+
+// ensureBaseImageFromBlob makes sure ImagesDir/default.ext4 exists locally.
+// If it's already on disk, returns nil immediately (no-op for the steady
+// state where the AMI baked in default.ext4).
+//
+// Otherwise, if a global blob store is configured, fetches default.ext4
+// from {GlobalBlobGoldensBucket}/{GlobalBlobGoldenKey} and writes it to
+// ImagesDir/default.ext4 atomically.
+//
+// Used by:
+// - PrepareGoldenSnapshot (worker startup) — ensure local copy before
+// building the runtime golden snapshot
+// - First-run on a fresh cell whose AMI doesn't carry the rootfs (e.g.
+// a thin AMI shared across clouds)
+//
+// Returns nil with a log warning if blobstore is unconfigured — callers
+// proceed with whatever's local (or fail downstream with a clear error).
+func (m *Manager) ensureBaseImageFromBlob(ctx context.Context) error {
+ target := filepath.Join(m.cfg.ImagesDir, "default.ext4")
+ if fileExists(target) {
+ return nil // already cached locally
+ }
+
+ if m.cfg.GlobalBlob == nil {
+ log.Printf("qemu: %s missing and no global blob store configured", target)
+ return nil // not an error here — caller logs/handles missing rootfs
+ }
+
+ bucket := m.cfg.GlobalBlobGoldensBucket
+ key := m.cfg.GlobalBlobGoldenKey
+ if key == "" {
+ key = "default.ext4"
+ }
+ if bucket == "" {
+ return errors.New("qemu: GlobalBlobGoldensBucket required to fetch from blob store")
+ }
+
+ log.Printf("qemu: %s missing, fetching from %s://%s/%s", target, m.cfg.GlobalBlob.Name(), bucket, key)
+ t0 := time.Now()
+
+ // Use a long timeout — golden blob is multi-GB.
+ dlCtx, cancel := context.WithTimeout(ctx, 15*time.Minute)
+ defer cancel()
+
+ if err := blobstore.Download(dlCtx, m.cfg.GlobalBlob, bucket, key, target); err != nil {
+ // Clean up any half-written tmp file (Download already does this on
+ // most paths but be defensive).
+ os.Remove(target + ".tmp")
+ return fmt.Errorf("download %s/%s: %w", bucket, key, err)
+ }
+
+ // Sanity check the downloaded file is non-trivial.
+ st, err := os.Stat(target)
+ if err != nil {
+ return fmt.Errorf("stat downloaded ext4: %w", err)
+ }
+ if st.Size() < 64*1024*1024 {
+ // Anything under 64MB is almost certainly corrupt — a real rootfs
+ // is multi-GB. Refuse to proceed; let the caller surface the error.
+ os.Remove(target)
+ return fmt.Errorf("downloaded ext4 suspiciously small (%d bytes), refusing to use", st.Size())
+ }
+
+ log.Printf("qemu: fetched %s from blob store (%.1fMB, %dms)",
+ target, float64(st.Size())/(1024*1024), time.Since(t0).Milliseconds())
+ return nil
+}
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 6a4acb62..dc2312b7 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -20,6 +20,7 @@ import (
"time"
"github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/blobstore"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/storage"
"github.com/opensandbox/opensandbox/pkg/types"
@@ -170,6 +171,17 @@ type Config struct {
DefaultCPUs int
DefaultDiskMB int
DefaultPort int
+
+ // GlobalBlob is the abstract S3-compat backend (Tigris, R2, etc.) the
+ // worker pulls canonical golden rootfs blobs from on cache miss.
+ // Nil disables — worker falls back to local-only behavior (whatever
+ // the AMI baked in or cloud-init copied).
+ GlobalBlob blobstore.Store
+ GlobalBlobGoldensBucket string // e.g. "opencomputer-goldens-dev"
+ // GlobalBlobGoldenKey is the path within the goldens bucket. Defaults
+ // to "default.ext4" if empty. Versioned variants (bases/{hash}/...) are
+ // resolved by the existing checkpoint-rebase path, not this fallback.
+ GlobalBlobGoldenKey string
}
// Manager implements sandbox.Manager using QEMU VMs.
@@ -384,6 +396,13 @@ func (m *Manager) reinstallProxyCA(ctx context.Context, sandboxID string, agent
// restore from this snapshot instead of cold-booting, cutting start time
// from ~10s to ~1-2s.
func (m *Manager) PrepareGoldenSnapshot() error {
+ // Multi-region cache-miss fallback: if no local default.ext4 (e.g., this
+ // is a fresh worker on a new cell whose AMI didn't bake one in), try to
+ // pull from the configured global blob store before failing.
+ if err := m.ensureBaseImageFromBlob(context.Background()); err != nil {
+ log.Printf("qemu: blobstore golden fetch failed (will try local-only): %v", err)
+ }
+
goldenDir := filepath.Join(m.cfg.DataDir, "golden")
memFile := filepath.Join(goldenDir, "mem")
rootfsFile := filepath.Join(goldenDir, "rootfs.qcow2")