diff --git a/packages/orchestrator/cmd/template-gc/main.go b/packages/orchestrator/cmd/template-gc/main.go new file mode 100644 index 00000000000..71300428a53 --- /dev/null +++ b/packages/orchestrator/cmd/template-gc/main.go @@ -0,0 +1,252 @@ +// Command template-gc garbage-collects template-storage build artifacts. +// +// It has two phases, both of which re-derive liveness from ground truth at run +// time (a stale reverse-reference index is more dangerous than reading the +// headers — a dropped edge is permanent corruption): +// +// - MARK (default): scan the bucket, expand each live root's header-mapping +// ancestor closure, and write manifests of what to keep and what is an +// unreferenced, old-enough deletion candidate. Deletes nothing. +// - SWEEP (-sweep): re-run the mark fresh, intersect it with an +// operator-approved candidates file, and delete only builds that are STILL +// unreferenced and old enough. This is operator-gated: it is a DRY RUN +// unless -confirm-delete is passed, so an approved manifest that went stale +// cannot delete a build that became referenced since it was written. +// +// Either phase can write a Prometheus textfile (-metrics-file) so the fleet can +// trend orphaned-storage bytes instead of eyeballing a one-off JSON manifest. +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "os" + "time" + + "github.com/google/uuid" + + "github.com/e2b-dev/infra/packages/orchestrator/cmd/internal/cmdutil" + "github.com/e2b-dev/infra/packages/orchestrator/internal/templategc" + "github.com/e2b-dev/infra/packages/shared/pkg/storage" +) + +func main() { + storagePath := flag.String("storage", "", "template storage: local path or gs://bucket") + rootsFile := flag.String("roots", "", "path to a JSON file: array of live-root build IDs (exported separately)") + graceDays := flag.Int("grace-days", 60, "a build prefix is a candidate only if every object under it is older than this many days") + outDir := flag.String("out", ".", "directory to write manifests") + metricsFile := flag.String("metrics-file", "", "optional path to write Prometheus textfile gauges (node_exporter textfile collector)") + + sweep := flag.Bool("sweep", false, "sweep mode: delete the intersection of -approved and a fresh mark (DRY RUN unless -confirm-delete)") + approvedFile := flag.String("approved", "", "sweep mode: path to the operator-approved candidates.json (as written by a prior mark run)") + confirmDelete := flag.Bool("confirm-delete", false, "sweep mode: actually delete. Without this, sweep is a dry run and deletes nothing") + flag.Parse() + + if *storagePath == "" || *rootsFile == "" { + fmt.Fprintln(os.Stderr, "both -storage and -roots are required") + os.Exit(2) + } + if *sweep && *approvedFile == "" { + fmt.Fprintln(os.Stderr, "-sweep requires -approved ") + os.Exit(2) + } + + ctx := context.Background() + if err := run(ctx, runOpts{ + storagePath: *storagePath, + rootsFile: *rootsFile, + graceDays: *graceDays, + outDir: *outDir, + metricsFile: *metricsFile, + sweep: *sweep, + approvedFile: *approvedFile, + confirmDelete: *confirmDelete, + }); err != nil { + fmt.Fprintf(os.Stderr, "template-gc failed: %v\n", err) + os.Exit(1) + } +} + +type runOpts struct { + storagePath string + rootsFile string + graceDays int + outDir string + metricsFile string + sweep bool + approvedFile string + confirmDelete bool +} + +func run(ctx context.Context, o runOpts) error { + roots, err := readRoots(o.rootsFile) + if err != nil { + return fmt.Errorf("read roots: %w", err) + } + + spec, err := cmdutil.TemplateSpec(o.storagePath) + if err != nil { + return fmt.Errorf("resolve storage spec: %w", err) + } + + provider, err := storage.NewProvider(ctx, spec) + if err != nil { + return fmt.Errorf("storage provider: %w", err) + } + + objects, err := storage.ListObjects(ctx, provider, "") + if err != nil { + return fmt.Errorf("list bucket (fail closed; cannot treat an unlistable bucket as empty): %w", err) + } + + now := time.Now() + manifest, err := templategc.Mark(ctx, templategc.StorageAncestorReader{Storage: provider}, templategc.MarkInput{ + LiveRoots: roots, + Objects: objects, + Now: now, + Grace: time.Duration(o.graceDays) * 24 * time.Hour, + }) + if err != nil { + return err + } + + for name, v := range map[string]any{ + "keep.json": manifest.Keep, + "candidates.json": manifest.Candidates, + "too-new.json": manifest.TooNew, + "unknown-keys.json": manifest.UnknownKeys, + } { + if err := writeJSON(o.outDir, name, v); err != nil { + return err + } + } + + var candBytes int64 + for _, c := range manifest.Candidates { + candBytes += c.TotalBytes + } + + fmt.Printf("mark complete (fresh, nothing deleted in this phase)\n") + fmt.Printf(" live roots: %d\n", len(roots)) + fmt.Printf(" keep builds: %d\n", len(manifest.Keep)) + fmt.Printf(" candidates: %d (%d bytes)\n", len(manifest.Candidates), candBytes) + fmt.Printf(" held (too new): %d\n", len(manifest.TooNew)) + fmt.Printf(" unknown keys: %d\n", len(manifest.UnknownKeys)) + fmt.Printf(" manifests in: %s\n", o.outDir) + + var sweepRes *templategc.SweepResult + if o.sweep { + sweepRes, err = runSweep(ctx, provider, o, manifest) + if err != nil { + return err + } + } + + if o.metricsFile != "" { + if err := writeMetrics(o.metricsFile, manifest, sweepRes, now); err != nil { + return fmt.Errorf("write metrics file: %w", err) + } + } + + return nil +} + +func runSweep(ctx context.Context, provider storage.StorageProvider, o runOpts, fresh *templategc.Manifest) (*templategc.SweepResult, error) { + approved, err := readApproved(o.approvedFile) + if err != nil { + return nil, fmt.Errorf("read approved candidates: %w", err) + } + + res, err := templategc.Sweep(ctx, templategc.StoragePrefixDeleter{Storage: provider}, approved, fresh, o.confirmDelete) + if err != nil { + return nil, err + } + + mode := "DRY RUN (pass -confirm-delete to actually delete)" + if res.Confirmed { + mode = "CONFIRMED — objects deleted" + } + fmt.Printf("sweep complete [%s]\n", mode) + fmt.Printf(" approved: %d\n", len(approved)) + fmt.Printf(" deleted: %d (%d bytes)\n", len(res.Deleted), res.ReclaimedBytes) + fmt.Printf(" skipped(changed):%d (became referenced/too-new since mark; TOCTOU guard)\n", len(res.SkippedChanged)) + fmt.Printf(" failed: %d\n", len(res.Failed)) + + return res, nil +} + +func writeMetrics(path string, manifest *templategc.Manifest, sweep *templategc.SweepResult, now time.Time) error { + f, err := os.Create(path) + if err != nil { + return err + } + defer f.Close() + + return templategc.WriteOrphanMetrics(f, manifest, sweep, now) +} + +func readRoots(path string) ([]uuid.UUID, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + + var raw []string + if err := json.Unmarshal(data, &raw); err != nil { + return nil, fmt.Errorf("roots file must be a JSON array of build-ID strings: %w", err) + } + + return parseIDs(raw) +} + +// readApproved reads the operator-approved candidates file. It accepts the exact +// candidates.json a prior mark wrote (an array of {build_id,...} objects) so the +// operator reviews and approves the same artifact, not a re-typed list. +func readApproved(path string) ([]uuid.UUID, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + + var prefixes []templategc.BuildPrefix + if err := json.Unmarshal(data, &prefixes); err == nil && len(prefixes) > 0 && prefixes[0].BuildID != uuid.Nil { + ids := make([]uuid.UUID, 0, len(prefixes)) + for _, p := range prefixes { + ids = append(ids, p.BuildID) + } + + return ids, nil + } + + // Fall back to a plain array of build-ID strings. + var raw []string + if err := json.Unmarshal(data, &raw); err != nil { + return nil, fmt.Errorf("approved file must be a candidates.json or a JSON array of build-ID strings: %w", err) + } + + return parseIDs(raw) +} + +func parseIDs(raw []string) ([]uuid.UUID, error) { + ids := make([]uuid.UUID, 0, len(raw)) + for _, s := range raw { + id, err := uuid.Parse(s) + if err != nil { + return nil, fmt.Errorf("invalid build ID %q: %w", s, err) + } + ids = append(ids, id) + } + + return ids, nil +} + +func writeJSON(dir, name string, v any) error { + data, err := json.MarshalIndent(v, "", " ") + if err != nil { + return err + } + + return os.WriteFile(dir+"/"+name, data, 0o644) +} diff --git a/packages/orchestrator/internal/templategc/deleter.go b/packages/orchestrator/internal/templategc/deleter.go new file mode 100644 index 00000000000..dc78b0d0b0a --- /dev/null +++ b/packages/orchestrator/internal/templategc/deleter.go @@ -0,0 +1,24 @@ +package templategc + +import ( + "context" + + "github.com/google/uuid" + + "github.com/e2b-dev/infra/packages/shared/pkg/storage" +) + +// StoragePrefixDeleter is the production PrefixDeleter. It removes every object +// under a build's prefix from template storage via DeleteObjectsWithPrefix. +type StoragePrefixDeleter struct { + Storage storage.StorageProvider +} + +func (d StoragePrefixDeleter) DeletePrefix(ctx context.Context, buildID uuid.UUID) error { + // Pass the bare build ID, matching every other caller of + // DeleteObjectsWithPrefix (delete_template.go, builder.go): the storage + // layer validates object paths and rejects a trailing slash. A UUID prefix + // matches only "{buildID}/..." keys — no sibling build can share the full + // UUID as a string prefix. + return d.Storage.DeleteObjectsWithPrefix(ctx, buildID.String()) +} diff --git a/packages/orchestrator/internal/templategc/mark.go b/packages/orchestrator/internal/templategc/mark.go new file mode 100644 index 00000000000..02d9787a3c2 --- /dev/null +++ b/packages/orchestrator/internal/templategc/mark.go @@ -0,0 +1,148 @@ +// Package templategc implements the mark phase of template-storage garbage +// collection. It is dry-run only: it computes which build prefixes are +// unreferenced and old enough to be deletion candidates, and NEVER deletes +// anything. Physical deletion is a separate, operator-gated step. +package templategc + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + + "github.com/e2b-dev/infra/packages/shared/pkg/storage" +) + +// AncestorReader resolves a build's header-mapping ancestor closure (the build +// itself plus every build its memfile/rootfs headers reference). An error means +// the dependency set is unknown; the marker then fails closed. +type AncestorReader interface { + AncestorBuilds(ctx context.Context, buildID uuid.UUID) ([]uuid.UUID, error) +} + +// Manifest is the result of a mark run. It is advisory: Candidates lists the +// build prefixes that are safe to delete under the inputs given, but nothing is +// deleted here. +type Manifest struct { + // Keep is every build ID still reachable from a live root's header closure. + Keep []uuid.UUID + // Candidates are build prefixes not in Keep and whose every object is older + // than the grace period — safe to delete. + Candidates []BuildPrefix + // TooNew are unreferenced builds held back because at least one object under + // the prefix is newer than the grace cutoff (possibly an in-flight upload). + TooNew []BuildPrefix + // UnknownKeys are object keys that do not sit under a UUID build prefix; + // surfaced for human review, never deleted. + UnknownKeys []string +} + +// BuildPrefix is a build's object-storage prefix and its aggregate stats. +type BuildPrefix struct { + BuildID uuid.UUID + ObjectCount int + TotalBytes int64 + NewestObject time.Time +} + +// MarkInput is everything the pure Mark computation needs. +type MarkInput struct { + // LiveRoots are the build IDs that must be kept: the union of DB active + // templates' builds, in-progress builds, and runtime-sandbox-pinned builds. + // The caller collects these from all sources and fails the whole run if any + // source could not be read. + LiveRoots []uuid.UUID + // Objects is the full, paginated listing of the template bucket. + Objects []storage.ObjectInfo + // Now and Grace define the age cutoff: a build is only a candidate when every + // object under its prefix predates Now.Add(-Grace). + Now time.Time + Grace time.Duration +} + +// Mark computes the deletion manifest. It fails closed: if any live root's +// ancestor closure cannot be resolved, it returns an error and no candidates, so +// an unreadable header can never cause a reachable build to be marked deletable. +func Mark(ctx context.Context, reader AncestorReader, in MarkInput) (*Manifest, error) { + keep := make(map[uuid.UUID]struct{}) + for _, root := range in.LiveRoots { + closure, err := reader.AncestorBuilds(ctx, root) + if err != nil { + return nil, fmt.Errorf("resolve ancestor closure of live root %s: %w", root, err) + } + + for _, b := range closure { + keep[b] = struct{}{} + } + } + + cutoff := in.Now.Add(-in.Grace) + + // Group objects by build prefix (the first path segment, which must be a UUID). + type agg struct { + count int + bytes int64 + newest time.Time + } + byBuild := make(map[uuid.UUID]*agg) + var unknown []string + + for _, obj := range in.Objects { + seg, _, ok := strings.Cut(obj.Path, "/") + if !ok { + unknown = append(unknown, obj.Path) + + continue + } + + id, err := uuid.Parse(seg) + if err != nil { + unknown = append(unknown, obj.Path) + + continue + } + + a := byBuild[id] + if a == nil { + a = &agg{} + byBuild[id] = a + } + a.count++ + a.bytes += obj.Size + if obj.LastModified.After(a.newest) { + a.newest = obj.LastModified + } + } + + m := &Manifest{UnknownKeys: unknown} + for b := range keep { + m.Keep = append(m.Keep, b) + } + + for id, a := range byBuild { + if _, kept := keep[id]; kept { + continue + } + + bp := BuildPrefix{ + BuildID: id, + ObjectCount: a.count, + TotalBytes: a.bytes, + NewestObject: a.newest, + } + + // Protect the whole prefix if any object is newer than the cutoff: a + // fresh object may be an in-flight upload not yet reflected in the roots. + if a.newest.After(cutoff) { + m.TooNew = append(m.TooNew, bp) + + continue + } + + m.Candidates = append(m.Candidates, bp) + } + + return m, nil +} diff --git a/packages/orchestrator/internal/templategc/mark_test.go b/packages/orchestrator/internal/templategc/mark_test.go new file mode 100644 index 00000000000..95d43d1df92 --- /dev/null +++ b/packages/orchestrator/internal/templategc/mark_test.go @@ -0,0 +1,169 @@ +package templategc + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/e2b-dev/infra/packages/shared/pkg/storage" +) + +type stubReader struct { + closures map[uuid.UUID][]uuid.UUID + err error +} + +func (s stubReader) AncestorBuilds(_ context.Context, b uuid.UUID) ([]uuid.UUID, error) { + if s.err != nil { + return nil, s.err + } + + out := []uuid.UUID{b} + + return append(out, s.closures[b]...), nil +} + +func obj(buildID uuid.UUID, name string, size int64, mod time.Time) storage.ObjectInfo { + return storage.ObjectInfo{Path: buildID.String() + "/" + name, Size: size, LastModified: mod} +} + +// A build referenced only through a live root's header closure (never its own +// root) must be kept, not marked a candidate. +func TestMark_KeepsAncestorOfLiveRoot(t *testing.T) { + t.Parallel() + + now := time.Now() + old := now.Add(-100 * 24 * time.Hour) + + liveRoot := uuid.New() + ancestor := uuid.New() // shared base layer, old, not a root itself + + reader := stubReader{closures: map[uuid.UUID][]uuid.UUID{liveRoot: {ancestor}}} + + in := MarkInput{ + LiveRoots: []uuid.UUID{liveRoot}, + Objects: []storage.ObjectInfo{ + obj(liveRoot, "rootfs.ext4.header", 10, old), + obj(ancestor, "rootfs.ext4.header", 10, old), + obj(ancestor, "memfile", 1000, old), + }, + Now: now, + Grace: 60 * 24 * time.Hour, + } + + m, err := Mark(context.Background(), reader, in) + require.NoError(t, err) + + assert.Empty(t, m.Candidates, "an old ancestor referenced by a live root must not be a candidate") + assert.Contains(t, m.Keep, ancestor) + assert.Contains(t, m.Keep, liveRoot) +} + +// An unreferenced, old build is a candidate. +func TestMark_OrphanOldBuildIsCandidate(t *testing.T) { + t.Parallel() + + now := time.Now() + old := now.Add(-100 * 24 * time.Hour) + + liveRoot := uuid.New() + orphan := uuid.New() + + reader := stubReader{closures: map[uuid.UUID][]uuid.UUID{}} + + in := MarkInput{ + LiveRoots: []uuid.UUID{liveRoot}, + Objects: []storage.ObjectInfo{ + obj(liveRoot, "memfile", 1, old), + obj(orphan, "memfile", 2048, old), + obj(orphan, "rootfs.ext4.header", 20, old), + }, + Now: now, + Grace: 60 * 24 * time.Hour, + } + + m, err := Mark(context.Background(), reader, in) + require.NoError(t, err) + + require.Len(t, m.Candidates, 1) + assert.Equal(t, orphan, m.Candidates[0].BuildID) + assert.Equal(t, 2, m.Candidates[0].ObjectCount) + assert.Equal(t, int64(2068), m.Candidates[0].TotalBytes) +} + +// An unreferenced build with a fresh object is held back (grace), protecting the +// whole prefix — a fresh object may be an in-flight upload. +func TestMark_RecentObjectProtectsWholePrefix(t *testing.T) { + t.Parallel() + + now := time.Now() + old := now.Add(-100 * 24 * time.Hour) + fresh := now.Add(-1 * time.Hour) + + orphan := uuid.New() + + reader := stubReader{closures: map[uuid.UUID][]uuid.UUID{}} + + in := MarkInput{ + LiveRoots: nil, + Objects: []storage.ObjectInfo{ + obj(orphan, "memfile", 10, old), + obj(orphan, "memfile.header", 10, fresh), // one fresh object + }, + Now: now, + Grace: 60 * 24 * time.Hour, + } + + m, err := Mark(context.Background(), reader, in) + require.NoError(t, err) + + assert.Empty(t, m.Candidates) + require.Len(t, m.TooNew, 1) + assert.Equal(t, orphan, m.TooNew[0].BuildID) +} + +// If any live root's closure cannot be resolved, Mark fails closed. +func TestMark_FailsClosedOnUnreadableRoot(t *testing.T) { + t.Parallel() + + reader := stubReader{err: errors.New("header corrupt")} + + in := MarkInput{ + LiveRoots: []uuid.UUID{uuid.New()}, + Objects: []storage.ObjectInfo{obj(uuid.New(), "memfile", 1, time.Now().Add(-1000*time.Hour))}, + Now: time.Now(), + Grace: 60 * 24 * time.Hour, + } + + _, err := Mark(context.Background(), reader, in) + require.Error(t, err, "an unreadable live-root closure must fail closed, not produce candidates") +} + +// Keys not under a UUID prefix are surfaced as unknown, never deleted. +func TestMark_UnknownKeysSurfaced(t *testing.T) { + t.Parallel() + + now := time.Now() + old := now.Add(-100 * 24 * time.Hour) + + in := MarkInput{ + LiveRoots: nil, + Objects: []storage.ObjectInfo{ + {Path: "not-a-uuid/file", Size: 1, LastModified: old}, + {Path: "toplevel", Size: 1, LastModified: old}, + }, + Now: now, + Grace: 60 * 24 * time.Hour, + } + + m, err := Mark(context.Background(), stubReader{}, in) + require.NoError(t, err) + + assert.Empty(t, m.Candidates) + assert.ElementsMatch(t, []string{"not-a-uuid/file", "toplevel"}, m.UnknownKeys) +} diff --git a/packages/orchestrator/internal/templategc/metrics.go b/packages/orchestrator/internal/templategc/metrics.go new file mode 100644 index 00000000000..c0fb4ab3d0d --- /dev/null +++ b/packages/orchestrator/internal/templategc/metrics.go @@ -0,0 +1,75 @@ +package templategc + +import ( + "fmt" + "io" + "time" +) + +// WriteOrphanMetrics writes the mark/sweep outcome as Prometheus text-exposition +// gauges, suitable for the node_exporter textfile collector (a batch job exposes +// a gauge by writing a .prom file, not by running a server). Scraping this file +// gives the fleet a live "orphaned storage" trend that was previously only +// visible by eyeballing a one-off JSON manifest. +// +// manifest is the (fresh) mark result; sweep may be nil for a mark-only run. +func WriteOrphanMetrics(w io.Writer, manifest *Manifest, sweep *SweepResult, now time.Time) error { + var orphanBytes, tooNewBytes int64 + for _, c := range manifest.Candidates { + orphanBytes += c.TotalBytes + } + for _, c := range manifest.TooNew { + tooNewBytes += c.TotalBytes + } + + write := func(name, help string, value int64) error { + if _, err := fmt.Fprintf(w, "# HELP %s %s\n# TYPE %s gauge\n%s %d\n", name, help, name, name, value); err != nil { + return err + } + + return nil + } + + if err := write("template_gc_orphan_builds", "Build prefixes unreferenced by any live root and older than the grace period (deletion candidates).", int64(len(manifest.Candidates))); err != nil { + return err + } + if err := write("template_gc_orphan_bytes", "Aggregate bytes of orphaned (candidate) build prefixes. Alert on sustained growth: online deletion is not keeping up.", orphanBytes); err != nil { + return err + } + if err := write("template_gc_too_new_builds", "Unreferenced build prefixes held back by the grace window (possible in-flight upload).", int64(len(manifest.TooNew))); err != nil { + return err + } + if err := write("template_gc_too_new_bytes", "Aggregate bytes held back by the grace window.", tooNewBytes); err != nil { + return err + } + if err := write("template_gc_unknown_keys", "Object keys not under a UUID build prefix; surfaced for review, never deleted.", int64(len(manifest.UnknownKeys))); err != nil { + return err + } + if err := write("template_gc_keep_builds", "Builds kept because a live root reaches them through its header closure.", int64(len(manifest.Keep))); err != nil { + return err + } + + if sweep != nil { + if err := write("template_gc_swept_builds", "Build prefixes deleted (or that would be deleted in a dry run) by the last sweep.", int64(len(sweep.Deleted))); err != nil { + return err + } + if err := write("template_gc_swept_bytes", "Bytes reclaimed by the last sweep.", sweep.ReclaimedBytes); err != nil { + return err + } + if err := write("template_gc_sweep_skipped_changed", "Approved builds skipped because they became reachable or too-new since the mark (TOCTOU guard).", int64(len(sweep.SkippedChanged))); err != nil { + return err + } + if err := write("template_gc_sweep_failed", "Approved builds whose deletion errored (possible partial delete; retried next sweep).", int64(len(sweep.Failed))); err != nil { + return err + } + confirmed := int64(0) + if sweep.Confirmed { + confirmed = 1 + } + if err := write("template_gc_sweep_confirmed", "1 if the last sweep actually deleted objects, 0 if it was a dry run.", confirmed); err != nil { + return err + } + } + + return write("template_gc_last_run_timestamp_seconds", "Unix time of the last template-gc run.", now.Unix()) +} diff --git a/packages/orchestrator/internal/templategc/reader.go b/packages/orchestrator/internal/templategc/reader.go new file mode 100644 index 00000000000..f438c1c97e1 --- /dev/null +++ b/packages/orchestrator/internal/templategc/reader.go @@ -0,0 +1,42 @@ +package templategc + +import ( + "context" + "fmt" + + "github.com/google/uuid" + + "github.com/e2b-dev/infra/packages/shared/pkg/storage" + "github.com/e2b-dev/infra/packages/shared/pkg/storage/header" +) + +// StorageAncestorReader reads a build's memfile and rootfs headers from template +// storage and unions the build IDs their block mappings reference. It is the +// production AncestorReader. A missing or unparseable header returns an error so +// Mark fails closed. +type StorageAncestorReader struct { + Storage storage.StorageProvider +} + +func (r StorageAncestorReader) AncestorBuilds(ctx context.Context, buildID uuid.UUID) ([]uuid.UUID, error) { + paths := storage.Paths{BuildID: buildID.String()} + + seen := map[uuid.UUID]struct{}{buildID: {}} + for _, hdrPath := range []string{paths.MemfileHeader(), paths.RootfsHeader()} { + h, _, err := header.LoadHeader(ctx, r.Storage, hdrPath) + if err != nil { + return nil, fmt.Errorf("load header %s: %w", hdrPath, err) + } + + for _, b := range h.Mapping.Builds() { + seen[b] = struct{}{} + } + } + + out := make([]uuid.UUID, 0, len(seen)) + for b := range seen { + out = append(out, b) + } + + return out, nil +} diff --git a/packages/orchestrator/internal/templategc/sweep.go b/packages/orchestrator/internal/templategc/sweep.go new file mode 100644 index 00000000000..858491a7261 --- /dev/null +++ b/packages/orchestrator/internal/templategc/sweep.go @@ -0,0 +1,99 @@ +package templategc + +import ( + "context" + "fmt" + + "github.com/google/uuid" +) + +// PrefixDeleter physically removes every object under a build's storage prefix. +// It is the one side effect of the sweep and is injected so the engine stays +// pure and testable. The production implementation wraps +// storage.DeleteObjectsWithPrefix. +type PrefixDeleter interface { + DeletePrefix(ctx context.Context, buildID uuid.UUID) error +} + +// SweepResult is the outcome of a sweep. The counts reconcile: +// +// len(approved) == len(Deleted) + len(SkippedChanged) + len(Failed) (confirmed run) +// +// so "approved but not reclaimed" is always derivable. +type SweepResult struct { + // Deleted are build prefixes physically removed (or that WOULD be removed in + // a dry run — see Confirmed). + Deleted []BuildPrefix + // SkippedChanged are builds that were in the approved manifest but are no + // longer fresh deletion candidates: since the manifest was written they + // became reachable from a live root, or gained a too-new object (possible + // in-flight upload). This is the TOCTOU guard; these are intentionally kept. + SkippedChanged []uuid.UUID + // Failed are builds whose deletion was attempted but errored; their prefix + // may be partially deleted and is a candidate for the next sweep. + Failed []SweepFailure + // ReclaimedBytes is the aggregate size of Deleted prefixes. + ReclaimedBytes int64 + // Confirmed is false for a dry run (nothing was actually deleted). + Confirmed bool +} + +// SweepFailure records one prefix whose deletion errored. +type SweepFailure struct { + BuildID uuid.UUID + Err string +} + +// Sweep deletes the intersection of the operator-approved build IDs and a FRESH +// mark result, re-validating every approved build against ground truth at +// delete time. A build is deleted only if it is STILL a fresh candidate: +// - not reachable from any live root's header closure (fresh.Keep), and +// - old enough (not in fresh.TooNew). +// +// Anything approved that is no longer a fresh candidate is SkippedChanged, never +// deleted — this closes the window between the mark run that produced the +// manifest and the sweep that consumes it. Because the fresh Manifest is +// produced by Mark (which fails closed on any unreadable live root), the sweep +// inherits that fail-closed guarantee: if reachability could not be proven, +// fresh.Candidates is empty and nothing is deleted. +// +// When confirm is false the sweep is a dry run: it computes exactly what it +// would delete and returns it with Confirmed=false, calling the deleter zero +// times. A per-build delete error never aborts the others (best-effort). +func Sweep(ctx context.Context, deleter PrefixDeleter, approved []uuid.UUID, fresh *Manifest, confirm bool) (*SweepResult, error) { + if fresh == nil { + return nil, fmt.Errorf("sweep: fresh mark manifest is required") + } + + // Index the fresh candidates by build ID; only these are safe to delete now. + freshCandidate := make(map[uuid.UUID]BuildPrefix, len(fresh.Candidates)) + for _, c := range fresh.Candidates { + freshCandidate[c.BuildID] = c + } + + res := &SweepResult{Confirmed: confirm} + + for _, id := range approved { + bp, ok := freshCandidate[id] + if !ok { + // Approved by the manifest but no longer a fresh candidate: it became + // reachable or too-new since the mark. Keep it. + res.SkippedChanged = append(res.SkippedChanged, id) + + continue + } + + if confirm { + if err := deleter.DeletePrefix(ctx, id); err != nil { + res.Failed = append(res.Failed, SweepFailure{BuildID: id, Err: err.Error()}) + + continue + } + } + + res.Deleted = append(res.Deleted, bp) + res.ReclaimedBytes += bp.TotalBytes + } + + return res, nil +} diff --git a/packages/orchestrator/internal/templategc/sweep_test.go b/packages/orchestrator/internal/templategc/sweep_test.go new file mode 100644 index 00000000000..b14fd8d4ef5 --- /dev/null +++ b/packages/orchestrator/internal/templategc/sweep_test.go @@ -0,0 +1,156 @@ +package templategc + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// recordingDeleter records every prefix it is asked to delete and can be told to +// fail for specific build IDs. +type recordingDeleter struct { + deleted []uuid.UUID + failFor map[uuid.UUID]bool +} + +func (d *recordingDeleter) DeletePrefix(_ context.Context, buildID uuid.UUID) error { + if d.failFor[buildID] { + return errors.New("storage delete failed") + } + d.deleted = append(d.deleted, buildID) + + return nil +} + +func bp(id uuid.UUID, bytes int64) BuildPrefix { + return BuildPrefix{BuildID: id, ObjectCount: 1, TotalBytes: bytes} +} + +// A confirmed sweep deletes exactly the intersection of approved IDs and the +// fresh candidate set, and sums reclaimed bytes. +func TestSweep_DeletesIntersectionConfirmed(t *testing.T) { + t.Parallel() + + a, b := uuid.New(), uuid.New() + fresh := &Manifest{Candidates: []BuildPrefix{bp(a, 100), bp(b, 200)}} + + d := &recordingDeleter{} + res, err := Sweep(context.Background(), d, []uuid.UUID{a, b}, fresh, true) + require.NoError(t, err) + + assert.ElementsMatch(t, []uuid.UUID{a, b}, d.deleted) + assert.Len(t, res.Deleted, 2) + assert.Equal(t, int64(300), res.ReclaimedBytes) + assert.True(t, res.Confirmed) + assert.Empty(t, res.SkippedChanged) + assert.Empty(t, res.Failed) +} + +// An approved build that is no longer a fresh candidate (became reachable or +// too-new since the mark) must be skipped, never deleted. This is the TOCTOU +// guard between mark and sweep. +func TestSweep_SkipsBuildThatChangedSinceMark(t *testing.T) { + t.Parallel() + + stillOrphan := uuid.New() + nowReachable := uuid.New() // approved earlier, but not in fresh candidates now + + fresh := &Manifest{Candidates: []BuildPrefix{bp(stillOrphan, 10)}} + + d := &recordingDeleter{} + res, err := Sweep(context.Background(), d, []uuid.UUID{stillOrphan, nowReachable}, fresh, true) + require.NoError(t, err) + + assert.Equal(t, []uuid.UUID{stillOrphan}, d.deleted, "only the still-orphan build is deleted") + assert.Equal(t, []uuid.UUID{nowReachable}, res.SkippedChanged, "the changed build is skipped, not deleted") +} + +// A dry run (confirm=false) computes what it would delete but never calls the +// deleter. +func TestSweep_DryRunDeletesNothing(t *testing.T) { + t.Parallel() + + a := uuid.New() + fresh := &Manifest{Candidates: []BuildPrefix{bp(a, 42)}} + + d := &recordingDeleter{} + res, err := Sweep(context.Background(), d, []uuid.UUID{a}, fresh, false) + require.NoError(t, err) + + assert.Empty(t, d.deleted, "dry run must not call the deleter") + assert.Len(t, res.Deleted, 1, "but still reports what it would delete") + assert.Equal(t, int64(42), res.ReclaimedBytes) + assert.False(t, res.Confirmed) +} + +// A per-build delete failure never aborts the others and is recorded. +func TestSweep_DeleteFailureIsNonFatal(t *testing.T) { + t.Parallel() + + a, bad, c := uuid.New(), uuid.New(), uuid.New() + fresh := &Manifest{Candidates: []BuildPrefix{bp(a, 1), bp(bad, 2), bp(c, 3)}} + + d := &recordingDeleter{failFor: map[uuid.UUID]bool{bad: true}} + res, err := Sweep(context.Background(), d, []uuid.UUID{a, bad, c}, fresh, true) + require.NoError(t, err) + + assert.ElementsMatch(t, []uuid.UUID{a, c}, d.deleted) + require.Len(t, res.Failed, 1) + assert.Equal(t, bad, res.Failed[0].BuildID) + assert.Equal(t, int64(4), res.ReclaimedBytes, "failed build's bytes are not counted as reclaimed") +} + +// Sweep inherits Mark's fail-closed guarantee: when the fresh manifest has no +// candidates (e.g. Mark failed closed on an unreadable root upstream), nothing +// is deleted even though builds were approved. +func TestSweep_FailClosedWhenNoFreshCandidates(t *testing.T) { + t.Parallel() + + a := uuid.New() + fresh := &Manifest{Candidates: nil} + + d := &recordingDeleter{} + res, err := Sweep(context.Background(), d, []uuid.UUID{a}, fresh, true) + require.NoError(t, err) + + assert.Empty(t, d.deleted) + assert.Equal(t, []uuid.UUID{a}, res.SkippedChanged) +} + +func TestSweep_NilManifestErrors(t *testing.T) { + t.Parallel() + + _, err := Sweep(context.Background(), &recordingDeleter{}, []uuid.UUID{uuid.New()}, nil, true) + require.Error(t, err) +} + +// WriteOrphanMetrics emits parseable Prometheus gauges for both mark and sweep. +func TestWriteOrphanMetrics_EmitsGauges(t *testing.T) { + t.Parallel() + + a := uuid.New() + manifest := &Manifest{ + Candidates: []BuildPrefix{bp(a, 1000)}, + TooNew: []BuildPrefix{bp(uuid.New(), 50)}, + Keep: []uuid.UUID{uuid.New()}, + } + sweep := &SweepResult{Deleted: []BuildPrefix{bp(a, 1000)}, ReclaimedBytes: 1000, Confirmed: true} + + var sb strings.Builder + require.NoError(t, WriteOrphanMetrics(&sb, manifest, sweep, time.Unix(1700000000, 0))) + out := sb.String() + + assert.Contains(t, out, "template_gc_orphan_builds 1") + assert.Contains(t, out, "template_gc_orphan_bytes 1000") + assert.Contains(t, out, "template_gc_too_new_bytes 50") + assert.Contains(t, out, "template_gc_swept_bytes 1000") + assert.Contains(t, out, "template_gc_sweep_confirmed 1") + assert.Contains(t, out, "template_gc_last_run_timestamp_seconds 1700000000") + assert.Contains(t, out, "# TYPE template_gc_orphan_bytes gauge") +} diff --git a/packages/shared/pkg/storage/objlister_test.go b/packages/shared/pkg/storage/objlister_test.go new file mode 100644 index 00000000000..3f92dfff384 --- /dev/null +++ b/packages/shared/pkg/storage/objlister_test.go @@ -0,0 +1,66 @@ +package storage + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestFSStorage_ListObjects(t *testing.T) { + t.Parallel() + + base := t.TempDir() + s := newFileSystemStorage(base, "", nil) + + // Two build prefixes, one with two objects. + require.NoError(t, os.MkdirAll(filepath.Join(base, "build-a"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(base, "build-b"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(base, "build-a", "memfile"), []byte("hello"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(base, "build-a", "rootfs.ext4.header"), []byte("hdr"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(base, "build-b", "memfile"), []byte("x"), 0o644)) + + objs, err := s.ListObjects(context.Background(), "") + require.NoError(t, err) + + paths := make(map[string]int64) + for _, o := range objs { + paths[o.Path] = o.Size + assert.False(t, o.LastModified.IsZero(), "LastModified must be populated for grace checks") + } + + assert.Equal(t, int64(5), paths["build-a/memfile"]) + assert.Equal(t, int64(3), paths["build-a/rootfs.ext4.header"]) + assert.Equal(t, int64(1), paths["build-b/memfile"]) + assert.Len(t, objs, 3) +} + +func TestFSStorage_ListObjects_PrefixScoped(t *testing.T) { + t.Parallel() + + base := t.TempDir() + s := newFileSystemStorage(base, "", nil) + require.NoError(t, os.MkdirAll(filepath.Join(base, "build-a"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(base, "build-b"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(base, "build-a", "memfile"), []byte("a"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(base, "build-b", "memfile"), []byte("b"), 0o644)) + + objs, err := s.ListObjects(context.Background(), "build-a") + require.NoError(t, err) + require.Len(t, objs, 1) + assert.Equal(t, "build-a/memfile", objs[0].Path) +} + +// ListObjects helper returns ErrListUnsupported for a provider without the +// capability, so callers fail closed instead of seeing an empty bucket. +func TestListObjects_UnsupportedFailsClosed(t *testing.T) { + t.Parallel() + + _, err := ListObjects(context.Background(), noListProvider{}, "") + assert.ErrorIs(t, err, ErrListUnsupported) +} + +type noListProvider struct{ StorageProvider } diff --git a/packages/shared/pkg/storage/storage.go b/packages/shared/pkg/storage/storage.go index f517dfdede6..a57e6624bb0 100644 --- a/packages/shared/pkg/storage/storage.go +++ b/packages/shared/pkg/storage/storage.go @@ -39,6 +39,11 @@ var ErrObjectSoftDeleted = errors.New("object soft-deleted by storage index") // backend instead of assuming there is no tombstone. var ErrMetadataUnsupported = errors.New("blob does not support reading custom metadata") +// ErrListUnsupported means the storage backend cannot enumerate objects under a +// prefix. Callers (e.g. the template GC mark tool) must fail closed when they +// get this rather than treat the bucket as empty. +var ErrListUnsupported = errors.New("storage provider does not support listing objects") + // ObjectMetadataSoftDeleted is the storage-index soft-delete tombstone key. const ObjectMetadataSoftDeleted = storageopts.ObjectMetadataSoftDeleted @@ -149,6 +154,38 @@ type MetadataReader interface { Metadata(ctx context.Context) (ObjectMetadata, error) } +// ObjectInfo describes one object returned by ObjectLister. +type ObjectInfo struct { + // Path is the object's full key (e.g. "{buildID}/memfile.header"). + Path string + // Size is the object size in bytes. + Size int64 + // LastModified is the object's last-modified time, used by the GC grace + // window: a build prefix is only a deletion candidate when every object + // under it is older than the grace period. + LastModified time.Time +} + +// ObjectLister is an optional StorageProvider capability: enumerate every object +// under a prefix (paginated internally). Required by full-bucket operations like +// the template GC mark tool; backends that cannot list omit it and callers fail +// closed via ErrListUnsupported. +type ObjectLister interface { + ListObjects(ctx context.Context, prefix string) ([]ObjectInfo, error) +} + +// ListObjects lists every object under prefix, or returns ErrListUnsupported if +// the provider cannot enumerate — so callers can distinguish "bucket empty" from +// "couldn't list" and refuse to treat an unlistable bucket as having no objects. +func ListObjects(ctx context.Context, p StorageProvider, prefix string) ([]ObjectInfo, error) { + l, ok := p.(ObjectLister) + if !ok { + return nil, ErrListUnsupported + } + + return l.ListObjects(ctx, prefix) +} + // BlobCustomMetadata returns the blob's custom metadata, or ErrMetadataUnsupported // when the backend can't read it — so callers can distinguish "no tombstone" // from "couldn't check" and fail closed under enforcement. diff --git a/packages/shared/pkg/storage/storage_aws.go b/packages/shared/pkg/storage/storage_aws.go index 52c8d49ab14..45158443f52 100644 --- a/packages/shared/pkg/storage/storage_aws.go +++ b/packages/shared/pkg/storage/storage_aws.go @@ -580,3 +580,35 @@ func (m *awsPartUploader) Close() error { return err } + +// ListObjects enumerates every object under prefix, paginating through the full +// result set. Implements the ObjectLister optional capability. +func (s *awsStorage) ListObjects(ctx context.Context, prefix string) ([]ObjectInfo, error) { + paginator := s3.NewListObjectsV2Paginator(s.client, &s3.ListObjectsV2Input{ + Bucket: aws.String(s.bucketName), + Prefix: aws.String(prefix), + }) + + var out []ObjectInfo + for paginator.HasMorePages() { + pageCtx, cancel := context.WithTimeout(ctx, awsOperationTimeout) + list, err := paginator.NextPage(pageCtx) + cancel() + if err != nil { + return nil, err + } + + for _, obj := range list.Contents { + info := ObjectInfo{Path: aws.ToString(obj.Key)} + if obj.Size != nil { + info.Size = *obj.Size + } + if obj.LastModified != nil { + info.LastModified = *obj.LastModified + } + out = append(out, info) + } + } + + return out, nil +} diff --git a/packages/shared/pkg/storage/storage_fs.go b/packages/shared/pkg/storage/storage_fs.go index 4fc101ef063..d1ca36b247e 100644 --- a/packages/shared/pkg/storage/storage_fs.go +++ b/packages/shared/pkg/storage/storage_fs.go @@ -422,3 +422,57 @@ func (o *fsObject) OpenRangeReader(ctx context.Context, offsetU int64, length in return raw, SourceFS, nil } + +// ListObjects walks the filesystem under prefix and reports each regular file as +// an object. Implements the ObjectLister optional capability (used by tests and +// local dry runs). +func (s *fsStorage) ListObjects(_ context.Context, prefix string) ([]ObjectInfo, error) { + // An empty prefix means "the whole bucket" (a valid listing), which the + // object-path validator rejects — so resolve the root directly for the empty + // case and only validate a non-empty prefix. + root := s.basePath + if prefix != "" { + p, err := s.getPath(prefix) + if err != nil { + return nil, err + } + root = p + } + + var out []ObjectInfo + err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { + if err != nil { + if os.IsNotExist(err) { + return nil + } + + return err + } + if d.IsDir() { + return nil + } + + info, statErr := d.Info() + if statErr != nil { + return statErr + } + + rel, relErr := filepath.Rel(s.basePath, path) + if relErr != nil { + return relErr + } + + out = append(out, ObjectInfo{ + Path: filepath.ToSlash(rel), + Size: info.Size(), + LastModified: info.ModTime(), + }) + + return nil + }) + if err != nil { + return nil, err + } + + return out, nil +}