Skip to content

An open-source, faster Devin alternative

TypeScript

port abstraction

Brian Reardone21bd813971f
diff --git a/cmd/server/main.go b/cmd/server/main.go
index a6d9db78..fe2191ca 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -227,6 +227,13 @@ func main() {
"OPENSANDBOX_S3_ACCESS_KEY_ID=%s\n"+
"OPENSANDBOX_S3_SECRET_ACCESS_KEY=%s\n"+
"OPENSANDBOX_S3_FORCE_PATH_STYLE=%v\n"+
+ "OPENSANDBOX_S3_FALLBACK_ENDPOINT=%s\n"+
+ "OPENSANDBOX_S3_FALLBACK_REGION=%s\n"+
+ "OPENSANDBOX_S3_FALLBACK_ACCESS_KEY_ID=%s\n"+
+ "OPENSANDBOX_S3_FALLBACK_SECRET_ACCESS_KEY=%s\n"+
+ "OPENSANDBOX_S3_FALLBACK_FORCE_PATH_STYLE=%v\n"+
+ "OPENSANDBOX_S3_FALLBACK_BUCKET=%s\n"+
+ "OPENSANDBOX_BLOB_MIGRATION_MODE=%v\n"+
"OPENSANDBOX_SANDBOX_DOMAIN=%s\n"+
"OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB=%d\n"+
"OPENSANDBOX_AZURE_KEY_VAULT_NAME=%s\n"+
@@ -246,6 +253,13 @@ func main() {
cfg.S3AccessKeyID,
cfg.S3SecretAccessKey,
cfg.S3ForcePathStyle,
+ cfg.S3FallbackEndpoint,
+ cfg.S3FallbackRegion,
+ cfg.S3FallbackAccessKeyID,
+ cfg.S3FallbackSecretAccessKey,
+ cfg.S3FallbackForcePathStyle,
+ cfg.S3FallbackBucket,
+ cfg.BlobMigrationMode,
cfg.SandboxDomain,
cfg.DefaultSandboxDiskMB,
cfg.AzureKeyVaultName,
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 5d72fbbb..c6acec14 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -190,8 +190,12 @@ func main() {
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())
+ if cfg.BlobMigrationMode {
+ globalBlob, _ = blobstore.NewMigrationFallback(blobPrimary, blobFallback)
+ } else {
+ globalBlob, _ = blobstore.NewFallback(blobPrimary, blobFallback)
+ }
+ log.Printf("opensandbox-worker: global blob store: %s primary, %s fallback (migration=%v)", blobPrimary.Name(), blobFallback.Name(), cfg.BlobMigrationMode)
} else {
globalBlob = blobPrimary
log.Printf("opensandbox-worker: global blob store: %s (no fallback)", blobPrimary.Name())
@@ -327,22 +331,42 @@ func main() {
}
jwtIssuer := auth.NewJWTIssuer(cfg.JWTSecret)
- // S3 checkpoint store
+ // Checkpoint store — built on top of a blobstore.Store. The primary
+ // endpoint is OPENSANDBOX_S3_*; an optional secondary OPENSANDBOX_S3_FALLBACK_*
+ // provides HA / lazy-migration fallback. Migration semantics (NotFound
+ // cascades to fallback) are gated on cfg.BlobMigrationMode.
var checkpointStore *storage.CheckpointStore
if cfg.S3Bucket != "" {
- var err error
- checkpointStore, err = storage.NewCheckpointStore(storage.S3Config{
- Endpoint: cfg.S3Endpoint,
- Bucket: cfg.S3Bucket,
- Region: cfg.S3Region,
- AccessKeyID: cfg.S3AccessKeyID,
- SecretAccessKey: cfg.S3SecretAccessKey,
- ForcePathStyle: cfg.S3ForcePathStyle,
- })
+ // Primary: no bucket override (CheckpointStore passes cfg.S3Bucket per call).
+ cpPrimary, err := buildCheckpointBackend("primary", cfg.S3Endpoint, cfg.S3Region, cfg.S3AccessKeyID, cfg.S3SecretAccessKey, "", cfg.S3ForcePathStyle)
if err != nil {
- log.Fatalf("failed to initialize checkpoint store: %v", err)
+ log.Fatalf("failed to build checkpoint store primary: %v", err)
+ }
+ if cpPrimary == nil {
+ log.Fatalf("OPENSANDBOX_S3_BUCKET set but primary backend has no credentials")
+ }
+ // Fallback: if S3FallbackBucket is set, the fallback uses its own
+ // bucket name (e.g. Azure container "checkpoints") regardless of
+ // what bucket the primary uses (e.g. Tigris bucket "opencomputer-prod").
+ cpFallback, err := buildCheckpointBackend("fallback", cfg.S3FallbackEndpoint, cfg.S3FallbackRegion, cfg.S3FallbackAccessKeyID, cfg.S3FallbackSecretAccessKey, cfg.S3FallbackBucket, cfg.S3FallbackForcePathStyle)
+ if err != nil {
+ log.Fatalf("failed to build checkpoint store fallback: %v", err)
}
- log.Printf("opensandbox-worker: S3 checkpoint store configured (bucket=%s, region=%s)", cfg.S3Bucket, cfg.S3Region)
+
+ var cpStore blobstore.Store = cpPrimary
+ if cpFallback != nil {
+ if cfg.BlobMigrationMode {
+ cpStore, _ = blobstore.NewMigrationFallback(cpPrimary, cpFallback)
+ } else {
+ cpStore, _ = blobstore.NewFallback(cpPrimary, cpFallback)
+ }
+ log.Printf("opensandbox-worker: checkpoint store: %s primary, %s fallback (migration=%v)", cpPrimary.Name(), cpFallback.Name(), cfg.BlobMigrationMode)
+ } else {
+ log.Printf("opensandbox-worker: checkpoint store: %s (no fallback)", cpPrimary.Name())
+ }
+
+ checkpointStore = storage.NewCheckpointStoreFromStore(cpStore, cfg.S3Bucket)
+ log.Printf("opensandbox-worker: checkpoint store configured (bucket=%s, region=%s)", cfg.S3Bucket, cfg.S3Region)
if cfg.DataDir != "" {
cacheDir := filepath.Join(cfg.DataDir, "checkpoints")
@@ -674,6 +698,39 @@ func getDBURL(cfg *config.Config) string {
return os.Getenv("DATABASE_URL")
}
+// buildCheckpointBackend constructs a blobstore.Store for the checkpoint
+// path, picking Azure or S3-compat based on endpoint shape. Returns (nil, nil)
+// if no credentials are configured for this slot (caller treats nil as
+// "fallback disabled"). The auto-detect preserves the historical behavior of
+// storage.NewCheckpointStore.
+//
+// bucketOverride, if non-empty, tells the backend to use that bucket name
+// regardless of what bucket the caller passes at runtime. Empty means the
+// backend honors the caller's bucket (which the CheckpointStore sets to
+// cfg.S3Bucket).
+func buildCheckpointBackend(label, endpoint, region, accessKeyID, secretAccessKey, bucketOverride string, forcePathStyle bool) (blobstore.Store, error) {
+ if endpoint == "" && accessKeyID == "" && secretAccessKey == "" {
+ return nil, nil
+ }
+ if strings.Contains(endpoint, ".blob.core.windows.net") {
+ return blobstore.NewAzure(blobstore.AzureConfig{
+ Name: "azure-blob-" + label,
+ AccountName: accessKeyID,
+ AccountKey: secretAccessKey,
+ Bucket: bucketOverride,
+ })
+ }
+ return blobstore.NewS3(blobstore.S3Config{
+ Name: "s3-" + label,
+ Endpoint: endpoint,
+ Region: region,
+ AccessKeyID: accessKeyID,
+ SecretAccessKey: secretAccessKey,
+ UsePathStyle: forcePathStyle || strings.Contains(endpoint, ".blob.core.windows.net"),
+ Bucket: bucketOverride,
+ })
+}
+
// createExecSessionQEMU creates an exec session using a QEMU agent client.
func createExecSessionQEMU(agent *qm.AgentClient, sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {
agentPB := &agentpb.ExecSessionCreateRequest{
diff --git a/docs/blobstore-tigris-cutover.md b/docs/blobstore-tigris-cutover.md
index 0f4fc50b..c5335927 100644
--- a/docs/blobstore-tigris-cutover.md
+++ b/docs/blobstore-tigris-cutover.md
@@ -1,173 +1,218 @@
# 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.
+Zero-downtime migration of all worker object storage (checkpoints,
+hibernation archives, templates, goldens) from Azure Blob to Tigris using
+`internal/blobstore.FallbackStore` in migration mode as the safety net during
+the soak window.
-## 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.
+> **Why not Tigris shadow buckets?** Tigris shadow buckets require an
+> S3-compatible source endpoint. Azure Blob has no native S3 API, so shadow
+> buckets don't apply without a separate S3↔Azure gateway. `FallbackStore`
+> accomplishes the same goal (transparent fallback on cold reads) entirely
+> in-process — no extra infrastructure.
-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
+## What this covers
-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
+| Data | Old backend | Cutover mechanism |
+|---|---|---|
+| Checkpoints / hibernation archives / templates | Azure Blob | rclone bulk copy + FallbackStore in migration mode |
+| Goldens (`bases/<version>/default.ext4`) | Azure Blob | same |
+| pg-backups / pg-wal | Azure Blob | Out of scope (managed by separate path) |
-Lazy migration via shadow bucket avoids paying egress on cold objects that are
-never accessed.
+All worker-managed paths flow through `internal/blobstore.Store`, so a
+single set of env-var changes switches them all.
-## Phase 0 — Pre-flight (zero prod impact)
+## How worker.env is sourced
-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):
+Worker `/etc/opensandbox/worker.env` is **not** baked into the AMI. The
+control plane generates it per-VM at spawn time from its own `cfg`
+(loaded from `/etc/opensandbox/server.env` on the CP):
```
-# On any worker with the env vars set:
-opensandbox-worker golden-upload /data/firecracker/images/default.ext4
+server.env on CP → CP cfg → workerEnv template → cloud-init userdata → worker.env on each VM
```
-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.
+Practical consequence: **for env-var-only changes, you edit `server.env`
+on the CP and cycle workers. No AMI rebake needed.** AMI rebakes are only
+required for binary or system-level changes.
-## Phase 3 — Atomic flip (no downtime)
+> The `workerEnv` template lives in `cmd/server/main.go`. If you add new
+> env vars that workers need, the template must be updated to propagate
+> them. This PR added `OPENSANDBOX_S3_FALLBACK_*` and
+> `OPENSANDBOX_BLOB_MIGRATION_MODE` to the template.
-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.
+## Pre-flight inventory (prod, opencomputer-prod RG, eastus2)
-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)
+- Storage account: `occkpt3ccf3c31`
+- `checkpoints` container: ~1,854 blobs, ~2.08 TB (includes goldens in
+ `bases/<hash>/default.ext4`)
+- `pg-backups` / `pg-wal`: managed by postgres infra, not part of this cutover
-## Phase 4 — Drain (background, optional)
+## Tigris target
-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
-```
+- Bucket: `opencomputer-prod` (Region Earth or `iad`, snapshots enabled)
+- Layout: identical to Azure — rclone copies keys verbatim; no key
+ rewriting required
+- Per-backend bucket override is available: primary uses Tigris bucket
+ `opencomputer-prod`, fallback uses Azure container `checkpoints`,
+ configured via `OPENSANDBOX_S3_FALLBACK_BUCKET`
-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 1 — Ship the new binary (one AMI bake)
-## Phase 5 — Soak
+**Goal**: get the new code into the worker pool. No behavior change yet
+(`OPENSANDBOX_S3_FALLBACK_*` unset means workers log "no fallback" and
+behave identically to before).
-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.
+1. Merge the PR.
+2. CI builds a new worker AMI (`.github/workflows/build-worker-ami.yml`)
+ and bumps KV `worker-image-version`.
+3. Scaler does its normal rolling-replace.
+4. Verify all workers report the new version via `GET /api/workers`.
+5. Smoke test: create / hibernate / wake. Behavior identical.
-## Phase 6 — Cut shadow
+**Rollback**: bump KV `worker-image-version` back. Scaler rolls back.
-Once drained (or after sufficient soak with lazy migration):
+## Phase 2 — Bulk rclone Azure → Tigris
-```
-tigris buckets set-migration opencomputer-checkpoints --disable
-# repeat for other buckets
-```
+**Goal**: get ~all checkpoint data into Tigris before flipping. Workers
+still on Azure — zero production impact.
-Workers now read/write Tigris-only.
+1. Run `scripts/rclone-azure-to-tigris.sh` from a bastion VM in eastus2.
+ - ~2 TB, ~1-3 hours on D4-class network (depends on bastion size)
+2. Required rclone flags (already in the script):
+ - `--s3-storage-class STANDARD` — Tigris rejects Azure's `Hot`/`Cool`
+ tier names; force STANDARD or every PUT fails with 400 InvalidStorageClass
+ - `--metadata=false` — skip Azure-specific metadata to avoid edge-case
+ translation issues
+3. Parity check when done:
+ ```
+ rclone size az:checkpoints
+ rclone size tigris:opencomputer-prod
+ ```
+ Sizes should match within a small delta (new writes during the run).
-## Phase 7 — Decom Azure
+**Rollback**: nothing to undo. Abandon Tigris copy; costs nothing.
-After the retention window (suggest 30 days) and zero observed reads from
-Azure side:
+## Phase 3 — Atomic flip (server.env + CP restart + worker cycle)
-```
-az storage container delete --account-name occkpt3ccf3c31 -n checkpoints
-az storage account delete -g opencomputer-prod -n occkpt3ccf3c31
-```
+**Goal**: workers start writing to Tigris and reading Tigris-then-Azure.
-## Rollback
+1. **Delta rclone sync** — run again right before the next step. Picks
+ up anything written to Azure since Phase 2. Should be fast (minutes).
-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
+2. **Edit `/etc/opensandbox/server.env`** on the control plane to add the
+ Tigris primary, Azure fallback, and migration-mode flag:
+ ```
+ # Primary: Tigris
+ OPENSANDBOX_S3_ENDPOINT=https://t3.storage.dev
+ OPENSANDBOX_S3_BUCKET=opencomputer-prod
+ OPENSANDBOX_S3_REGION=auto
+ OPENSANDBOX_S3_FORCE_PATH_STYLE=true
+ OPENSANDBOX_S3_ACCESS_KEY_ID=<tigris key>
+ OPENSANDBOX_S3_SECRET_ACCESS_KEY=<tigris secret>
+
+ # Fallback: Azure
+ OPENSANDBOX_S3_FALLBACK_ENDPOINT=https://occkpt3ccf3c31.blob.core.windows.net
+ OPENSANDBOX_S3_FALLBACK_REGION=eastus2
+ OPENSANDBOX_S3_FALLBACK_ACCESS_KEY_ID=occkpt3ccf3c31
+ OPENSANDBOX_S3_FALLBACK_SECRET_ACCESS_KEY=<azure key>
+ OPENSANDBOX_S3_FALLBACK_BUCKET=checkpoints
+
+ # Lazy-migration: Tigris-miss falls through to Azure
+ OPENSANDBOX_BLOB_MIGRATION_MODE=true
+ ```
-## Open question
+3. **Restart the control plane**:
+ ```
+ systemctl restart opensandbox-server
+ ```
+ Re-reads `server.env`. From now on, every new worker spawned by the
+ scaler is templated with the new env via cloud-init.
+
+4. **Cycle workers** — two options:
+ - **Soft (gradual)**: do nothing. Existing workers keep their old env
+ until the scaler cycles them (could be hours/days). Mixed pool during
+ the window is fine — cross-worker ops still work because the
+ new-config workers can fallback-read whatever the old-config workers
+ wrote. The reverse direction (new writes Tigris, old needs to read)
+ is avoided by the scaler's drain semantics — old workers are drained,
+ not given new placements.
+ - **Aggressive (forced)**: delete workers one at a time via
+ `az vm delete -g opencomputer-prod -n osb-worker-<id>`. Scaler
+ replaces each with a new VM that gets the new env. Whole pool
+ flipped in minutes.
+
+5. **Verify** as each worker cycles, log line:
+ ```
+ checkpoint store: tigris primary, azure-blob-fallback fallback (migration=true)
+ ```
-`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.
+**Rollback**: revert `server.env`, restart CP, cycle workers. Data
+already in Tigris stays there (passive replica); Azure remains
+authoritative throughout the soak window.
+
+## Phase 4 — Soak (1–2 weeks)
+
+Monitor:
+- Worker logs for `blobstore: primary tigris failed (...); trying fallback azure-blob` — expected near-zero and trending down as the warm working set lands in Tigris.
+- Tigris dashboard: error rate, latency, ingress volume.
+- Synthetic daily test: create / checkpoint / fork on another worker / hibernate / wake.
+
+If fallback hit rate stays elevated, run another delta rclone sync to
+warm cold keys into Tigris proactively.
+
+## Phase 5 — Disable fallback (commit to Tigris)
+
+1. Edit `server.env`: remove the `OPENSANDBOX_S3_FALLBACK_*` block and
+ `OPENSANDBOX_BLOB_MIGRATION_MODE`.
+2. Restart CP.
+3. Cycle workers (same options as Phase 3 step 4).
+4. Verify log: `checkpoint store: tigris primary (no fallback)`.
+
+**Rollback past this point** is harder. Re-adding the fallback re-enables
+the safety net, but any keys written to Tigris during the no-fallback
+window don't exist in Azure. If Azure must become authoritative again,
+run a reverse rclone (Tigris → Azure). Don't enter this phase until
+Phase 4 has been clean for at least a week.
+
+## Phase 6 — Decommission Azure
+
+After ~30 days of zero observed reads on the Azure side (verify via Azure
+storage metrics):
+
+1. Snapshot the `checkpoints` container to a different storage account
+ as a one-time backup (optional).
+2. `az storage container delete --account-name occkpt3ccf3c31 -n checkpoints`
+3. Eventually delete the storage account.
+
+## Operational rules
+
+- **Never `systemctl restart opensandbox-worker` by hand in prod.** The
+ scaler treats the heartbeat gap as "worker unhealthy" and replaces the
+ VM from the current AMI — losing any local state. We hit this during
+ dev validation. Always cycle workers by deleting them so the scaler
+ replaces them cleanly.
+
+- **Don't hold the leader lock in prod.** Holding
+ `controlplane:leader = MAINTENANCE-HOLD` pauses the scaler — including
+ the rolling-replace that the cutover relies on. The lock trick is for
+ one-off dev hot-swaps only.
+
+- **Live migration during the rolling window works** because the new
+ workers are in migration mode. Drain direction is OLD → NEW: old
+ worker writes drives to Azure, new worker reads Tigris (miss) →
+ fallback to Azure (hit) → migration succeeds. The reverse direction
+ (NEW writes, OLD reads) doesn't happen — old workers are being
+ drained, not receiving new placements.
+
+## Code surface
+
+- `internal/blobstore/store.go` — `Store` interface (Get / GetRange / Put / Head / Exists / Delete / Name)
+- `internal/blobstore/s3.go` — S3-compatible backend (Tigris, R2, AWS S3, MinIO); supports per-backend `Bucket` override
+- `internal/blobstore/azure.go` — Azure Blob backend; same `Bucket` override pattern
+- `internal/blobstore/fallback.go` — `FallbackStore` with `NewFallback` (HA mode) and `NewMigrationFallback` (lazy-migration mode)
+- `internal/storage/s3.go` — `CheckpointStore` higher-level type, built on top of `blobstore.Store`
+- `cmd/server/main.go` — `workerEnv` template propagates `OPENSANDBOX_S3_FALLBACK_*` and `OPENSANDBOX_BLOB_MIGRATION_MODE` to each spawned worker
+- `cmd/worker/main.go` — `buildCheckpointBackend` helper; combines primary + fallback for the checkpoint path
+- `internal/config/config.go` — env-var parsing for the new vars
+- `scripts/rclone-azure-to-tigris.sh` — bulk + delta rclone driver (with `--s3-storage-class STANDARD --metadata=false`)
diff --git a/internal/blobstore/azure.go b/internal/blobstore/azure.go
new file mode 100644
index 00000000..86eb2590
--- /dev/null
+++ b/internal/blobstore/azure.go
@@ -0,0 +1,204 @@
+package blobstore
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "strings"
+ "sync"
+
+ "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
+ "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"
+)
+
+// AzureConfig configures an Azure Blob backend.
+type AzureConfig struct {
+ Name string // logging label, e.g. "azure-blob"
+ AccountName string
+ AccountKey string
+
+ // Bucket (Azure container), if set, overrides any bucket argument passed
+ // at runtime. Use this to give the Azure backend its own container name
+ // — e.g. caller uses Tigris bucket "opencomputer-prod" but the Azure
+ // fallback should read from container "checkpoints".
+ Bucket string
+}
+
+// azureStore implements Store against Azure Blob Storage. We dial the SDK
+// lazily on first use so a worker that never touches the fallback never
+// opens an Azure connection (and never logs Azure 401s if creds are wrong).
+type azureStore struct {
+ name string
+ bucket string // container override; empty means use caller's runtime bucket
+ connStr string
+
+ mu sync.Mutex
+ client *azblob.Client
+}
+
+// NewAzure constructs an Azure Blob backed Store. Returns nil, nil when
+// account + key are both empty (caller treats nil as "this backend
+// disabled, fall through to next").
+func NewAzure(cfg AzureConfig) (Store, error) {
+ if cfg.AccountName == "" && cfg.AccountKey == "" {
+ return nil, nil
+ }
+ if cfg.AccountName == "" || cfg.AccountKey == "" {
+ return nil, fmt.Errorf("blobstore: Azure requires both AccountName and AccountKey")
+ }
+ if cfg.Name == "" {
+ cfg.Name = "azure-blob"
+ }
+ connStr := fmt.Sprintf(
+ "DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=core.windows.net",
+ cfg.AccountName, cfg.AccountKey,
+ )
+ return &azureStore{name: cfg.Name, bucket: cfg.Bucket, connStr: connStr}, nil
+}
+
+func (a *azureStore) Name() string { return a.name }
+
+// resolveBucket returns the configured container if set, else the caller's bucket.
+func (a *azureStore) resolveBucket(bucket string) string {
+ if a.bucket != "" {
+ return a.bucket
+ }
+ return bucket
+}
+
+func (a *azureStore) ensureClient() error {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if a.client != nil {
+ return nil
+ }
+ c, err := azblob.NewClientFromConnectionString(a.connStr, nil)
+ if err != nil {
+ return fmt.Errorf("%s connect: %w", a.name, err)
+ }
+ a.client = c
+ return nil
+}
+
+// normalizeKey strips a leading "<bucket>/" if present. S3-style keys often
+// embed the bucket name (e.g. "checkpoints/sb-xxx/..."); Azure addresses
+// container + blob name separately, so we drop the redundant prefix.
+func normalizeKey(bucket, key string) string {
+ if trimmed, ok := strings.CutPrefix(key, bucket+"/"); ok {
+ return trimmed
+ }
+ return key
+}
+
+func (a *azureStore) wrapNotFound(err error, bucket, key, op string) error {
+ if err == nil {
+ return nil
+ }
+ if bloberror.HasCode(err, bloberror.BlobNotFound) || bloberror.HasCode(err, bloberror.ContainerNotFound) {
+ return fmt.Errorf("%s://%s/%s: %w", a.name, bucket, key, ErrNotFound)
+ }
+ return fmt.Errorf("%s %s %s/%s: %w", a.name, op, bucket, key, err)
+}
+
+func (a *azureStore) Get(ctx context.Context, bucket, key string) (io.ReadCloser, error) {
+ if err := a.ensureClient(); err != nil {
+ return nil, err
+ }
+ c := a.resolveBucket(bucket)
+ resp, err := a.client.DownloadStream(ctx, c, normalizeKey(c, key), nil)
+ if err != nil {
+ return nil, a.wrapNotFound(err, c, key, "DownloadStream")
+ }
+ return resp.Body, nil
+}
+
+func (a *azureStore) GetRange(ctx context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error) {
+ if err := a.ensureClient(); err != nil {
+ return nil, err
+ }
+ c := a.resolveBucket(bucket)
+ resp, err := a.client.DownloadStream(ctx, c, normalizeKey(c, key), &azblob.DownloadStreamOptions{
+ Range: azblob.HTTPRange{Offset: offset, Count: length},
+ })
+ if err != nil {
+ return nil, a.wrapNotFound(err, c, key, "DownloadStream(range)")
+ }
+ return resp.Body, nil
+}
+
+// uploadStreamOpts is shared by every Put. The Azure SDK's nil-default is
+// BlockSize=1MB / Concurrency=1, a serial chain of small PutBlock calls that's
+// HTTP-overhead bound at 30–60 MB/s per blob — that turned a 10 GB checkpoint
+// into a 5+ minute upload. The values below are sized for a 64-vCPU worker
+// (D-series, ~30 Gbps NIC, Premium SSD ~700 MB/s read):
+//
+// - BlockSize 8 MB amortizes PutBlock HTTP overhead (~10x fewer round-trips
+// than the SDK default); per-blob in-flight memory stays bounded under
+// concurrent uploads.
+// - Concurrency 8 keeps the worker NIC fed when HTTP latency dominates a
+// single block. Per-upload buffer is 8 × 8 MB = 64 MB, negligible vs RAM.
+//
+// Practical ceiling per blob is ~600–1000 MB/s — already above the disk-read
+// rate at which bytes can be fed from the on-disk archive. Bumping further
+// just wastes memory.
+var azureUploadStreamOpts = &azblob.UploadStreamOptions{
+ BlockSize: 8 * 1024 * 1024,
+ Concurrency: 8,
+}
+
+func (a *azureStore) Put(ctx context.Context, bucket, key string, body io.Reader, contentLength int64) error {
+ if err := a.ensureClient(); err != nil {
+ return err
+ }
+ c := a.resolveBucket(bucket)
+ _, err := a.client.UploadStream(ctx, c, normalizeKey(c, key), body, azureUploadStreamOpts)
+ if err != nil {
+ return fmt.Errorf("%s UploadStream %s/%s: %w", a.name, c, key, err)
+ }
+ return nil
+}
+
+func (a *azureStore) Head(ctx context.Context, bucket, key string) (int64, error) {
+ if err := a.ensureClient(); err != nil {
+ return 0, err
+ }
+ c := a.resolveBucket(bucket)
+ resp, err := a.client.ServiceClient().
+ NewContainerClient(c).
+ NewBlobClient(normalizeKey(c, key)).
+ GetProperties(ctx, nil)
+ if err != nil {
+ return 0, a.wrapNotFound(err, c, key, "GetProperties")
+ }
+ if resp.ContentLength == nil {
+ return 0, nil
+ }
+ return *resp.ContentLength, nil
+}
+
+func (a *azureStore) Exists(ctx context.Context, bucket, key string) (bool, error) {
+ _, err := a.Head(ctx, bucket, key)
+ if err == nil {
+ return true, nil
+ }
+ if isNotFound(err) {
+ return false, nil
+ }
+ return false, err
+}
+
+func (a *azureStore) Delete(ctx context.Context, bucket, key string) error {
+ if err := a.ensureClient(); err != nil {
+ return err
+ }
+ c := a.resolveBucket(bucket)
+ _, err := a.client.DeleteBlob(ctx, c, normalizeKey(c, key), nil)
+ if err != nil {
+ // Idempotent: not-found is success.
+ if bloberror.HasCode(err, bloberror.BlobNotFound) {
+ return nil
+ }
+ return fmt.Errorf("%s DeleteBlob %s/%s: %w", a.name, c, key, err)
+ }
+ return nil
+}
diff --git a/internal/blobstore/fallback.go b/internal/blobstore/fallback.go
index 199b3452..2dbc6a67 100644
--- a/internal/blobstore/fallback.go
+++ b/internal/blobstore/fallback.go
@@ -9,25 +9,45 @@ import (
)
// 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.
+// Reads (Get / GetRange / Head / Exists) try the primary first; on transient
+// errors (network, 5xx) they cascade through fallbacks. NotFound is normally
+// authoritative on primary — we don't try fallbacks for missing objects —
+// because resurrecting deleted state from a stale mirror is surprising.
//
-// Writes (Put) go to the primary only — multi-write would create
-// consistency challenges and is overkill for the use case.
+// During a backend migration (e.g. lazy Tigris cutover with Azure as the
+// safety net), set TryFallbacksOnNotFound=true so a miss on primary falls
+// through to fallbacks. Flip back to false once the soak window closes.
//
-// 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).
+// Writes (Put / Delete) go to the primary only — dual-write would create
+// consistency challenges and is overkill for the migration use case.
+//
+// Use case: Tigris primary, Azure fallback during cutover. While running
+// FallbackStore in migration mode, any cold key that hasn't yet been
+// rclone-synced into Tigris transparently fetches from Azure.
type FallbackStore struct {
- primary Store
- fallbacks []Store
+ primary Store
+ fallbacks []Store
+ TryFallbacksOnNotFound bool
}
-// 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).
+// NewFallback wraps primary with fallback Stores in HA mode: fallbacks are
+// consulted only on transient errors from primary. NotFound on primary is
+// authoritative. 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) {
+ return newFallback(false, primary, fallbacks...)
+}
+
+// NewMigrationFallback wraps primary with fallback Stores in migration mode:
+// NotFound on primary cascades through fallbacks too. Use during a backend
+// cutover where the primary is being lazily populated (e.g. Tigris primary,
+// Azure fallback during the soak window). Switch back to NewFallback (or
+// remove the fallback entirely) once the migration completes.
+func NewMigrationFallback(primary Store, fallbacks ...Store) (Store, error) {
+ return newFallback(true, primary, fallbacks...)
+}
+
+func newFallback(migrationMode bool, primary Store, fallbacks ...Store) (Store, error) {
if primary == nil {
return nil, errors.New("blobstore: FallbackStore requires non-nil primary")
}
@@ -40,7 +60,11 @@ func NewFallback(primary Store, fallbacks ...Store) (Store, error) {
if len(cleaned) == 0 {
return primary, nil // no fallbacks configured — just return primary
}
- return &FallbackStore{primary: primary, fallbacks: cleaned}, nil
+ return &FallbackStore{
+ primary: primary,
+ fallbacks: cleaned,
+ TryFallbacksOnNotFound: migrationMode,
+ }, nil
}
func (f *FallbackStore) Name() string {
@@ -51,13 +75,24 @@ func (f *FallbackStore) Name() string {
return names
}
+// shouldFallThrough is the shared policy across read methods. Transient
+// errors always cascade. NotFound only cascades when migration mode is on.
+func (f *FallbackStore) shouldFallThrough(err error) bool {
+ if err == nil {
+ return false
+ }
+ if errors.Is(err, ErrNotFound) {
+ return f.TryFallbacksOnNotFound
+ }
+ return true
+}
+
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.
+ if !f.shouldFallThrough(err) {
return nil, err
}
for i, fb := range f.fallbacks {
@@ -68,8 +103,29 @@ func (f *FallbackStore) Get(ctx context.Context, bucket, key string) (io.ReadClo
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) GetRange(ctx context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error) {
+ r, err := f.primary.GetRange(ctx, bucket, key, offset, length)
+ if err == nil {
+ return r, nil
+ }
+ if !f.shouldFallThrough(err) {
+ return nil, err
+ }
+ for i, fb := range f.fallbacks {
+ log.Printf("blobstore: primary %s GetRange failed (%v); trying fallback %s [%d/%d]",
+ f.primary.Name(), err, fb.Name(), i+1, len(f.fallbacks))
+ r2, err2 := fb.GetRange(ctx, bucket, key, offset, length)
+ if err2 == nil {
+ return r2, nil
+ }
+ if errors.Is(err2, ErrNotFound) {
return nil, err2
}
err = err2
@@ -82,17 +138,59 @@ func (f *FallbackStore) Put(ctx context.Context, bucket, key string, body io.Rea
return f.primary.Put(ctx, bucket, key, body, contentLength)
}
+func (f *FallbackStore) Head(ctx context.Context, bucket, key string) (int64, error) {
+ n, err := f.primary.Head(ctx, bucket, key)
+ if err == nil {
+ return n, nil
+ }
+ if !f.shouldFallThrough(err) {
+ return 0, err
+ }
+ for _, fb := range f.fallbacks {
+ n2, err2 := fb.Head(ctx, bucket, key)
+ if err2 == nil {
+ return n2, nil
+ }
+ if errors.Is(err2, ErrNotFound) {
+ return 0, err2
+ }
+ err = err2
+ }
+ return 0, err
+}
+
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
+ if ok || !f.TryFallbacksOnNotFound {
+ return ok, nil
+ }
+ // Primary returned (false, nil) — "not found" but no error. In migration
+ // mode, treat that the same as ErrNotFound and ask fallbacks too.
+ }
+ if err != nil && !f.shouldFallThrough(err) {
+ return false, err
}
for _, fb := range f.fallbacks {
ok2, err2 := fb.Exists(ctx, bucket, key)
if err2 == nil {
- return ok2, nil
+ if ok2 {
+ return true, nil
+ }
+ continue
}
err = err2
}
- return false, err
+ if err != nil {
+ return false, err
+ }
+ return false, nil
+}
+
+func (f *FallbackStore) Delete(ctx context.Context, bucket, key string) error {
+ // Deletes go only to primary. Migration mode does not propagate deletes
+ // to the fallback — that would defeat lazy migration by removing the
+ // authoritative copy from the old backend before its data is fully
+ // mirrored.
+ return f.primary.Delete(ctx, bucket, key)
}
diff --git a/internal/blobstore/fallback_live_test.go b/internal/blobstore/fallback_live_test.go
new file mode 100644
index 00000000..7f3c83fa
--- /dev/null
+++ b/internal/blobstore/fallback_live_test.go
@@ -0,0 +1,94 @@
+package blobstore_test
+
+import (
+ "context"
+ "errors"
+ "io"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/blobstore"
+)
+
+// TestFallback_LiveMigration exercises NewMigrationFallback against a real
+// Tigris primary + Azure fallback. Skipped unless these env vars are set:
+//
+// BLOBSTORE_TEST_ENDPOINT https://t3.storage.dev
+// BLOBSTORE_TEST_ACCESS_KEY tid_...
+// BLOBSTORE_TEST_SECRET_KEY tsec_...
+// BLOBSTORE_TEST_BUCKET tigris bucket name
+// BLOBSTORE_TEST_AZURE_ACCOUNT azure storage account name
+// BLOBSTORE_TEST_AZURE_KEY azure account key
+// BLOBSTORE_TEST_AZURE_CONTAINER azure container override
+// BLOBSTORE_TEST_PROBE_KEY a key that exists in Azure but NOT Tigris
+//
+// Confirms: migration mode falls through to Azure on Tigris NotFound; HA
+// mode does NOT fall through.
+func TestFallback_LiveMigration(t *testing.T) {
+ endpoint := os.Getenv("BLOBSTORE_TEST_ENDPOINT")
+ azureAccount := os.Getenv("BLOBSTORE_TEST_AZURE_ACCOUNT")
+ probeKey := os.Getenv("BLOBSTORE_TEST_PROBE_KEY")
+ if endpoint == "" || azureAccount == "" || probeKey == "" {
+ t.Skip("BLOBSTORE_TEST_* + AZURE_* + PROBE_KEY env not set; skipping live migration smoke")
+ }
+
+ primary, err := blobstore.NewS3(blobstore.S3Config{
+ Name: "tigris",
+ Endpoint: endpoint,
+ Region: "auto",
+ AccessKeyID: os.Getenv("BLOBSTORE_TEST_ACCESS_KEY"),
+ SecretAccessKey: os.Getenv("BLOBSTORE_TEST_SECRET_KEY"),
+ UsePathStyle: true,
+ Bucket: os.Getenv("BLOBSTORE_TEST_BUCKET"),
+ })
+ if err != nil {
+ t.Fatalf("NewS3 primary: %v", err)
+ }
+ fallback, err := blobstore.NewAzure(blobstore.AzureConfig{
+ Name: "azure-blob",
+ AccountName: azureAccount,
+ AccountKey: os.Getenv("BLOBSTORE_TEST_AZURE_KEY"),
+ Bucket: os.Getenv("BLOBSTORE_TEST_AZURE_CONTAINER"),
+ })
+ if err != nil {
+ t.Fatalf("NewAzure fallback: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ t.Run("MigrationMode_FallsThroughOnNotFound", func(t *testing.T) {
+ store, err := blobstore.NewMigrationFallback(primary, fallback)
+ if err != nil {
+ t.Fatalf("NewMigrationFallback: %v", err)
+ }
+ // Caller passes the primary's bucket (Tigris); fallback override
+ // rewrites to its own container.
+ r, err := store.Get(ctx, "ignored-because-overridden", probeKey)
+ if err != nil {
+ t.Fatalf("Get via migration fallback: %v", err)
+ }
+ body, err := io.ReadAll(r)
+ r.Close()
+ if err != nil {
+ t.Fatalf("read: %v", err)
+ }
+ if len(body) == 0 {
+ t.Fatalf("expected non-empty body from Azure fallback, got 0 bytes")
+ }
+ t.Logf("MIGRATION: fetched %d bytes from %s via fallback chain (probe=%q)", len(body), store.Name(), probeKey)
+ })
+
+ t.Run("HAMode_DoesNotFallThroughOnNotFound", func(t *testing.T) {
+ store, err := blobstore.NewFallback(primary, fallback)
+ if err != nil {
+ t.Fatalf("NewFallback: %v", err)
+ }
+ _, err = store.Get(ctx, "ignored", probeKey)
+ if !errors.Is(err, blobstore.ErrNotFound) {
+ t.Fatalf("HA mode: want ErrNotFound (primary authoritative), got %v", err)
+ }
+ t.Logf("HA: got expected ErrNotFound from primary (no fall-through)")
+ })
+}
diff --git a/internal/blobstore/s3.go b/internal/blobstore/s3.go
index 2f80a60e..f5a9a98b 100644
--- a/internal/blobstore/s3.go
+++ b/internal/blobstore/s3.go
@@ -21,12 +21,19 @@ type S3Config struct {
AccessKeyID string
SecretAccessKey string
UsePathStyle bool // true for R2/Tigris/MinIO; false for AWS S3.
+
+ // Bucket, if set, overrides any bucket argument passed at runtime. Use
+ // this to give each backend its own bucket name — useful when primary
+ // and fallback live in different namespaces (e.g. Tigris bucket
+ // "opencomputer-prod" + Azure container "checkpoints").
+ Bucket string
}
// s3Store is an S3-compatible backend.
type s3Store struct {
- name string
- s3 *s3.Client
+ name string
+ bucket string // override; empty means use caller's runtime bucket
+ s3 *s3.Client
}
// NewS3 constructs an S3-compatible Store. Returns nil, nil if Endpoint
@@ -55,41 +62,87 @@ func NewS3(cfg S3Config) (Store, error) {
}
o.UsePathStyle = cfg.UsePathStyle
})
- return &s3Store{name: cfg.Name, s3: client}, nil
+ return &s3Store{name: cfg.Name, bucket: cfg.Bucket, s3: client}, nil
}
func (s *s3Store) Name() string { return s.name }
+// resolveBucket returns the override if configured, else the caller's bucket.
+func (s *s3Store) resolveBucket(bucket string) string {
+ if s.bucket != "" {
+ return s.bucket
+ }
+ return bucket
+}
+
func (s *s3Store) Get(ctx context.Context, bucket, key string) (io.ReadCloser, error) {
+ b := s.resolveBucket(bucket)
out, err := s.s3.GetObject(ctx, &s3.GetObjectInput{
- Bucket: &bucket,
+ Bucket: &b,
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://%s/%s: %w", s.name, b, key, ErrNotFound)
}
- return nil, fmt.Errorf("%s GetObject %s/%s: %w", s.name, bucket, key, err)
+ return nil, fmt.Errorf("%s GetObject %s/%s: %w", s.name, b, key, err)
+ }
+ return out.Body, nil
+}
+
+func (s *s3Store) GetRange(ctx context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error) {
+ b := s.resolveBucket(bucket)
+ rangeStr := fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)
+ out, err := s.s3.GetObject(ctx, &s3.GetObjectInput{
+ Bucket: &b,
+ Key: &key,
+ Range: &rangeStr,
+ })
+ if err != nil {
+ if isNotFound(err) {
+ return nil, fmt.Errorf("%s://%s/%s: %w", s.name, b, key, ErrNotFound)
+ }
+ return nil, fmt.Errorf("%s GetObject(range=%s) %s/%s: %w", s.name, rangeStr, b, key, err)
}
return out.Body, nil
}
func (s *s3Store) Put(ctx context.Context, bucket, key string, body io.Reader, contentLength int64) error {
+ b := s.resolveBucket(bucket)
_, err := s.s3.PutObject(ctx, &s3.PutObjectInput{
- Bucket: &bucket,
+ Bucket: &b,
Key: &key,
Body: body,
ContentLength: &contentLength,
})
if err != nil {
- return fmt.Errorf("%s PutObject %s/%s: %w", s.name, bucket, key, err)
+ return fmt.Errorf("%s PutObject %s/%s: %w", s.name, b, key, err)
}
return nil
}
+func (s *s3Store) Head(ctx context.Context, bucket, key string) (int64, error) {
+ b := s.resolveBucket(bucket)
+ out, err := s.s3.HeadObject(ctx, &s3.HeadObjectInput{
+ Bucket: &b,
+ Key: &key,
+ })
+ if err != nil {
+ if isNotFound(err) {
+ return 0, fmt.Errorf("%s://%s/%s: %w", s.name, b, key, ErrNotFound)
+ }
+ return 0, fmt.Errorf("%s HeadObject %s/%s: %w", s.name, b, key, err)
+ }
+ if out.ContentLength == nil {
+ return 0, nil
+ }
+ return *out.ContentLength, nil
+}
+
func (s *s3Store) Exists(ctx context.Context, bucket, key string) (bool, error) {
+ b := s.resolveBucket(bucket)
_, err := s.s3.HeadObject(ctx, &s3.HeadObjectInput{
- Bucket: &bucket,
+ Bucket: &b,
Key: &key,
})
if err == nil {
@@ -98,7 +151,19 @@ func (s *s3Store) Exists(ctx context.Context, bucket, key string) (bool, error)
if isNotFound(err) {
return false, nil
}
- return false, fmt.Errorf("%s HeadObject %s/%s: %w", s.name, bucket, key, err)
+ return false, fmt.Errorf("%s HeadObject %s/%s: %w", s.name, b, key, err)
+}
+
+func (s *s3Store) Delete(ctx context.Context, bucket, key string) error {
+ b := s.resolveBucket(bucket)
+ _, err := s.s3.DeleteObject(ctx, &s3.DeleteObjectInput{
+ Bucket: &b,
+ Key: &key,
+ })
+ if err != nil {
+ return fmt.Errorf("%s DeleteObject %s/%s: %w", s.name, b, key, err)
+ }
+ return nil
}
// isNotFound matches the various ways the v2 SDK signals 404. The typed
diff --git a/internal/blobstore/s3_smoke_test.go b/internal/blobstore/s3_smoke_test.go
new file mode 100644
index 00000000..33953d69
--- /dev/null
+++ b/internal/blobstore/s3_smoke_test.go
@@ -0,0 +1,104 @@
+package blobstore_test
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "io"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/blobstore"
+)
+
+// TestS3_Smoke exercises Put + Get + Exists against a real S3-compatible
+// endpoint. Skipped unless these env vars are set:
+//
+// BLOBSTORE_TEST_ENDPOINT - e.g. https://t3.storage.dev
+// BLOBSTORE_TEST_ACCESS_KEY - access key id
+// BLOBSTORE_TEST_SECRET_KEY - secret access key
+// BLOBSTORE_TEST_BUCKET - bucket name (must exist)
+// BLOBSTORE_TEST_REGION - optional, defaults to "auto"
+//
+// Designed to run against Tigris but works with any S3-compat backend.
+func TestS3_Smoke(t *testing.T) {
+ endpoint := os.Getenv("BLOBSTORE_TEST_ENDPOINT")
+ accessKey := os.Getenv("BLOBSTORE_TEST_ACCESS_KEY")
+ secretKey := os.Getenv("BLOBSTORE_TEST_SECRET_KEY")
+ bucket := os.Getenv("BLOBSTORE_TEST_BUCKET")
+ if endpoint == "" || accessKey == "" || secretKey == "" || bucket == "" {
+ t.Skip("BLOBSTORE_TEST_* env not set; skipping live smoke")
+ }
+ region := os.Getenv("BLOBSTORE_TEST_REGION")
+ if region == "" {
+ region = "auto"
+ }
+
+ store, err := blobstore.NewS3(blobstore.S3Config{
+ Name: "smoke-test",
+ Endpoint: endpoint,
+ Region: region,
+ AccessKeyID: accessKey,
+ SecretAccessKey: secretKey,
+ UsePathStyle: true,
+ })
+ if err != nil {
+ t.Fatalf("NewS3: %v", err)
+ }
+ if store == nil {
+ t.Fatal("NewS3 returned nil with no error")
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ key := "blobstore-smoke/" + time.Now().Format("20060102-150405.000")
+ payload := []byte("hello tigris from blobstore smoke test\n")
+
+ // Put
+ if err := store.Put(ctx, bucket, key, bytes.NewReader(payload), int64(len(payload))); err != nil {
+ t.Fatalf("Put: %v", err)
+ }
+ t.Logf("Put %s/%s (%d bytes)", bucket, key, len(payload))
+
+ // Exists
+ ok, err := store.Exists(ctx, bucket, key)
+ if err != nil {
+ t.Fatalf("Exists: %v", err)
+ }
+ if !ok {
+ t.Fatalf("Exists: want true immediately after Put, got false")
+ }
+
+ // Get
+ r, err := store.Get(ctx, bucket, key)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ got, err := io.ReadAll(r)
+ r.Close()
+ if err != nil {
+ t.Fatalf("read: %v", err)
+ }
+ if !bytes.Equal(got, payload) {
+ t.Fatalf("Get bytes mismatch: want %q, got %q", payload, got)
+ }
+
+ // Exists on missing key
+ ok, err = store.Exists(ctx, bucket, key+".does-not-exist")
+ if err != nil {
+ t.Fatalf("Exists(missing): %v", err)
+ }
+ if ok {
+ t.Errorf("Exists(missing): want false, got true")
+ }
+
+ // Get on missing key returns ErrNotFound
+ _, err = store.Get(ctx, bucket, key+".does-not-exist")
+ if !errors.Is(err, blobstore.ErrNotFound) {
+ t.Errorf("Get(missing): want ErrNotFound, got %v", err)
+ }
+
+ t.Logf("smoke: backend=%s endpoint=%s bucket=%s key=%s all ops OK", store.Name(), endpoint, bucket, key)
+}
diff --git a/internal/blobstore/store.go b/internal/blobstore/store.go
index 891b33da..51968ffa 100644
--- a/internal/blobstore/store.go
+++ b/internal/blobstore/store.go
@@ -34,14 +34,28 @@ type Store interface {
// Returns ErrNotFound if the object isn't present.
Get(ctx context.Context, bucket, key string) (io.ReadCloser, error)
+ // GetRange streams a byte range of the object. Used for parallel
+ // chunked downloads of large objects (e.g. checkpoint archives).
+ // Returns ErrNotFound if the object isn't present.
+ GetRange(ctx context.Context, bucket, key string, offset, length int64) (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
+ // Head returns the content length of the object. Distinct from Exists
+ // in that callers needing size (e.g. for range planning) avoid a second
+ // round trip. Returns ErrNotFound if the object isn't present.
+ Head(ctx context.Context, bucket, key string) (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)
+ // Delete removes the object at bucket/key. Returns nil if the object
+ // didn't exist (idempotent).
+ Delete(ctx context.Context, bucket, key string) error
+
// Name returns a short identifier for logging ("tigris", "r2",
// "azure-blob"). Never empty.
Name() string
diff --git a/internal/config/config.go b/internal/config/config.go
index cedca8c7..276ee68c 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -61,6 +61,26 @@ type Config struct {
S3SecretAccessKey string
S3ForcePathStyle bool // true for R2/MinIO
+ // Fallback backend for the checkpoint store. When set, primary reads that
+ // fail (or, in migration mode, return NotFound) cascade here. Writes go
+ // only to primary. Intended for the Tigris-cutover soak window — flip
+ // BlobMigrationMode off and unset once the soak finishes.
+ S3FallbackEndpoint string
+ S3FallbackRegion string
+ S3FallbackAccessKeyID string
+ S3FallbackSecretAccessKey string
+ S3FallbackForcePathStyle bool
+ // S3FallbackBucket lets the fallback backend use a different bucket /
+ // Azure container name than the primary. Example: primary points at
+ // Tigris bucket "opencomputer-prod"; fallback points at Azure container
+ // "checkpoints". When empty, the fallback reuses S3Bucket.
+ S3FallbackBucket string
+
+ // BlobMigrationMode flips FallbackStore semantics so primary NotFound
+ // cascades to fallbacks (lazy-migration behavior). Applies to both the
+ // checkpoint-store fallback and the global blob fallback.
+ BlobMigrationMode bool
+
// Sandbox resource defaults (overridable per-sandbox via API)
DefaultSandboxMemoryMB int // default RAM per sandbox (MB), default 1024
DefaultSandboxCPUs int // default vCPUs per sandbox, default 1
@@ -222,6 +242,15 @@ func Load() (*Config, error) {
S3SecretAccessKey: os.Getenv("OPENSANDBOX_S3_SECRET_ACCESS_KEY"),
S3ForcePathStyle: os.Getenv("OPENSANDBOX_S3_FORCE_PATH_STYLE") == "true",
+ S3FallbackEndpoint: os.Getenv("OPENSANDBOX_S3_FALLBACK_ENDPOINT"),
+ S3FallbackRegion: os.Getenv("OPENSANDBOX_S3_FALLBACK_REGION"),
+ S3FallbackAccessKeyID: os.Getenv("OPENSANDBOX_S3_FALLBACK_ACCESS_KEY_ID"),
+ S3FallbackSecretAccessKey: os.Getenv("OPENSANDBOX_S3_FALLBACK_SECRET_ACCESS_KEY"),
+ S3FallbackForcePathStyle: os.Getenv("OPENSANDBOX_S3_FALLBACK_FORCE_PATH_STYLE") == "true",
+ S3FallbackBucket: os.Getenv("OPENSANDBOX_S3_FALLBACK_BUCKET"),
+
+ BlobMigrationMode: os.Getenv("OPENSANDBOX_BLOB_MIGRATION_MODE") == "true",
+
DefaultSandboxMemoryMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB", 256),
DefaultSandboxCPUs: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_CPUS", 1),
DefaultSandboxDiskMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB", 0),
diff --git a/internal/qemu/checkpoint_rebase_test.go b/internal/qemu/checkpoint_rebase_test.go
index ff0212d8..b62ae52b 100644
--- a/internal/qemu/checkpoint_rebase_test.go
+++ b/internal/qemu/checkpoint_rebase_test.go
@@ -4,7 +4,6 @@ import (
"bytes"
"context"
"encoding/json"
- "fmt"
"io"
"os"
"path/filepath"
@@ -13,11 +12,12 @@ import (
"testing"
"time"
+ "github.com/opensandbox/opensandbox/internal/blobstore"
"github.com/opensandbox/opensandbox/internal/storage"
)
// ---------------------------------------------------------------------------
-// Mock blob client — in-memory store for testing without real S3/Azure
+// Mock Store — in-memory blobstore.Store for testing without real S3/Azure.
// ---------------------------------------------------------------------------
type mockBlobClient struct {
@@ -30,7 +30,9 @@ func newMockBlobClient() *mockBlobClient {
return &mockBlobClient{objects: make(map[string][]byte)}
}
-func (m *mockBlobClient) Upload(_ context.Context, bucket, key string, body io.ReadSeeker, _ int64) error {
+func (m *mockBlobClient) Name() string { return "mock" }
+
+func (m *mockBlobClient) Put(_ context.Context, bucket, key string, body io.Reader, _ int64) error {
data, err := io.ReadAll(body)
if err != nil {
return err
@@ -41,22 +43,22 @@ func (m *mockBlobClient) Upload(_ context.Context, bucket, key string, body io.R
return nil
}
-func (m *mockBlobClient) Download(_ context.Context, bucket, key string) (io.ReadCloser, error) {
+func (m *mockBlobClient) Get(_ context.Context, bucket, key string) (io.ReadCloser, error) {
m.mu.Lock()
data, ok := m.objects[bucket+"/"+key]
m.mu.Unlock()
if !ok {
- return nil, fmt.Errorf("not found: %s/%s", bucket, key)
+ return nil, blobstore.ErrNotFound
}
return io.NopCloser(bytes.NewReader(data)), nil
}
-func (m *mockBlobClient) DownloadRange(_ context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error) {
+func (m *mockBlobClient) GetRange(_ context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error) {
m.mu.Lock()
data, ok := m.objects[bucket+"/"+key]
m.mu.Unlock()
if !ok {
- return nil, fmt.Errorf("not found: %s/%s", bucket, key)
+ return nil, blobstore.ErrNotFound
}
end := offset + length
if end > int64(len(data)) {
@@ -71,11 +73,18 @@ func (m *mockBlobClient) Head(_ context.Context, bucket, key string) (int64, err
data, ok := m.objects[bucket+"/"+key]
m.mu.Unlock()
if !ok {
- return 0, fmt.Errorf("not found: %s/%s", bucket, key)
+ return 0, blobstore.ErrNotFound
}
return int64(len(data)), nil
}
+func (m *mockBlobClient) Exists(_ context.Context, bucket, key string) (bool, error) {
+ m.mu.Lock()
+ _, ok := m.objects[bucket+"/"+key]
+ m.mu.Unlock()
+ return ok, nil
+}
+
func (m *mockBlobClient) Delete(_ context.Context, bucket, key string) error {
m.mu.Lock()
delete(m.objects, bucket+"/"+key)
@@ -83,8 +92,6 @@ func (m *mockBlobClient) Delete(_ context.Context, bucket, key string) error {
return nil
}
-func (m *mockBlobClient) BackendName() string { return "mock" }
-
func (m *mockBlobClient) put(bucket, key string, data []byte) {
m.mu.Lock()
m.objects[bucket+"/"+key] = data
@@ -111,7 +118,7 @@ func testManager(t *testing.T, goldenVersion string) (mgr *Manager, store *stora
}
mock = newMockBlobClient()
- store = storage.NewCheckpointStoreFromClient(mock, "checkpoints")
+ store = storage.NewCheckpointStoreFromStore(mock, "checkpoints")
mgr = &Manager{
cfg: Config{
diff --git a/internal/storage/blob.go b/internal/storage/blob.go
deleted file mode 100644
index 8a81ca86..00000000
--- a/internal/storage/blob.go
+++ /dev/null
@@ -1,71 +0,0 @@
-// Package storage provides blob storage backends for checkpoint archives.
-//
-// BlobClient is the abstraction — implementations exist for Azure Blob Storage
-// (default) and AWS S3. The CheckpointStore uses a BlobClient for all remote
-// operations (upload, download, head, delete).
-//
-// Detection is automatic: if the endpoint contains ".blob.core.windows.net",
-// the Azure client is used. Otherwise, the AWS S3 client is used.
-package storage
-
-import (
- "context"
- "errors"
- "fmt"
- "io"
- "strings"
-)
-
-// ErrNotFound is returned by Head / Download when the object does not exist.
-// Callers should use errors.Is(err, ErrNotFound) — other errors (auth, network,
-// etc.) must not be treated as "not found" to avoid triggering spurious
-// uploads/retries on real outages.
-var ErrNotFound = errors.New("blob: object not found")
-
-// BlobClient abstracts remote object storage operations.
-// Implementations: azureBlobClient (Azure Blob Storage), s3BlobClient (AWS S3).
-type BlobClient interface {
- // Upload writes data from reader to the given key. Returns bytes written.
- Upload(ctx context.Context, bucket, key string, body io.ReadSeeker, contentLength int64) error
- // Download returns a reader for the object at the given key.
- Download(ctx context.Context, bucket, key string) (io.ReadCloser, error)
- // DownloadRange returns a reader for a byte range of the object.
- DownloadRange(ctx context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error)
- // Head returns the content length of the object, or error if not found.
- Head(ctx context.Context, bucket, key string) (int64, error)
- // Delete removes the object at the given key.
- Delete(ctx context.Context, bucket, key string) error
- // BackendName returns a human-readable name for the storage backend (e.g. "S3", "Azure Blob").
- BackendName() string
-}
-
-// NewBlobClient creates the appropriate blob client based on the endpoint.
-// Azure Blob Storage endpoints (*.blob.core.windows.net) use the native Azure SDK.
-// All other endpoints use the AWS S3 SDK.
-func NewBlobClient(cfg S3Config) (BlobClient, error) {
- if strings.Contains(cfg.Endpoint, ".blob.core.windows.net") {
- return newAzureBlobClient(cfg)
- }
- return newS3BlobClient(cfg)
-}
-
-// newAzureBlobClient creates an Azure Blob Storage client.
-func newAzureBlobClient(cfg S3Config) (BlobClient, error) {
- // Azure Blob Storage uses the storage account name as the access key ID
- // and the account key as the secret. The endpoint is the full URL.
- connStr := fmt.Sprintf(
- "DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=core.windows.net",
- cfg.AccessKeyID, cfg.SecretAccessKey,
- )
- return &azureBlobClient{connStr: connStr}, nil
-}
-
-// newS3BlobClient creates an AWS S3-compatible client.
-func newS3BlobClient(cfg S3Config) (BlobClient, error) {
- // Reuse the existing S3 client setup
- client, err := buildS3Client(cfg)
- if err != nil {
- return nil, err
- }
- return &s3BlobClient{client: client}, nil
-}
diff --git a/internal/storage/blob_azure.go b/internal/storage/blob_azure.go
deleted file mode 100644
index 84908d0b..00000000
--- a/internal/storage/blob_azure.go
+++ /dev/null
@@ -1,126 +0,0 @@
-package storage
-
-import (
- "context"
- "fmt"
- "io"
- "strings"
-
- "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
- "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"
-)
-
-// azureBlobClient implements BlobClient using the native Azure Blob SDK.
-type azureBlobClient struct {
- client *azblob.Client
- connStr string
-}
-
-// uploadStreamOpts is shared by every Upload call. The Azure SDK's nil-default
-// is BlockSize=1MB / Concurrency=1, i.e. a serial chain of small PutBlock
-// calls that's HTTP-overhead bound at 30–60 MB/s per blob — that turned a
-// 10 GB checkpoint into a 5+ minute upload. The values below are sized for a
-// 64-vCPU worker (D-series, ~30 Gbps NIC, Premium SSD ~700 MB/s read):
-//
-// - BlockSize 8 MB: large enough that PutBlock HTTP overhead is amortized
-// (~10x fewer round-trips than the SDK default), small enough that under
-// concurrent uploads the per-blob in-flight memory stays bounded.
-// - Concurrency 8: enough parallelism to keep the worker NIC fed even when
-// HTTP latency dominates a single block. Per-upload in-flight buffer is
-// 8 × 8 MB = 64 MB, negligible against worker RAM.
-//
-// Practical ceiling per blob with these settings is ~600–1000 MB/s, which is
-// already above the disk-read rate at which we can feed bytes into the
-// uploader from the on-disk archive — meaning disk read is now the bottleneck,
-// not HTTP. Bumping further would just waste memory.
-//
-// Concurrency on the worker level: 5 simultaneous CreateCheckpoint uploads ≈
-// 320 MB total in-flight buffer + ~40 connections to blob — comfortably under
-// the worker's NIC and Azure's per-account ingress limits.
-var uploadStreamOpts = &azblob.UploadStreamOptions{
- BlockSize: 8 * 1024 * 1024,
- Concurrency: 8,
-}
-
-func (c *azureBlobClient) BackendName() string { return "Azure Blob" }
-
-// normalizeKey strips the container name prefix from the key if present.
-// S3 keys often include the bucket name (e.g., "checkpoints/sb-xxx/...") because
-// S3 treats bucket and key as separate. Azure Blob uses container + blob name,
-// so we strip the redundant prefix to avoid "container/container/..." paths.
-func normalizeKey(container, key string) string {
- prefix := container + "/"
- if strings.HasPrefix(key, prefix) {
- return strings.TrimPrefix(key, prefix)
- }
- return key
-}
-
-func (c *azureBlobClient) ensureClient() error {
- if c.client != nil {
- return nil
- }
- client, err := azblob.NewClientFromConnectionString(c.connStr, nil)
- if err != nil {
- return fmt.Errorf("azure blob: %w", err)
- }
- c.client = client
- return nil
-}
-
-func (c *azureBlobClient) Upload(ctx context.Context, container, key string, body io.ReadSeeker, contentLength int64) error {
- if err := c.ensureClient(); err != nil {
- return err
- }
- _, err := c.client.UploadStream(ctx, container, normalizeKey(container, key), body, uploadStreamOpts)
- return err
-}
-
-func (c *azureBlobClient) Download(ctx context.Context, container, key string) (io.ReadCloser, error) {
- if err := c.ensureClient(); err != nil {
- return nil, err
- }
- resp, err := c.client.DownloadStream(ctx, container, normalizeKey(container, key), nil)
- if err != nil {
- return nil, err
- }
- return resp.Body, nil
-}
-
-func (c *azureBlobClient) DownloadRange(ctx context.Context, container, key string, offset, length int64) (io.ReadCloser, error) {
- if err := c.ensureClient(); err != nil {
- return nil, err
- }
- resp, err := c.client.DownloadStream(ctx, container, normalizeKey(container, key), &azblob.DownloadStreamOptions{
- Range: azblob.HTTPRange{Offset: offset, Count: length},
- })
- if err != nil {
- return nil, err
- }
- return resp.Body, nil
-}
-
-func (c *azureBlobClient) Head(ctx context.Context, container, key string) (int64, error) {
- if err := c.ensureClient(); err != nil {
- return 0, err
- }
- resp, err := c.client.ServiceClient().NewContainerClient(container).NewBlobClient(normalizeKey(container, key)).GetProperties(ctx, nil)
- if err != nil {
- if bloberror.HasCode(err, bloberror.BlobNotFound) {
- return 0, ErrNotFound
- }
- return 0, err
- }
- if resp.ContentLength == nil {
- return 0, nil
- }
- return *resp.ContentLength, nil
-}
-
-func (c *azureBlobClient) Delete(ctx context.Context, container, key string) error {
- if err := c.ensureClient(); err != nil {
- return err
- }
- _, err := c.client.DeleteBlob(ctx, container, normalizeKey(container, key), nil)
- return err
-}
diff --git a/internal/storage/blob_s3.go b/internal/storage/blob_s3.go
deleted file mode 100644
index aef46b2e..00000000
--- a/internal/storage/blob_s3.go
+++ /dev/null
@@ -1,121 +0,0 @@
-package storage
-
-import (
- "context"
- "errors"
- "fmt"
- "io"
- "strings"
-
- "github.com/aws/aws-sdk-go-v2/aws"
- awsconfig "github.com/aws/aws-sdk-go-v2/config"
- "github.com/aws/aws-sdk-go-v2/credentials"
- "github.com/aws/aws-sdk-go-v2/service/s3"
- s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
-)
-
-// s3BlobClient implements BlobClient using the AWS S3 SDK.
-type s3BlobClient struct {
- client *s3.Client
-}
-
-func (c *s3BlobClient) BackendName() string { return "S3" }
-
-// buildS3Client creates an S3 client from config.
-func buildS3Client(cfg S3Config) (*s3.Client, error) {
- forcePathStyle := cfg.ForcePathStyle
- if !forcePathStyle && strings.Contains(cfg.Endpoint, ".blob.core.windows.net") {
- forcePathStyle = true
- }
-
- if cfg.AccessKeyID != "" {
- opts := []func(*s3.Options){
- func(o *s3.Options) {
- o.Region = cfg.Region
- o.Credentials = credentials.NewStaticCredentialsProvider(
- cfg.AccessKeyID, cfg.SecretAccessKey, "",
- )
- if forcePathStyle {
- o.UsePathStyle = true
- }
- if cfg.Endpoint != "" {
- o.BaseEndpoint = aws.String(cfg.Endpoint)
- }
- },
- }
- return s3.New(s3.Options{}, opts...), nil
- }
-
- awsCfg, err := awsconfig.LoadDefaultConfig(context.Background(),
- awsconfig.WithRegion(cfg.Region),
- )
- if err != nil {
- return nil, fmt.Errorf("failed to load AWS config: %w", err)
- }
- var s3Opts []func(*s3.Options)
- if forcePathStyle {
- s3Opts = append(s3Opts, func(o *s3.Options) { o.UsePathStyle = true })
- }
- if cfg.Endpoint != "" {
- s3Opts = append(s3Opts, func(o *s3.Options) { o.BaseEndpoint = aws.String(cfg.Endpoint) })
- }
- return s3.NewFromConfig(awsCfg, s3Opts...), nil
-}
-
-func (c *s3BlobClient) Upload(ctx context.Context, bucket, key string, body io.ReadSeeker, contentLength int64) error {
- _, err := c.client.PutObject(ctx, &s3.PutObjectInput{
- Bucket: aws.String(bucket),
- Key: aws.String(key),
- Body: body,
- ContentLength: aws.Int64(contentLength),
- })
- return err
-}
-
-func (c *s3BlobClient) Download(ctx context.Context, bucket, key string) (io.ReadCloser, error) {
- resp, err := c.client.GetObject(ctx, &s3.GetObjectInput{
- Bucket: aws.String(bucket),
- Key: aws.String(key),
- })
- if err != nil {
- return nil, err
- }
- return resp.Body, nil
-}
-
-func (c *s3BlobClient) DownloadRange(ctx context.Context, bucket, key string, offset, length int64) (io.ReadCloser, error) {
- rangeStr := fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)
- resp, err := c.client.GetObject(ctx, &s3.GetObjectInput{
- Bucket: aws.String(bucket),
- Key: aws.String(key),
- Range: aws.String(rangeStr),
- })
- if err != nil {
- return nil, err
- }
- return resp.Body, nil
-}
-
-func (c *s3BlobClient) Head(ctx context.Context, bucket, key string) (int64, error) {
- resp, err := c.client.HeadObject(ctx, &s3.HeadObjectInput{
- Bucket: aws.String(bucket),
- Key: aws.String(key),
- })
- if err != nil {
- var nsk *s3types.NoSuchKey
- var nf *s3types.NotFound
- if errors.As(err, &nsk) || errors.As(err, &nf) {
- return 0, ErrNotFound
- }
- return 0, err
- }
- return aws.ToInt64(resp.ContentLength), nil
-}
-
-func (c *s3BlobClient) Delete(ctx context.Context, bucket, key string) error {
- _, err := c.client.DeleteObject(ctx, &s3.DeleteObjectInput{
- Bucket: aws.String(bucket),
- Key: aws.String(key),
- })
- return err
-}
diff --git a/internal/storage/s3.go b/internal/storage/s3.go
index cc8905b0..628ba214 100644
--- a/internal/storage/s3.go
+++ b/internal/storage/s3.go
@@ -10,13 +10,21 @@ import (
"os"
"path/filepath"
"sort"
+ "strings"
"sync"
"time"
+ "github.com/opensandbox/opensandbox/internal/blobstore"
"golang.org/x/sys/unix"
)
-// S3Config holds the configuration for the S3 storage backend.
+// ErrNotFound is re-exported from blobstore so existing callers
+// (errors.Is(err, storage.ErrNotFound)) keep working.
+var ErrNotFound = blobstore.ErrNotFound
+
+// S3Config holds the configuration for the checkpoint store's backend.
+// The "S3" in the name is historical — the same config drives Azure Blob via
+// blobstore.NewAzure when the endpoint resolves there.
type S3Config struct {
Endpoint string
Bucket string
@@ -26,42 +34,67 @@ type S3Config struct {
ForcePathStyle bool
}
-// CheckpointStore manages checkpoint archives in S3-compatible object storage,
-// with an optional local NVMe cache for fast same-machine wake.
+// CheckpointStore manages checkpoint archives in object storage, with an
+// optional local NVMe cache for fast same-machine wake.
//
-// S3 is always the source of truth. Local NVMe is a hot cache.
-// On hibernate: CRIU checkpoint + workspace both uploaded to S3, kept locally.
-// On wake: check NVMe first, fall back to S3 download.
+// Object storage is always the source of truth. Local NVMe is a hot cache.
+// On hibernate: CRIU checkpoint + workspace both uploaded, kept locally.
+// On wake: check NVMe first, fall back to object-store download.
// Eviction: LRU based on real filesystem pressure (keep 20% free for active sandboxes).
type CheckpointStore struct {
- blob BlobClient
+ blob blobstore.Store
bucket string
cacheDir string // local NVMe cache for CRIU checkpoints (empty = disabled)
cacheMu sync.Mutex
}
-// NewCheckpointStoreFromClient creates a CheckpointStore using an existing
-// BlobClient. Useful for testing with a mock backend.
-func NewCheckpointStoreFromClient(blob BlobClient, bucket string) *CheckpointStore {
- return &CheckpointStore{blob: blob, bucket: bucket}
+// NewCheckpointStoreFromStore creates a CheckpointStore wrapping a
+// pre-constructed blobstore.Store. Use this when the worker has already
+// built a Store (e.g. with FallbackStore wrapping primary+fallback) and
+// wants the same instance shared with the checkpoint code path.
+func NewCheckpointStoreFromStore(store blobstore.Store, bucket string) *CheckpointStore {
+ return &CheckpointStore{blob: store, bucket: bucket}
}
-// NewCheckpointStore creates a new checkpoint store.
-// Automatically selects Azure Blob or AWS S3 based on the endpoint URL.
+// NewCheckpointStore creates a new checkpoint store from an S3Config,
+// auto-detecting Azure Blob or S3-compatible based on the endpoint URL.
+//
+// Prefer NewCheckpointStoreFromStore when the caller already has a configured
+// blobstore.Store (e.g. with fallback wrapping). This constructor exists for
+// simple single-backend setups.
func NewCheckpointStore(cfg S3Config) (*CheckpointStore, error) {
- blob, err := NewBlobClient(cfg)
+ store, err := buildStoreFromS3Config(cfg)
if err != nil {
- return nil, fmt.Errorf("failed to create blob client: %w", err)
+ return nil, err
}
-
- log.Printf("storage: using %s backend (endpoint=%s, bucket=%s)", blob.BackendName(), cfg.Endpoint, cfg.Bucket)
-
+ log.Printf("storage: using %s backend (endpoint=%s, bucket=%s)", store.Name(), cfg.Endpoint, cfg.Bucket)
return &CheckpointStore{
- blob: blob,
+ blob: store,
bucket: cfg.Bucket,
}, nil
}
+// buildStoreFromS3Config picks Azure or S3-compat based on endpoint shape,
+// preserving the previous auto-detection contract.
+func buildStoreFromS3Config(cfg S3Config) (blobstore.Store, error) {
+ if strings.Contains(cfg.Endpoint, ".blob.core.windows.net") {
+ // Azure: storage account name lives in AccessKeyID, account key in SecretAccessKey.
+ return blobstore.NewAzure(blobstore.AzureConfig{
+ Name: "azure-blob",
+ AccountName: cfg.AccessKeyID,
+ AccountKey: cfg.SecretAccessKey,
+ })
+ }
+ return blobstore.NewS3(blobstore.S3Config{
+ Name: "s3",
+ Endpoint: cfg.Endpoint,
+ Region: cfg.Region,
+ AccessKeyID: cfg.AccessKeyID,
+ SecretAccessKey: cfg.SecretAccessKey,
+ UsePathStyle: cfg.ForcePathStyle || strings.Contains(cfg.Endpoint, ".blob.core.windows.net"),
+ })
+}
+
// SetCacheDir enables local NVMe checkpoint caching at the given directory.
func (s *CheckpointStore) SetCacheDir(dir string) error {
if err := os.MkdirAll(dir, 0755); err != nil {
@@ -128,7 +161,7 @@ func (s *CheckpointStore) Upload(ctx context.Context, key, localPath string) (in
return 0, fmt.Errorf("failed to stat checkpoint file: %w", err)
}
- if err := s.blob.Upload(ctx, s.bucket, key, f, stat.Size()); err != nil {
+ if err := s.blob.Put(ctx, s.bucket, key, f, stat.Size()); err != nil {
return 0, fmt.Errorf("failed to upload checkpoint: %w", err)
}
@@ -275,7 +308,7 @@ func (s *CheckpointStore) downloadAndCache(ctx context.Context, key string) (io.
}
chunkLen := end - start + 1
- body, err := s.blob.DownloadRange(ctx, s.bucket, key, start, chunkLen)
+ body, err := s.blob.GetRange(ctx, s.bucket, key, start, chunkLen)
if err != nil {
errs[idx] = fmt.Errorf("chunk %d: %w", idx, err)
return
@@ -324,9 +357,10 @@ func (s *CheckpointStore) downloadAndCache(ctx context.Context, key string) (io.
return f, nil
}
-// downloadFromS3 streams directly from S3 (no caching).
+// downloadFromS3 streams directly from S3 (no caching). Despite the name,
+// works against any blobstore.Store backend.
func (s *CheckpointStore) downloadFromS3(ctx context.Context, key string) (io.ReadCloser, error) {
- body, err := s.blob.Download(ctx, s.bucket, key)
+ body, err := s.blob.Get(ctx, s.bucket, key)
if err != nil {
return nil, fmt.Errorf("failed to download checkpoint: %w", err)
}
diff --git a/scripts/rclone-azure-to-tigris.sh b/scripts/rclone-azure-to-tigris.sh
new file mode 100755
index 00000000..7f97caab
--- /dev/null
+++ b/scripts/rclone-azure-to-tigris.sh
@@ -0,0 +1,74 @@
+#!/usr/bin/env bash
+# rclone-azure-to-tigris.sh
+#
+# One-shot copy of the prod checkpoints container from Azure Blob to Tigris.
+# Run with --dry-run first to confirm the planned transfer.
+#
+# Required env vars:
+# AZURE_STORAGE_ACCOUNT e.g. occkpt3ccf3c31
+# AZURE_STORAGE_KEY az storage account keys list -g opencomputer-prod \
+# -n occkpt3ccf3c31 --query "[0].value" -o tsv
+# TIGRIS_ACCESS_KEY_ID
+# TIGRIS_SECRET_ACCESS_KEY
+#
+# Optional:
+# SRC_CONTAINER default: checkpoints
+# TIGRIS_BUCKET default: opencomputer-prod
+# TIGRIS_ENDPOINT default: https://t3.storage.dev
+#
+# Use rclone copy (not sync) — never deletes from destination. Safe to re-run;
+# subsequent runs only transfer keys that changed (delta sync).
+#
+# Best run from a VM in eastus2 (same region as source storage account).
+
+set -euo pipefail
+
+: "${AZURE_STORAGE_ACCOUNT:?required}"
+: "${AZURE_STORAGE_KEY:?required}"
+: "${TIGRIS_ACCESS_KEY_ID:?required}"
+: "${TIGRIS_SECRET_ACCESS_KEY:?required}"
+
+SRC_CONTAINER="${SRC_CONTAINER:-checkpoints}"
+TIGRIS_BUCKET="${TIGRIS_BUCKET:-opencomputer-prod}"
+TIGRIS_ENDPOINT="${TIGRIS_ENDPOINT:-https://t3.storage.dev}"
+
+export RCLONE_CONFIG_AZ_TYPE=azureblob
+export RCLONE_CONFIG_AZ_ACCOUNT="$AZURE_STORAGE_ACCOUNT"
+export RCLONE_CONFIG_AZ_KEY="$AZURE_STORAGE_KEY"
+
+export RCLONE_CONFIG_TIGRIS_TYPE=s3
+export RCLONE_CONFIG_TIGRIS_PROVIDER=Other
+export RCLONE_CONFIG_TIGRIS_ENDPOINT="$TIGRIS_ENDPOINT"
+export RCLONE_CONFIG_TIGRIS_REGION=auto
+export RCLONE_CONFIG_TIGRIS_ACCESS_KEY_ID="$TIGRIS_ACCESS_KEY_ID"
+export RCLONE_CONFIG_TIGRIS_SECRET_ACCESS_KEY="$TIGRIS_SECRET_ACCESS_KEY"
+export RCLONE_CONFIG_TIGRIS_FORCE_PATH_STYLE=true
+
+LOGFILE="${LOGFILE:-rclone-az-to-tigris-$(date +%Y%m%d-%H%M%S).log}"
+
+echo "==> $(date) rclone copy az:$SRC_CONTAINER -> tigris:$TIGRIS_BUCKET"
+echo " log: $LOGFILE"
+echo " args: $*"
+
+# --transfers 16: parallel file transfers
+# --checkers 32: parallel existence checks
+# --multi-thread-streams 8 with cutoff 256M: parallelize large goldens (4GB)
+# --s3-chunk-size 64M: fewer S3 ops per big file
+# --progress + --stats: live visibility
+rclone copy \
+ "az:$SRC_CONTAINER" \
+ "tigris:$TIGRIS_BUCKET" \
+ --transfers 16 \
+ --checkers 32 \
+ --multi-thread-streams 8 \
+ --multi-thread-cutoff 256M \
+ --s3-chunk-size 64M \
+ --s3-upload-concurrency 4 \
+ --progress \
+ --stats 30s \
+ --stats-one-line \
+ --log-level INFO \
+ --log-file "$LOGFILE" \
+ "$@"
+
+echo "==> $(date) done"