From 4ff3147ee58c50f8e53122390e1572bfec7624cd Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Sat, 28 Nov 2026 17:20:03 -0800 Subject: [PATCH] worker: filer_ttl job removes expired rows from stores without native TTL (#13084) * worker: add a filer_ttl job that walks filer.conf TTL paths A filer store without native TTL keeps the rows of expired entries until something looks them up or lists their directory. The job lists every TTL path subtree once per filer store, so the filer drops the expired rows it meets. Co-Authored-By: Claude Opus 5.5 * worker: register the filer_ttl job in the lifecycle lane Co-Authored-By: Claude Opus 5.5 * filer: re-check an expired entry under its path lock before a listing deletes it A listing deleted the expired entries it collected by path after the page was read, so a write that replaced one in between lost its new row. The delete now re-reads the row under the lock writers take, and in one conflict-checked transaction on stores that refuse a commit over another writer's change; anything but a still-expired row is kept. Co-Authored-By: Claude Opus 5.5 * worker: read each filer store's own filer.conf, chunk-backed included Filers with separate stores keep separate filer.conf files, so one filer's rules could hide another store's TTL paths. A config stored in chunks read as empty. An unreadable config now fails the detection instead of reading as no rules. Co-Authored-By: Claude Opus 5.5 * command: count filer_ttl among the mini default job types Co-Authored-By: Claude Opus 5.5 * worker: resume an unfinished filer_ttl walk from its checkpoint The walk position is saved in the job's filer store every 30s and at the first failure, keyed by store signature, and cleared when a pass completes. The next run skips the prefixes and subtrees already walked, unless the TTL prefix set changed or the pass is over 7 days old. Co-Authored-By: Claude Opus 5.5 * worker: save the filer_ttl checkpoint as soon as a walk fails The first failure froze the checkpoint but only the end of the run saved it, so a worker killed while walking later prefixes lost it. stop now saves it at once; the end of the run saves again only if that save failed. Co-Authored-By: Claude Opus 5.5 * worker: keep a path TTL rule from expiring the filer_ttl checkpoint A filer.conf TTL rule over /etc/ gave the checkpoint that rule's TTL, so an interrupted pass could lose its record long before checkpointMaxAge. The checkpoint is now written with its own TTL of checkpointMaxAge, which the filer keeps instead of the rule's. Co-Authored-By: Claude Opus 5.5 * worker: remove a filer_ttl checkpoint the new pass will not resume from An overwrite keeps the stored entry's Crtime, and the checkpoint's TTL counts from it, so a pass that replaced a rejected record could lose its own record before checkpointMaxAge. load now deletes a record it rejects, and the new pass creates a fresh one. Co-Authored-By: Claude Opus 5.5 * worker: expire filer_ttl entries from metadata events per TTL rule Each run replays every filer.conf TTL rule's metadata events from that rule's cursor up to the run start, and looks up each entry whose TTL has passed so the filer removes its row. The first entry not yet due holds the rule's cursor, so a later run replays it. A rule without a cursor, or whose TTL changed, is listed once to reach rows older than its replay window. The periodic full walk and its checkpoint are gone. Co-Authored-By: Claude Opus 5.5 * filer: re-check an S3-expired entry under its path lock before a listing deletes it A listing deleted an S3-expired object by the row it had read, so an upload that replaced it after the page was read was removed. The delete now re-reads the row under the path lock and removes it only if it is still S3-expired. Co-Authored-By: Claude Opus 5.5 * filer: remove an expired row a lookup meets in a conflict-checked transaction A lookup that met an expired row deleted it by path, so a replacement written through another filer between the read and the delete was lost, even on stores that refuse conflicting commits; a failed delete was hidden behind not found. The lookup now re-reads and deletes through deleteIfExpired and returns the delete error. Co-Authored-By: Claude Opus 5.5 * worker: keep a failed filer_ttl lookup that ties a done event When the first event at a timestamp was done and the second one's lookup failed, the cursor already stood at that timestamp, so the retry subscribed after it and skipped the failed event. A failed lookup now holds the cursor below a tie, as a waiting entry does. Co-Authored-By: Claude Opus 5.5 * worker: hold a filer_ttl event whose entry the filer still serves A lookup that returned the live entry counted as done, so when the worker's clock ran ahead of the filer's near the deadline the event was skipped and the row stayed. An entry the filer still serves with the same deadline now holds the cursor like one not yet due. Co-Authored-By: Claude Opus 5.5 * worker: keep a path TTL rule from expiring the filer_ttl cursors The cursors were written without a TTL, so a filer.conf TTL rule covering /etc/seaweedfs/filer_ttl gave them the rule's TTL and every rule was listed again once they expired. When a rule covers them they are now written with a TTL of their own, which the filer keeps. Co-Authored-By: Claude Opus 5.5 * worker: list a filer_ttl rule again for a live entry its replay cannot reach A new rule nested under a longer one started its replay one TTL back, so a live entry the enclosing rule had stamped with its longer TTL, written before that, was in neither rule's replay: the nested rule now owns it and the enclosing rule skips it. The listing of a new rule now records the earliest deadline of such entries, and the rule is listed again then. Co-Authored-By: Claude Opus 5.5 * worker: hand a removed filer_ttl rule's replay to the rule enclosing it When a nested rule was removed, its entries became the enclosing rule's, but that rule's cursor could already be past their events, so they were never replayed. The enclosing rule now replays from the earlier of both cursors. Co-Authored-By: Claude Opus 5.5 * worker: list a filer_ttl rule whose unfinished events the filer no longer keeps When fs.log.purge removed the event of an entry still waiting for its TTL, the rule's cursor matched, so the rule was never listed and the replay never met the entry again. A rule whose cursor is older than the oldest kept metadata log is now listed, and its cursor moves to that log. The cursor also records how far a replay read with nothing left waiting, so a quiet rule is not listed just because old logs were purged. Co-Authored-By: Claude Opus 5.5 * worker: leave S3 lifecycle expiry to the s3_lifecycle job in filer_ttl An entry whose TTL an S3 lifecycle rule set carries the S3 expiry flag; s3_lifecycle evaluates and removes it. filer_ttl no longer looks such entries up, and their deadline no longer holds a TTL rule's cursor. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- weed/admin/plugin/scheduler_lane.go | 1 + weed/command/mini_plugin_test.go | 4 +- weed/command/worker_test.go | 1 + weed/filer/filer.go | 19 +- weed/filer/filer_expired_entry.go | 83 ++ weed/filer/filer_expired_entry_test.go | 217 +++++ weed/plugin/worker/handlers/handlers.go | 1 + weed/worker/tasks/filer_ttl/handler.go | 233 +++++ weed/worker/tasks/filer_ttl/handler_test.go | 899 ++++++++++++++++++++ weed/worker/tasks/filer_ttl/replay.go | 443 ++++++++++ weed/worker/tasks/filer_ttl/walk.go | 55 ++ 11 files changed, 1943 insertions(+), 13 deletions(-) create mode 100644 weed/filer/filer_expired_entry.go create mode 100644 weed/filer/filer_expired_entry_test.go create mode 100644 weed/worker/tasks/filer_ttl/handler.go create mode 100644 weed/worker/tasks/filer_ttl/handler_test.go create mode 100644 weed/worker/tasks/filer_ttl/replay.go create mode 100644 weed/worker/tasks/filer_ttl/walk.go diff --git a/weed/admin/plugin/scheduler_lane.go b/weed/admin/plugin/scheduler_lane.go index 9dcfa41518..22e6fd3d67 100644 --- a/weed/admin/plugin/scheduler_lane.go +++ b/weed/admin/plugin/scheduler_lane.go @@ -91,6 +91,7 @@ var jobTypeLaneMap = map[string]SchedulerLane{ // S3 lifecycle management "s3_lifecycle": LaneLifecycle, + "filer_ttl": LaneLifecycle, // Lance table maintenance. Without these the job types fall back to the // default lane, which serialises everything under the cluster admin lock diff --git a/weed/command/mini_plugin_test.go b/weed/command/mini_plugin_test.go index f302e01af5..e39947d215 100644 --- a/weed/command/mini_plugin_test.go +++ b/weed/command/mini_plugin_test.go @@ -15,7 +15,7 @@ func TestMiniDefaultPluginJobTypes(t *testing.T) { if err != nil { t.Fatalf("buildPluginWorkerHandlers(mini default) err = %v", err) } - if len(handlers) != 7 { - t.Fatalf("expected mini default job types to include 7 handlers, got %d", len(handlers)) + if len(handlers) != 8 { + t.Fatalf("expected mini default job types to include 8 handlers, got %d", len(handlers)) } } diff --git a/weed/command/worker_test.go b/weed/command/worker_test.go index b2044b9def..b44cf37007 100644 --- a/weed/command/worker_test.go +++ b/weed/command/worker_test.go @@ -19,6 +19,7 @@ func TestWorkerDefaultJobTypes(t *testing.T) { "admin_script", "ec_balance", "erasure_coding", + "filer_ttl", "iceberg_maintenance", "s3_lifecycle", "vacuum", diff --git a/weed/filer/filer.go b/weed/filer/filer.go index c666b31fcf..fabdacf670 100644 --- a/weed/filer/filer.go +++ b/weed/filer/filer.go @@ -1141,7 +1141,10 @@ func (f *Filer) findEntry(ctx context.Context, p util.FullPath) (entry *Entry, f return nil, gone, filer_pb.ErrNotFound } } else if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) { - gone := f.Store.DeleteOneEntry(ctx, entry) == nil + gone, delErr := f.deleteIfExpired(ctx, p) + if delErr != nil { + return nil, false, fmt.Errorf("delete expired %s: %w", p, delErr) + } return nil, gone, filer_pb.ErrNotFound } } @@ -1180,7 +1183,6 @@ func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, sta // Collect expired entries during iteration to avoid deadlock with DB connection pool var expiredEntries []*Entry - var s3ExpiredEntries []*Entry var hasValidEntries bool lastFileName, err = f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix, func(entry *Entry) (bool, error) { @@ -1193,7 +1195,7 @@ func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, sta if entry.IsExpireS3Enabled() { if entry.GetS3ExpireTime().Before(time.Now()) && !entry.IsS3Versioning() { // Collect for deletion after iteration completes to avoid DB deadlock - s3ExpiredEntries = append(s3ExpiredEntries, entry) + expiredEntries = append(expiredEntries, entry) expiredCount++ return true, nil } @@ -1214,15 +1216,10 @@ func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, sta } // Delete expired entries after iteration completes to avoid DB connection deadlock - if len(s3ExpiredEntries) > 0 || len(expiredEntries) > 0 { - for _, entry := range s3ExpiredEntries { - if delErr := f.doDeleteEntryMetaAndData(ctx, entry, true, false, nil); delErr != nil { - glog.ErrorfCtx(ctx, "doListDirectoryEntries doDeleteEntryMetaAndData %s failed: %v", entry.FullPath, delErr) - } - } + if len(expiredEntries) > 0 { for _, entry := range expiredEntries { - if delErr := f.Store.DeleteOneEntry(ctx, entry); delErr != nil { - glog.ErrorfCtx(ctx, "doListDirectoryEntries DeleteOneEntry %s failed: %v", entry.FullPath, delErr) + if delErr := f.deleteExpiredEntry(ctx, entry.FullPath); delErr != nil { + glog.ErrorfCtx(ctx, "doListDirectoryEntries delete expired %s failed: %v", entry.FullPath, delErr) } } diff --git a/weed/filer/filer_expired_entry.go b/weed/filer/filer_expired_entry.go new file mode 100644 index 0000000000..3541655874 --- /dev/null +++ b/weed/filer/filer_expired_entry.go @@ -0,0 +1,83 @@ +package filer + +import ( + "context" + "errors" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// deleteExpiredEntry removes an entry a listing found expired. The row is +// re-read under the lock writers take, so a replacement written after the +// listing read the row is kept; a contended path is left to a later listing. +func (f *Filer) deleteExpiredEntry(ctx context.Context, p util.FullPath) error { + if lt := f.EntryLockTable; lt != nil { + lock, acquired := lt.TryAcquireLock("deleteExpiredEntry", p, util.ExclusiveLock) + if !acquired { + return nil + } + defer lt.ReleaseLock(p, lock) + } + current, err := f.Store.FindEntry(ctx, p) + if err != nil { + if errors.Is(err, filer_pb.ErrNotFound) { + return nil + } + return err + } + if !current.IsExpireS3Enabled() { + _, err = f.deleteIfExpired(ctx, p) + return err + } + // Its remote delete and event would outlive a refused commit, so it is + // removed outside a transaction. + if ctx.Value(storeTransactionKey{}) != nil || current.IsDirectory() || current.TtlSec <= 0 || + current.IsS3Versioning() || !current.GetS3ExpireTime().Before(time.Now()) { + return nil + } + return f.doDeleteEntryMetaAndData(ctx, current, true, false, nil) +} + +// deleteIfExpired removes p's row if its TTL has passed, and reports whether +// the store then holds nothing at p. On a store that refuses conflicting +// commits the re-read and the delete share a transaction, so a replacement +// written through another filer is kept. +func (f *Filer) deleteIfExpired(ctx context.Context, p util.FullPath) (gone bool, err error) { + if !f.RefusesConflictingCommits(p) || ctx.Value(storeTransactionKey{}) != nil { + return f.deleteRowIfExpired(ctx, p) + } + txCtx, err := f.BeginTransaction(ctx) + if err != nil { + return false, err + } + if gone, err = f.deleteRowIfExpired(txCtx, p); err == nil { + err = f.CommitTransaction(txCtx) + } + if err != nil { + f.RollbackTransaction(txCtx) + if errors.Is(err, ErrTransactionConflict) { + return false, nil + } + return false, err + } + return gone, nil +} + +func (f *Filer) deleteRowIfExpired(ctx context.Context, p util.FullPath) (gone bool, err error) { + current, err := f.Store.FindEntry(ctx, p) + if err != nil { + if errors.Is(err, filer_pb.ErrNotFound) { + return true, nil + } + return false, err + } + if current.IsDirectory() || current.TtlSec <= 0 || current.IsExpireS3Enabled() || !current.Crtime.Add(time.Duration(current.TtlSec)*time.Second).Before(time.Now()) { + return false, nil + } + if err := f.Store.DeleteOneEntry(ctx, current); err != nil { + return false, err + } + return true, nil +} diff --git a/weed/filer/filer_expired_entry_test.go b/weed/filer/filer_expired_entry_test.go new file mode 100644 index 0000000000..866d553224 --- /dev/null +++ b/weed/filer/filer_expired_entry_test.go @@ -0,0 +1,217 @@ +package filer + +import ( + "context" + "errors" + "os" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +func putSweepTestEntry(t *testing.T, store *stubFilerStore, path string, isDir bool, ttlSec int32, crtime time.Time) { + t.Helper() + mode := os.FileMode(0o644) + if isDir { + mode = os.ModeDir | 0o755 + } + entry := &Entry{FullPath: util.FullPath(path), Attr: Attr{Mode: mode, Crtime: crtime, Mtime: crtime, TtlSec: ttlSec}} + if err := store.InsertEntry(context.Background(), entry); err != nil { + t.Fatal(err) + } +} + +func TestDeleteExpiredEntryKeepsAReplacement(t *testing.T) { + f, store := newTestFilerWithStubStore(t) + ctx := context.Background() + p := util.FullPath("/logs/current") + + putSweepTestEntry(t, store, string(p), false, 120, time.Now()) + if err := f.deleteExpiredEntry(ctx, p); err != nil { + t.Fatal(err) + } + if store.getEntry(string(p)) == nil { + t.Fatal("live replacement removed") + } + + putSweepTestEntry(t, store, string(p), false, 120, time.Now().Add(-time.Hour)) + lock := f.EntryLockTable.AcquireLock("test", p, util.ExclusiveLock) + if err := f.deleteExpiredEntry(ctx, p); err != nil { + t.Fatal(err) + } + f.EntryLockTable.ReleaseLock(p, lock) + if store.getEntry(string(p)) == nil { + t.Fatal("removed while a writer held the path") + } + + s3Expiring := &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: time.Now().Add(-time.Hour), Mtime: time.Now(), TtlSec: 120}, + Extended: map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}} + if err := store.InsertEntry(ctx, s3Expiring); err != nil { + t.Fatal(err) + } + if err := f.deleteExpiredEntry(ctx, p); err != nil { + t.Fatal(err) + } + if store.getEntry(string(p)) == nil { + t.Fatal("replacement under S3 expiration removed by its creation time") + } + + putSweepTestEntry(t, store, string(p), false, 120, time.Now().Add(-time.Hour)) + if err := f.deleteExpiredEntry(ctx, p); err != nil { + t.Fatal(err) + } + if store.getEntry(string(p)) != nil { + t.Fatal("expired entry kept") + } +} + +// Another filer on the same store does not take this filer's lock: a write it +// makes between the re-read and the delete gets the delete's commit refused. +func TestDeleteExpiredEntryKeepsAReplacementFromAnotherFiler(t *testing.T) { + f, _ := newTestFilerWithStubStore(t) + store := newVersionedStore() + f.Store = NewFilerStoreWrapper(store) + other := NewFilerStoreWrapper(store) + ctx := context.Background() + p := util.FullPath("/logs/current") + old := time.Now().Add(-time.Hour) + expired := &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: old, Mtime: old, TtlSec: 120}} + + if err := other.InsertEntry(ctx, expired); err != nil { + t.Fatal(err) + } + ran := store.once(t, "r"+string(p), func() error { + return other.InsertEntry(ctx, &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: time.Now(), Mtime: time.Now(), TtlSec: 120}}) + }) + if err := f.deleteExpiredEntry(ctx, p); err != nil { + t.Fatal(err) + } + if !*ran { + t.Fatal("the expired entry was not re-read in a transaction") + } + if store.getEntry(string(p)) == nil { + t.Fatal("replacement written through another filer removed") + } + + store.afterRead = nil + if err := other.InsertEntry(ctx, expired); err != nil { + t.Fatal(err) + } + if err := f.deleteExpiredEntry(ctx, p); err != nil { + t.Fatal(err) + } + if store.getEntry(string(p)) != nil { + t.Fatal("expired entry kept") + } +} + +// replacingStore writes a fresh entry over replaced once a listing has read +// the directory, as an upload would between the listing and its expiry delete. +type replacingStore struct { + *stubFilerStore + replaced util.FullPath +} + +func (s *replacingStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (string, error) { + last, err := s.stubFilerStore.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, prefix, eachEntryFunc) + if err == nil && s.replaced != "" { + now := time.Now() + fresh := &Entry{FullPath: s.replaced, Attr: Attr{Mode: 0o644, Crtime: now, Mtime: now, TtlSec: 120}} + s.replaced = "" + if err := s.stubFilerStore.InsertEntry(ctx, fresh); err != nil { + return last, err + } + } + return last, err +} + +func TestListingKeepsAnExpiredEntryReplacedMeanwhile(t *testing.T) { + for _, s3Expiring := range []bool{false, true} { + f, stub := newTestFilerWithStubStore(t) + p := util.FullPath("/clips/latest.mp4") + f.Store = NewFilerStoreWrapper(&replacingStore{stubFilerStore: stub, replaced: p}) + putSweepTestEntry(t, stub, "/clips", true, 0, time.Now()) + old := time.Now().Add(-time.Hour) + expired := &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: old, Mtime: old, TtlSec: 120}} + if s3Expiring { + expired.Extended = map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")} + } + if err := stub.InsertEntry(context.Background(), expired); err != nil { + t.Fatal(err) + } + + if _, _, err := f.ListDirectoryEntries(context.Background(), "/clips", "", false, 100, "", "", ""); err != nil { + t.Fatal(err) + } + if stub.getEntry(string(p)) == nil { + t.Fatalf("s3Expiring=%v: replacement written after the listing read the expired row was removed", s3Expiring) + } + } +} + +func TestDeleteExpiredEntryRemovesAnExpiredS3Object(t *testing.T) { + f, store := newTestFilerWithStubStore(t) + p := util.FullPath("/buckets/b/old.txt") + old := time.Now().Add(-time.Hour) + if err := store.InsertEntry(context.Background(), &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: old, Mtime: old, TtlSec: 120}, + Extended: map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}}); err != nil { + t.Fatal(err) + } + if err := f.deleteExpiredEntry(context.Background(), p); err != nil { + t.Fatal(err) + } + if store.getEntry(string(p)) != nil { + t.Fatal("expired S3 object kept") + } +} + +// A lookup through another filer on the same store meets an expired row that +// this filer's writer is replacing: the lookup's delete re-reads in a +// transaction the replacement makes it refuse. +func TestFindEntryKeepsAReplacementFromAnotherFiler(t *testing.T) { + f, _ := newTestFilerWithStubStore(t) + store := newVersionedStore() + f.Store = NewFilerStoreWrapper(store) + other := NewFilerStoreWrapper(store) + ctx := context.Background() + p := util.FullPath("/logs/current") + old := time.Now().Add(-time.Hour) + + if err := other.InsertEntry(ctx, &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: old, Mtime: old, TtlSec: 120}}); err != nil { + t.Fatal(err) + } + ran := store.once(t, "r"+string(p), func() error { + return other.InsertEntry(ctx, &Entry{FullPath: p, Attr: Attr{Mode: 0o644, Crtime: time.Now(), Mtime: time.Now(), TtlSec: 120}}) + }) + if _, err := f.FindEntry(ctx, p); !errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("lookup of the expired row: %v", err) + } + if !*ran { + t.Fatal("the expired row was not re-read in a transaction") + } + if store.getEntry(string(p)) == nil { + t.Fatal("replacement written through another filer removed") + } +} + +type failingDeleteStore struct { + *stubFilerStore +} + +func (s *failingDeleteStore) DeleteEntry(context.Context, util.FullPath) error { + return errors.New("store unavailable") +} + +func TestFindEntryReportsAFailedExpiryDelete(t *testing.T) { + f, stub := newTestFilerWithStubStore(t) + f.Store = NewFilerStoreWrapper(&failingDeleteStore{stubFilerStore: stub}) + p := util.FullPath("/logs/old") + putSweepTestEntry(t, stub, string(p), false, 120, time.Now().Add(-time.Hour)) + + if _, err := f.FindEntry(context.Background(), p); err == nil || errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("lookup hid a failed delete of the expired row: %v", err) + } +} diff --git a/weed/plugin/worker/handlers/handlers.go b/weed/plugin/worker/handlers/handlers.go index d96792e220..f914b6feb9 100644 --- a/weed/plugin/worker/handlers/handlers.go +++ b/weed/plugin/worker/handlers/handlers.go @@ -8,6 +8,7 @@ import ( _ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance" // register volume_balance handler _ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/ec_balance" // register ec_balance handler _ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding" // register erasure_coding handler + _ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/filer_ttl" // register filer_ttl handler _ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/iceberg" // register iceberg_maintenance handler _ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/s3_lifecycle" // register s3_lifecycle handler _ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum" // register vacuum handler diff --git a/weed/worker/tasks/filer_ttl/handler.go b/weed/worker/tasks/filer_ttl/handler.go new file mode 100644 index 0000000000..5cd12d17f3 --- /dev/null +++ b/weed/worker/tasks/filer_ttl/handler.go @@ -0,0 +1,233 @@ +package filer_ttl + +import ( + "context" + "fmt" + "math" + "strings" + "time" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb" + pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker" + "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/seaweedfs/seaweedfs/weed/wdclient" + "google.golang.org/grpc" +) + +const ( + jobType = "filer_ttl" + filerAddressParam = "filer_address" + defaultDetectionMinutes = 24 * 60 +) + +func init() { + pluginworker.RegisterHandler(pluginworker.HandlerFactory{ + JobType: jobType, + Category: pluginworker.CategoryDefault, + Aliases: []string{"filer-ttl", "filer.ttl"}, + Build: func(opts pluginworker.HandlerBuildOptions) (pluginworker.JobHandler, error) { + return NewHandler(opts.GrpcDialOption), nil + }, + }) +} + +// Handler removes the filer rows of entries whose filer.conf path TTL has +// passed. A store without native TTL keeps such rows until something looks +// them up, long after the TTL volumes holding the data are gone. +type Handler struct { + grpcDialOption grpc.DialOption +} + +func NewHandler(grpcDialOption grpc.DialOption) *Handler { + return &Handler{grpcDialOption: grpcDialOption} +} + +func (h *Handler) Capability() *plugin_pb.JobTypeCapability { + return &plugin_pb.JobTypeCapability{ + JobType: jobType, + CanDetect: true, + CanExecute: true, + MaxDetectionConcurrency: 1, + MaxExecutionConcurrency: 1, + DisplayName: "Filer TTL", + Description: "Replay filer metadata events under filer.conf TTL paths so the filer removes the rows of expired entries.", + Weight: 20, + } +} + +func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor { + return &plugin_pb.JobTypeDescriptor{ + JobType: jobType, + DisplayName: "Filer TTL", + Description: "Remove the filer rows of entries past their filer.conf path TTL, once per filer store.", + Icon: "bi bi-hourglass-split", + DescriptorVersion: 1, + AdminRuntimeDefaults: &plugin_pb.AdminRuntimeDefaults{ + Enabled: true, + DetectionIntervalMinutes: defaultDetectionMinutes, + DetectionTimeoutSeconds: 60, + ExecutionTimeoutSeconds: math.MaxInt32, + JobTypeMaxRuntimeSeconds: math.MaxInt32, + }, + WorkerDefaultValues: map[string]*plugin_pb.ConfigValue{}, + } +} + +func (h *Handler) Detect(ctx context.Context, request *plugin_pb.RunDetectionRequest, sender pluginworker.DetectionSender) error { + if request == nil || sender == nil { + return fmt.Errorf("detect: nil request or sender") + } + if request.JobType != "" && request.JobType != jobType { + return fmt.Errorf("job type %q is not handled by filer ttl handler", request.JobType) + } + var filers []pb.ServerAddress + for _, address := range request.GetClusterContext().GetFilerAddresses() { + if address != "" { + filers = append(filers, pb.ServerAddress(address)) + } + } + if len(filers) == 0 { + _ = sender.SendActivity(pluginworker.BuildDetectorActivity("skipped", "no filer addresses in cluster context", nil)) + return sender.SendComplete(&plugin_pb.DetectionComplete{JobType: jobType, Success: true}) + } + var proposals []*plugin_pb.JobProposal + var readErrors []string + for _, address := range h.oneFilerPerStore(ctx, filers, sender) { + client := &adminFilerClient{address: address, grpcDialOption: h.grpcDialOption} + fc, err := filer.ReadFilerConfFromClient(ctx, client, client) + if err != nil { + readErrors = append(readErrors, fmt.Sprintf("filer %s: %v", address, err)) + continue + } + rules := ttlRules(fc) + if len(rules) == 0 { + continue + } + proposals = append(proposals, &plugin_pb.JobProposal{ + JobType: jobType, + ProposalId: fmt.Sprintf("filer-ttl-%s-%d", address, time.Now().UnixNano()), + DedupeKey: fmt.Sprintf("%s:%s", jobType, address), + Priority: plugin_pb.JobPriority_JOB_PRIORITY_LOW, + Summary: fmt.Sprintf("Expire entries under %d TTL path(s) on the store of filer %s", len(rules), address), + Parameters: map[string]*plugin_pb.ConfigValue{ + filerAddressParam: {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: string(address)}}, + }, + }) + } + if len(proposals) > 0 { + if err := sender.SendProposals(&plugin_pb.DetectionProposals{JobType: jobType, Proposals: proposals}); err != nil { + return err + } + } + return sender.SendComplete(&plugin_pb.DetectionComplete{ + JobType: jobType, + Success: len(readErrors) == 0, + ErrorMessage: strings.Join(readErrors, "; "), + TotalProposals: int32(len(proposals)), + }) +} + +// adminFilerClient reaches one filer with the admin token, so filer.conf is +// read from that filer's own store, including a chunk-backed one. +type adminFilerClient struct { + address pb.ServerAddress + grpcDialOption grpc.DialOption +} + +func (c *adminFilerClient) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { + return pb.WithGrpcFilerClient(streamingMode, 0, c.address, c.grpcDialOption, security.FilerAdminToken, fn) +} + +func (c *adminFilerClient) AdjustedUrl(location *filer_pb.Location) string { return location.Url } + +func (c *adminFilerClient) GetDataCenter() string { return "" } + +func (c *adminFilerClient) GetLookupFileIdFunction() wdclient.LookupFileIdFunctionType { + return filer.LookupFn(c) +} + +// oneFilerPerStore keeps the first reachable filer of each store signature: +// filers sharing a store share its rows, and a filer with its own store has +// rows no other filer's job removes. +func (h *Handler) oneFilerPerStore(ctx context.Context, filers []pb.ServerAddress, sender pluginworker.DetectionSender) []pb.ServerAddress { + seen := make(map[int32]bool) + var picked []pb.ServerAddress + for _, address := range filers { + var signature int32 + err := pb.WithGrpcFilerClient(false, 0, address, h.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { + resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{}) + if err != nil { + return err + } + signature = resp.Signature + return nil + }) + if err != nil { + _ = sender.SendActivity(pluginworker.BuildDetectorActivity("filer_unreachable", fmt.Sprintf("filer %s: %v", address, err), nil)) + continue + } + if seen[signature] { + continue + } + seen[signature] = true + picked = append(picked, address) + } + return picked +} + +func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequest, sender pluginworker.ExecutionSender) error { + if request == nil || request.Job == nil || sender == nil { + return fmt.Errorf("execute: nil request/job/sender") + } + if request.Job.JobType != "" && request.Job.JobType != jobType { + return fmt.Errorf("job type %q is not handled by filer ttl handler", request.Job.JobType) + } + address := pluginworker.ReadStringConfig(request.Job.Parameters, filerAddressParam, "") + if address == "" { + return fmt.Errorf("execute: missing %s in job parameters", filerAddressParam) + } + client := &adminFilerClient{address: pb.ServerAddress(address), grpcDialOption: h.grpcDialOption} + + _ = sender.SendProgress(&plugin_pb.JobProgressUpdate{ + JobId: request.Job.JobId, JobType: jobType, + State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "replaying", + Message: fmt.Sprintf("filer %s", address), + }) + + stats := &runStats{} + var rules []ttlRule + fc, err := filer.ReadFilerConfFromClient(ctx, client, client) + if err == nil { + rules = ttlRules(fc) + err = client.WithFilerClient(true, func(c filer_pb.SeaweedFilerClient) error { + return expireByEvents(ctx, c, rules, stats) + }) + } + + summary := fmt.Sprintf("filer %s: %d TTL path(s), %d events, %d expired entries looked up, %d still waiting", address, len(rules), stats.events, stats.expired, stats.pending) + if stats.directories > 0 { + summary += fmt.Sprintf(", listed %d directories and %d live entries", stats.directories, stats.entries) + } + completed := &plugin_pb.JobCompleted{ + JobId: request.Job.JobId, + JobType: jobType, + Success: err == nil, + Result: &plugin_pb.JobResult{ + Summary: summary, + OutputValues: map[string]*plugin_pb.ConfigValue{ + "events": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.events}}, + "expired": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.expired}}, + "pending": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.pending}}, + "directories": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.directories}}, + "entries": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.entries}}, + }, + }, + } + if err != nil { + completed.ErrorMessage = err.Error() + } + return sender.SendCompleted(completed) +} diff --git a/weed/worker/tasks/filer_ttl/handler_test.go b/weed/worker/tasks/filer_ttl/handler_test.go new file mode 100644 index 0000000000..1d6b9c37db --- /dev/null +++ b/weed/worker/tasks/filer_ttl/handler_test.go @@ -0,0 +1,899 @@ +package filer_ttl + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "net/http/httptest" + "sort" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/util" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// ttlFiler behaves like a filer on a store without native TTL: an expired +// row stays until a lookup or a listing reaches it, and then it is deleted. +type ttlFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + signature int32 + conf []byte + volumeUrl string + mu sync.Mutex + dirs map[string]map[string]*filer_pb.Entry + events []*filer_pb.SubscribeMetadataResponse + lastTsNs int64 + lists map[string]int + lookups map[string]int + failLookup string + clockLag time.Duration + subscriptions []*filer_pb.SubscribeMetadataRequest +} + +// newTTLFiler keeps metadata logs from 2000 on. +func newTTLFiler(signature int32) *ttlFiler { + f := &ttlFiler{signature: signature, dirs: map[string]map[string]*filer_pb.Entry{}, lists: map[string]int{}, lookups: map[string]int{}} + f.keepLogsFrom(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)) + return f +} + +// keepLogsFrom stands for the persisted metadata logs, the oldest one +// starting at the minute of start. +func (f *ttlFiler) keepLogsFrom(start time.Time) { + f.mu.Lock() + defer f.mu.Unlock() + delete(f.dirs, filer.SystemLogDir) + for dir := range f.dirs { + if strings.HasPrefix(dir, filer.SystemLogDir+"/") { + delete(f.dirs, dir) + } + } + start = start.UTC() + day := filer.SystemLogDir + "/" + start.Format("2006-01-02") + f.put(day, &filer_pb.Entry{IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}}) + f.put(day+"/"+start.Format("15-04")+".0000000a", &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}}) + f.put(day+"/23-59.0000000a", &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}}) +} + +// gone reports whether the filer, whose clock trails by clockLag, treats the +// entry as expired. +func (f *ttlFiler) gone(entry *filer_pb.Entry) bool { + attr := entry.GetAttributes() + return !entry.IsDirectory && attr.GetTtlSec() > 0 && time.Unix(attr.Crtime, 0).Add(time.Duration(attr.TtlSec)*time.Second).Before(time.Now().Add(-f.clockLag)) +} + +func (f *ttlFiler) put(fullPath string, entry *filer_pb.Entry) { + dir, name := util.FullPath(fullPath).DirAndName() + entry.Name = name + if f.dirs[dir] == nil { + f.dirs[dir] = map[string]*filer_pb.Entry{} + } + f.dirs[dir][name] = entry +} + +func (f *ttlFiler) row(fullPath string) *filer_pb.Entry { + f.mu.Lock() + defer f.mu.Unlock() + dir, name := util.FullPath(fullPath).DirAndName() + return f.dirs[dir][name] +} + +// add stores a row that no replayed event names. +func (f *ttlFiler) add(fullPath string, isDirectory bool, crtime time.Time, ttlSec int32) { + f.mu.Lock() + defer f.mu.Unlock() + f.put(fullPath, &filer_pb.Entry{IsDirectory: isDirectory, Attributes: &filer_pb.FuseAttributes{Crtime: crtime.Unix(), TtlSec: ttlSec}}) +} + +// write stores a file and logs its create event. +func (f *ttlFiler) write(fullPath string, crtime time.Time, ttlSec int32) *filer_pb.SubscribeMetadataResponse { + tsNs := time.Now().UnixNano() + f.mu.Lock() + if tsNs <= f.lastTsNs { + tsNs = f.lastTsNs + 1 + } + f.mu.Unlock() + return f.writeAt(tsNs, fullPath, crtime, ttlSec) +} + +func (f *ttlFiler) writeAt(tsNs int64, fullPath string, crtime time.Time, ttlSec int32) *filer_pb.SubscribeMetadataResponse { + f.mu.Lock() + defer f.mu.Unlock() + entry := &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{Crtime: crtime.Unix(), TtlSec: ttlSec}} + f.put(fullPath, entry) + dir, _ := util.FullPath(fullPath).DirAndName() + event := &filer_pb.SubscribeMetadataResponse{Directory: dir, TsNs: tsNs, EventNotification: &filer_pb.EventNotification{NewEntry: proto.Clone(entry).(*filer_pb.Entry)}} + f.events = append(f.events, event) + f.lastTsNs = tsNs + return event +} + +func (f *ttlFiler) remove(fullPath string) *filer_pb.SubscribeMetadataResponse { + f.mu.Lock() + defer f.mu.Unlock() + dir, name := util.FullPath(fullPath).DirAndName() + old := f.dirs[dir][name] + delete(f.dirs[dir], name) + f.lastTsNs = max(f.lastTsNs+1, time.Now().UnixNano()) + event := &filer_pb.SubscribeMetadataResponse{Directory: dir, TsNs: f.lastTsNs, EventNotification: &filer_pb.EventNotification{OldEntry: old}} + f.events = append(f.events, event) + return event +} + +func (f *ttlFiler) cursors() map[string]ruleCursor { + f.mu.Lock() + defer f.mu.Unlock() + entry := f.dirs[cursorDir][cursorName(f.signature)] + if entry == nil { + return nil + } + var saved savedCursors + if err := json.Unmarshal(entry.Content, &saved); err != nil { + return nil + } + return saved.Rules +} + +func (f *ttlFiler) saveCursors(t *testing.T, cursors map[string]ruleCursor) { + t.Helper() + content, err := json.Marshal(savedCursors{Rules: cursors}) + if err != nil { + t.Fatal(err) + } + f.mu.Lock() + defer f.mu.Unlock() + f.put(cursorDir+"/"+cursorName(f.signature), &filer_pb.Entry{Content: content, Attributes: &filer_pb.FuseAttributes{}}) +} + +func (f *ttlFiler) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.put(req.Directory+"/"+req.Entry.Name, proto.Clone(req.Entry).(*filer_pb.Entry)) + return &filer_pb.CreateEntryResponse{}, nil +} + +func (f *ttlFiler) UpdateEntry(_ context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.put(req.Directory+"/"+req.Entry.Name, proto.Clone(req.Entry).(*filer_pb.Entry)) + return &filer_pb.UpdateEntryResponse{}, nil +} + +func (f *ttlFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) { + return &filer_pb.GetFilerConfigurationResponse{Signature: f.signature}, nil +} + +func (f *ttlFiler) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + fullPath := req.Directory + "/" + req.Name + if req.Directory == filer.DirectoryEtcSeaweedFS && req.Name == filer.FilerConfName && f.conf != nil { + if f.volumeUrl != "" { + return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{ + Name: req.Name, + Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(f.conf))}, + Chunks: []*filer_pb.FileChunk{{FileId: "3,01637037d6", Size: uint64(len(f.conf))}}, + }}, nil + } + return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{Name: req.Name, Content: f.conf}}, nil + } + f.mu.Lock() + defer f.mu.Unlock() + f.lookups[fullPath]++ + if fullPath == f.failLookup { + return nil, status.Error(codes.Unavailable, "store unavailable") + } + entry := f.dirs[req.Directory][req.Name] + if entry == nil { + return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error()) + } + if f.gone(entry) { + delete(f.dirs[req.Directory], req.Name) + return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error()) + } + return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}, nil +} + +func (f *ttlFiler) LookupVolume(_ context.Context, req *filer_pb.LookupVolumeRequest) (*filer_pb.LookupVolumeResponse, error) { + resp := &filer_pb.LookupVolumeResponse{LocationsMap: map[string]*filer_pb.Locations{}} + for _, vid := range req.VolumeIds { + resp.LocationsMap[vid] = &filer_pb.Locations{Locations: []*filer_pb.Location{{Url: f.volumeUrl}}} + } + return resp, nil +} + +func (f *ttlFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error { + dir := strings.TrimSuffix(req.Directory, "/") + if dir == "" { + dir = "/" + } + f.mu.Lock() + if req.StartFromFileName == "" && !strings.HasPrefix(dir, filer.SystemLogDir) { + f.lists[dir]++ + } + var names []string + for name := range f.dirs[dir] { + if strings.HasPrefix(name, req.Prefix) && name > req.StartFromFileName { + names = append(names, name) + } + } + sort.Strings(names) + var page []*filer_pb.Entry + for _, name := range names { + if uint32(len(page)) >= req.Limit { + break + } + if f.gone(f.dirs[dir][name]) { + delete(f.dirs[dir], name) + continue + } + page = append(page, proto.Clone(f.dirs[dir][name]).(*filer_pb.Entry)) + } + f.mu.Unlock() + for _, entry := range page { + if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil { + return err + } + } + return nil +} + +// SubscribeMetadata sends the logged events of a bounded subscription two +// per response, the second one batched. +func (f *ttlFiler) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeMetadataServer) error { + f.mu.Lock() + f.subscriptions = append(f.subscriptions, req) + var matched []*filer_pb.SubscribeMetadataResponse + for _, event := range f.events { + if event.TsNs <= req.SinceNs || (req.UntilNs != 0 && event.TsNs > req.UntilNs) { + continue + } + n := event.EventNotification + var paths []string + if n.OldEntry != nil { + paths = append(paths, event.Directory+"/"+n.OldEntry.Name) + } + if n.NewEntry != nil { + dir := n.NewParentPath + if dir == "" { + dir = event.Directory + } + paths = append(paths, dir+"/"+n.NewEntry.Name) + } + for _, p := range paths { + if strings.HasPrefix(p, req.PathPrefix) { + matched = append(matched, proto.Clone(event).(*filer_pb.SubscribeMetadataResponse)) + break + } + } + } + f.mu.Unlock() + for i := 0; i < len(matched); i += 2 { + resp := matched[i] + if i+1 < len(matched) { + resp.Events = matched[i+1 : i+2] + } + if err := stream.Send(resp); err != nil { + return err + } + } + return nil +} + +func serveFiler(t *testing.T, f *ttlFiler) string { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + s := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(s, f) + go s.Serve(lis) + t.Cleanup(s.Stop) + host, port, _ := net.SplitHostPort(lis.Addr().String()) + return fmt.Sprintf("%s:1.%s", host, port) +} + +func filerConf(t *testing.T, rules ...*filer_pb.FilerConf_PathConf) []byte { + t.Helper() + fc := filer.NewFilerConf() + for _, rule := range rules { + if err := fc.SetLocationConf(rule); err != nil { + t.Fatal(err) + } + } + var buf strings.Builder + if err := fc.ToText(&buf); err != nil { + t.Fatal(err) + } + return []byte(buf.String()) +} + +type detectRecorder struct { + proposals []*plugin_pb.JobProposal + completes []*plugin_pb.DetectionComplete +} + +func (r *detectRecorder) SendProposals(p *plugin_pb.DetectionProposals) error { + r.proposals = append(r.proposals, p.Proposals...) + return nil +} +func (r *detectRecorder) SendComplete(c *plugin_pb.DetectionComplete) error { + r.completes = append(r.completes, c) + return nil +} +func (r *detectRecorder) SendActivity(*plugin_pb.ActivityEvent) error { return nil } + +type executeRecorder struct { + completed []*plugin_pb.JobCompleted +} + +func (r *executeRecorder) SendProgress(*plugin_pb.JobProgressUpdate) error { return nil } +func (r *executeRecorder) SendCompleted(c *plugin_pb.JobCompleted) error { + r.completed = append(r.completed, c) + return nil +} + +func newTestHandler() *Handler { + return NewHandler(grpc.WithTransportCredentials(insecure.NewCredentials())) +} + +func executeOn(t *testing.T, address string) *plugin_pb.JobCompleted { + t.Helper() + sender := &executeRecorder{} + if err := newTestHandler().Execute(context.Background(), &plugin_pb.ExecuteJobRequest{Job: &plugin_pb.JobSpec{ + JobType: jobType, + Parameters: map[string]*plugin_pb.ConfigValue{ + filerAddressParam: {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: address}}, + }, + }}, sender); err != nil { + t.Fatal(err) + } + if len(sender.completed) != 1 { + t.Fatalf("completed = %v", sender.completed) + } + return sender.completed[0] +} + +func TestTTLRulesOwnerAndOutermost(t *testing.T) { + fc := filer.NewFilerConf() + for _, rule := range []*filer_pb.FilerConf_PathConf{ + {LocationPrefix: "/buckets/logs/", Ttl: "7d"}, + {LocationPrefix: "/buckets/logs/debug/", Ttl: "1d"}, + {LocationPrefix: "/buckets/archive/", Replication: "001"}, + {LocationPrefix: "/tmp", Ttl: "1h"}, + } { + if err := fc.SetLocationConf(rule); err != nil { + t.Fatal(err) + } + } + rules := ttlRules(fc) + if got := fmt.Sprint(rules); got != "[{/buckets/logs/ 604800} {/buckets/logs/debug/ 86400} {/tmp 3600}]" { + t.Fatalf("rules = %s", got) + } + for path, want := range map[string]string{ + "/buckets/logs/a.log": "/buckets/logs/", + "/buckets/logs/debug/a.log": "/buckets/logs/debug/", + "/buckets/logs/debugging.log": "/buckets/logs/", + "/tmp-cache/x": "/tmp", + "/buckets/archive/x": "", + } { + if got := owner(rules, path); got != want { + t.Fatalf("owner(%s) = %q, want %q", path, got, want) + } + } + if got := fmt.Sprint(outermost([]string{"/buckets/logs/", "/buckets/logs/debug/", "/tmp"})); got != "[/buckets/logs/ /tmp]" { + t.Fatalf("outermost = %s", got) + } +} + +func TestDetectProposesOneJobPerStore(t *testing.T) { + conf := filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "11d"}) + shared1, shared2, own := newTTLFiler(7), newTTLFiler(7), newTTLFiler(9) + for _, f := range []*ttlFiler{shared1, shared2, own} { + f.conf = conf + } + addresses := []string{serveFiler(t, shared1), serveFiler(t, shared2), serveFiler(t, own)} + + sender := &detectRecorder{} + err := newTestHandler().Detect(context.Background(), &plugin_pb.RunDetectionRequest{ + JobType: jobType, + ClusterContext: &plugin_pb.ClusterContext{FilerAddresses: addresses}, + }, sender) + if err != nil { + t.Fatal(err) + } + var got []string + for _, p := range sender.proposals { + got = append(got, p.Parameters[filerAddressParam].GetStringValue()) + } + if want := []string{addresses[0], addresses[2]}; fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("proposed filers = %v, want %v", got, want) + } +} + +func TestDetectReadsEachStoresOwnFilerConf(t *testing.T) { + plain, clips := newTTLFiler(1), newTTLFiler(2) + plain.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/a/", Replication: "001"}) + clips.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/clips/", Ttl: "1d"}) + volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Write(clips.conf) + })) + t.Cleanup(volume.Close) + clips.volumeUrl = strings.TrimPrefix(volume.URL, "http://") + addresses := []string{serveFiler(t, plain), serveFiler(t, clips)} + + sender := &detectRecorder{} + err := newTestHandler().Detect(context.Background(), &plugin_pb.RunDetectionRequest{ + JobType: jobType, + ClusterContext: &plugin_pb.ClusterContext{FilerAddresses: addresses}, + }, sender) + if err != nil { + t.Fatal(err) + } + if len(sender.proposals) != 1 { + t.Fatalf("proposals = %d, want 1", len(sender.proposals)) + } + if got := sender.proposals[0].Parameters[filerAddressParam].GetStringValue(); got != addresses[1] { + t.Fatalf("proposed filer = %s, want %s", got, addresses[1]) + } +} + +func TestDetectWithoutTTLRulesProposesNothing(t *testing.T) { + f := newTTLFiler(1) + f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/a/", Replication: "001"}) + sender := &detectRecorder{} + err := newTestHandler().Detect(context.Background(), &plugin_pb.RunDetectionRequest{ + JobType: jobType, + ClusterContext: &plugin_pb.ClusterContext{FilerAddresses: []string{serveFiler(t, f)}}, + }, sender) + if err != nil { + t.Fatal(err) + } + if len(sender.proposals) != 0 || len(sender.completes) != 1 || !sender.completes[0].Success { + t.Fatalf("proposals=%d completes=%v", len(sender.proposals), sender.completes) + } +} + +func TestExecuteListsANewRuleOnceThenReplaysItsEvents(t *testing.T) { + now := time.Now() + f := newTTLFiler(1) + f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "1h"}) + f.add("/buckets/cam/2026-11-01", true, now, 0) + for i := 0; i < 2*walkPageSize+10; i++ { + f.add(fmt.Sprintf("/buckets/cam/2026-11-01/clip-%05d.mp4", i), false, now.Add(-2*time.Hour), 3600) + } + f.add("/buckets/cam/2026-11-01/live.mp4", false, now, 3600) + f.add("/keep", true, now, 0) + f.add("/keep/old.bin", false, now.Add(-2*time.Hour), 3600) + address := serveFiler(t, f) + + if c := executeOn(t, address); !c.Success { + t.Fatalf("first run: %s", c.ErrorMessage) + } + if n := len(f.dirs["/buckets/cam/2026-11-01"]); n != 1 || f.row("/buckets/cam/2026-11-01/live.mp4") == nil { + t.Fatalf("rows left under the TTL path = %d, want only the live one", n) + } + if f.row("/keep/old.bin") == nil { + t.Fatal("an entry outside every TTL path was removed") + } + c := f.cursors()["/buckets/cam/"] + if c.TtlSec != 3600 || c.TsNs < now.Add(-time.Hour-time.Minute).UnixNano() || c.TsNs > now.Add(-time.Hour+time.Minute).UnixNano() { + t.Fatalf("cursor = %+v, want ttl 3600 at about an hour ago", c) + } + + old := f.write("/buckets/cam/2026-11-02/rewritten.mp4", now.Add(-2*time.Hour), 3600) + if c := executeOn(t, address); !c.Success { + t.Fatalf("second run: %s", c.ErrorMessage) + } + if got := f.lists["/buckets/cam"]; got != 1 { + t.Fatalf("TTL path listed %d times, want once", got) + } + if f.row("/buckets/cam/2026-11-02/rewritten.mp4") != nil { + t.Fatal("the expired entry of a replayed event is still stored") + } + if got := f.cursors()["/buckets/cam/"].TsNs; got != old.TsNs { + t.Fatalf("cursor = %d, want the last event %d", got, old.TsNs) + } +} + +func TestExecuteHoldsTheCursorAtTheFirstEntryNotYetDue(t *testing.T) { + now := time.Now() + f := newTTLFiler(1) + f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1h"}) + f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}}) + a := f.write("/logs/a.log", now.Add(-2*time.Hour), 3600) + b := f.write("/logs/b.log", now, 3600) + f.write("/logs/c.log", now.Add(-3*time.Hour), 3600) + f.write("/logs/outside-ttl.log", now.Add(-3*time.Hour), 0) + f.write("/logs/d.log", now.Add(-3*time.Hour), 3600) + last := f.remove("/logs/d.log") + address := serveFiler(t, f) + + if c := executeOn(t, address); !c.Success { + t.Fatalf("first run: %s", c.ErrorMessage) + } + if f.row("/logs/a.log") != nil || f.row("/logs/c.log") != nil { + t.Fatal("an entry whose TTL passed is still stored") + } + if f.row("/logs/b.log") == nil || f.lookups["/logs/b.log"] != 0 { + t.Fatal("an entry not yet due was looked up") + } + if f.row("/logs/outside-ttl.log") == nil { + t.Fatal("an entry without a TTL was removed") + } + if len(f.lists) != 0 { + t.Fatalf("a rule with a cursor was listed: %v", f.lists) + } + if got := f.cursors()["/logs/"].TsNs; got != a.TsNs { + t.Fatalf("cursor = %d, want the event before the waiting entry %d", got, a.TsNs) + } + + f.mu.Lock() + b.EventNotification.NewEntry.Attributes.Crtime = now.Add(-2 * time.Hour).Unix() + f.dirs["/logs"]["b.log"].Attributes.Crtime = now.Add(-2 * time.Hour).Unix() + f.mu.Unlock() + if c := executeOn(t, address); !c.Success { + t.Fatalf("second run: %s", c.ErrorMessage) + } + if f.row("/logs/b.log") != nil { + t.Fatal("the held entry was not removed once its TTL passed") + } + if got := f.subscriptions[1].SinceNs; got != a.TsNs { + t.Fatalf("second run subscribed from %d, want %d", got, a.TsNs) + } + if got := f.cursors()["/logs/"].TsNs; got != last.TsNs { + t.Fatalf("cursor = %d, want the last event %d", got, last.TsNs) + } +} + +func TestExecuteLeavesS3LifecycleExpiryToTheLifecycleJob(t *testing.T) { + now := time.Now() + f := newTTLFiler(1) + f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "1h"}) + f.saveCursors(t, map[string]ruleCursor{"/buckets/cam/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}}) + lifecycle := func(fullPath string, mtime time.Time, ttlSec int32) { + event := f.write(fullPath, mtime, ttlSec) + f.mu.Lock() + defer f.mu.Unlock() + for _, entry := range []*filer_pb.Entry{event.EventNotification.NewEntry, f.dirs[event.Directory][event.EventNotification.NewEntry.Name]} { + entry.Attributes.Mtime = mtime.Unix() + entry.Extended = map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")} + } + } + lifecycle("/buckets/cam/kept-a-year.mp4", now, 365*24*3600) + lifecycle("/buckets/cam/lifecycle-expired.mp4", now.Add(-2*time.Hour), 3600) + last := f.write("/buckets/cam/path-ttl.mp4", now.Add(-2*time.Hour), 3600) + address := serveFiler(t, f) + + if c := executeOn(t, address); !c.Success { + t.Fatalf("run: %s", c.ErrorMessage) + } + if f.row("/buckets/cam/path-ttl.mp4") != nil { + t.Fatal("an entry past its path TTL is still stored") + } + if n := f.lookups["/buckets/cam/kept-a-year.mp4"] + f.lookups["/buckets/cam/lifecycle-expired.mp4"]; n != 0 { + t.Fatalf("entries with an S3 lifecycle expiry were looked up %d times", n) + } + if got := f.cursors()["/buckets/cam/"].TsNs; got != last.TsNs { + t.Fatalf("cursor = %d, want the last event %d: an S3 lifecycle expiry held it", got, last.TsNs) + } +} + +func TestExecuteHoldsTheCursorBelowATieWithAWaitingEntry(t *testing.T) { + now := time.Now() + f := newTTLFiler(1) + f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1h"}) + f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}}) + tsNs := now.UnixNano() + f.writeAt(tsNs, "/logs/a.log", now.Add(-2*time.Hour), 3600) + f.writeAt(tsNs, "/logs/b.log", now, 3600) + + if c := executeOn(t, serveFiler(t, f)); !c.Success { + t.Fatal(c.ErrorMessage) + } + if got := f.cursors()["/logs/"].TsNs; got != tsNs-1 { + t.Fatalf("cursor = %d, want %d so the waiting event is replayed", got, tsNs-1) + } +} + +func TestExecuteLeavesANestedRulesEntriesToThatRule(t *testing.T) { + now := time.Now() + f := newTTLFiler(1) + f.conf = filerConf(t, + &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1d"}, + &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/debug/", Ttl: "1h"}) + f.saveCursors(t, map[string]ruleCursor{ + "/logs/": {TtlSec: 86400, TsNs: now.Add(-24 * time.Hour).UnixNano()}, + "/logs/debug/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}, + }) + f.write("/logs/debug/trace.log", now.Add(-2*time.Hour), 3600) + f.write("/logs/app.log", now.Add(-2*time.Hour), 86400) + + if c := executeOn(t, serveFiler(t, f)); !c.Success { + t.Fatal(c.ErrorMessage) + } + if f.row("/logs/debug/trace.log") != nil || f.lookups["/logs/debug/trace.log"] != 1 { + t.Fatalf("nested rule entry: stored=%v lookups=%d, want removed by one lookup", f.row("/logs/debug/trace.log") != nil, f.lookups["/logs/debug/trace.log"]) + } + if f.row("/logs/app.log") == nil { + t.Fatal("an entry not yet due was removed") + } + var prefixes []string + for _, s := range f.subscriptions { + prefixes = append(prefixes, s.PathPrefix) + } + if fmt.Sprint(prefixes) != "[/logs/ /logs/debug/]" { + t.Fatalf("subscriptions = %v, want one per TTL rule", prefixes) + } +} + +func TestExecuteListsARuleAgainWhenItsTTLChanged(t *testing.T) { + now := time.Now() + f := newTTLFiler(1) + f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1h"}) + f.saveCursors(t, map[string]ruleCursor{ + "/logs/": {TtlSec: 7200, TsNs: now.Add(-time.Hour).UnixNano()}, + "/old/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}, + }) + f.add("/logs/stale.log", false, now.Add(-90*time.Minute), 3600) + + if c := executeOn(t, serveFiler(t, f)); !c.Success { + t.Fatal(c.ErrorMessage) + } + if f.lists["/logs"] != 1 || f.row("/logs/stale.log") != nil { + t.Fatalf("lists=%v stale stored=%v, want the TTL path listed once", f.lists, f.row("/logs/stale.log") != nil) + } + cursors := f.cursors() + if _, found := cursors["/old/"]; found { + t.Fatal("the cursor of a removed rule was kept") + } + c := cursors["/logs/"] + if c.TtlSec != 3600 || c.TsNs > now.Add(-2*time.Hour+time.Minute).UnixNano() { + t.Fatalf("cursor = %+v, want ttl 3600 starting two hours back, the longer of both TTLs", c) + } +} + +func TestExecuteStopsAtAFailedLookupAndKeepsItsEvent(t *testing.T) { + now := time.Now() + f := newTTLFiler(1) + f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1h"}) + f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}}) + a := f.write("/logs/a.log", now.Add(-2*time.Hour), 3600) + f.write("/logs/b.log", now.Add(-2*time.Hour), 3600) + c := f.write("/logs/c.log", now.Add(-2*time.Hour), 3600) + f.failLookup = "/logs/b.log" + address := serveFiler(t, f) + + if completed := executeOn(t, address); completed.Success || !strings.Contains(completed.ErrorMessage, "/logs/b.log") { + t.Fatalf("completed = %+v, want a failure naming the lookup", completed) + } + if got := f.cursors()["/logs/"].TsNs; got != a.TsNs { + t.Fatalf("cursor = %d, want %d before the failed lookup", got, a.TsNs) + } + f.mu.Lock() + f.failLookup = "" + f.mu.Unlock() + if completed := executeOn(t, address); !completed.Success { + t.Fatal(completed.ErrorMessage) + } + if f.row("/logs/b.log") != nil || f.row("/logs/c.log") != nil { + t.Fatal("entries after the failed lookup were not removed on the next run") + } + if got := f.cursors()["/logs/"].TsNs; got != c.TsNs { + t.Fatalf("cursor = %d, want %d", got, c.TsNs) + } +} + +func TestExecuteKeepsAFailedLookupThatTiesADoneEvent(t *testing.T) { + now := time.Now() + f := newTTLFiler(1) + f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1h"}) + f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}}) + tsNs := now.UnixNano() + f.writeAt(tsNs, "/logs/a.log", now.Add(-2*time.Hour), 3600) + f.writeAt(tsNs, "/logs/b.log", now.Add(-2*time.Hour), 3600) + f.failLookup = "/logs/b.log" + address := serveFiler(t, f) + + if completed := executeOn(t, address); completed.Success { + t.Fatal("a failed lookup reported success") + } + if got := f.cursors()["/logs/"].TsNs; got != tsNs-1 { + t.Fatalf("cursor = %d, want %d so the failed event is replayed", got, tsNs-1) + } + f.mu.Lock() + f.failLookup = "" + f.mu.Unlock() + if completed := executeOn(t, address); !completed.Success { + t.Fatal(completed.ErrorMessage) + } + if f.row("/logs/b.log") != nil { + t.Fatal("the entry of the failed lookup was not removed on the next run") + } +} + +func TestExecuteHoldsAnEntryTheFilerStillServes(t *testing.T) { + now := time.Now() + f := newTTLFiler(1) + f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1h"}) + f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: 3600, TsNs: now.Add(-2 * time.Hour).UnixNano()}}) + first := f.write("/logs/a.log", now.Add(-2*time.Hour), 3600) + f.write("/logs/b.log", now.Add(-61*time.Minute), 3600) + f.clockLag = 5 * time.Minute + address := serveFiler(t, f) + + if completed := executeOn(t, address); !completed.Success { + t.Fatal(completed.ErrorMessage) + } + if f.row("/logs/a.log") != nil || f.row("/logs/b.log") == nil { + t.Fatal("want the entry due on both clocks removed and the other one kept") + } + if got := f.cursors()["/logs/"].TsNs; got != first.TsNs { + t.Fatalf("cursor = %d, want %d before the entry the filer still serves", got, first.TsNs) + } + f.mu.Lock() + f.clockLag = 0 + f.mu.Unlock() + if completed := executeOn(t, address); !completed.Success { + t.Fatal(completed.ErrorMessage) + } + if f.row("/logs/b.log") != nil { + t.Fatal("the held entry was not removed once the filer saw it expire") + } +} + +func TestExecuteKeepsAPathTTLOffTheCursors(t *testing.T) { + for _, covered := range []bool{false, true} { + f := newTTLFiler(1) + rules := []*filer_pb.FilerConf_PathConf{{LocationPrefix: "/logs/", Ttl: "1h"}} + if covered { + rules = append(rules, &filer_pb.FilerConf_PathConf{LocationPrefix: "/etc/", Ttl: "1h"}) + } + f.conf = filerConf(t, rules...) + if completed := executeOn(t, serveFiler(t, f)); !completed.Success { + t.Fatal(completed.ErrorMessage) + } + row := f.row(cursorDir + "/" + cursorName(1)) + if row == nil { + t.Fatal("cursors not saved") + } + want := int32(0) + if covered { + want = int32(cursorTTL / time.Second) + } + if got := row.Attributes.TtlSec; got != want { + t.Fatalf("covered=%v: cursor TTL = %d, want %d", covered, got, want) + } + } +} + +func TestExecuteListsANewNestedRuleAgainAtAnOlderEntrysDeadline(t *testing.T) { + now := time.Now() + f := newTTLFiler(1) + f.conf = filerConf(t, + &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "7d"}, + &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/debug/", Ttl: "1h"}) + f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: 7 * 86400, TsNs: now.Add(-7 * 24 * time.Hour).UnixNano()}}) + written := now.Add(-3 * 24 * time.Hour) + f.writeAt(written.UnixNano(), "/logs/debug/trace.log", written, 7*86400) + address := serveFiler(t, f) + + if completed := executeOn(t, address); !completed.Success { + t.Fatal(completed.ErrorMessage) + } + deadline := written.Add(7 * 24 * time.Hour) + if got := f.cursors()["/logs/debug/"].WalkAtNs; got != time.Unix(deadline.Unix(), 0).UnixNano() { + t.Fatalf("nested rule lists again at %d, want the entry's deadline %d", got, deadline.UnixNano()) + } + if got := f.cursors()["/logs/"].WalkAtNs; got != 0 { + t.Fatalf("enclosing rule lists again at %d, want never", got) + } + + cursors := f.cursors() + c := cursors["/logs/debug/"] + c.WalkAtNs = now.UnixNano() + cursors["/logs/debug/"] = c + f.saveCursors(t, cursors) + f.mu.Lock() + f.dirs["/logs/debug"]["trace.log"].Attributes.Crtime = now.Add(-8 * 24 * time.Hour).Unix() + f.mu.Unlock() + if completed := executeOn(t, address); !completed.Success { + t.Fatal(completed.ErrorMessage) + } + if f.row("/logs/debug/trace.log") != nil || f.lists["/logs/debug"] != 2 { + t.Fatalf("stored=%v lists=%v, want the nested rule listed again and the entry removed", f.row("/logs/debug/trace.log") != nil, f.lists) + } + if got := f.cursors()["/logs/debug/"].WalkAtNs; got != 0 { + t.Fatalf("nested rule lists again at %d after the entry went", got) + } +} + +func TestExecuteHandsARemovedNestedRulesReplayToTheEnclosingRule(t *testing.T) { + now := time.Now() + f := newTTLFiler(1) + f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1d"}) + f.saveCursors(t, map[string]ruleCursor{ + "/logs/": {TtlSec: 86400, TsNs: now.Add(-time.Minute).UnixNano()}, + "/logs/debug/": {TtlSec: 3600, TsNs: now.Add(-2 * time.Hour).UnixNano()}, + }) + f.writeAt(now.Add(-90*time.Minute).UnixNano(), "/logs/debug/trace.log", now.Add(-90*time.Minute), 3600) + + if completed := executeOn(t, serveFiler(t, f)); !completed.Success { + t.Fatal(completed.ErrorMessage) + } + if f.row("/logs/debug/trace.log") != nil { + t.Fatal("an expired entry of the removed rule was left behind the enclosing rule's cursor") + } + if _, found := f.cursors()["/logs/debug/"]; found { + t.Fatal("the cursor of the removed rule was kept") + } +} + +func TestExecuteListsARuleWhoseUnfinishedEventsAreNoLongerLogged(t *testing.T) { + now := time.Now() + week := int32(7 * 86400) + f := newTTLFiler(1) + f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "7d"}) + held := now.Add(-3 * 24 * time.Hour) + f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: week, TsNs: held.UnixNano()}}) + f.add("/logs/expired.log", false, now.Add(-8*24*time.Hour), week) + f.add("/logs/live.log", false, held, week) + logStart := now.Add(-24 * time.Hour) + f.keepLogsFrom(logStart) + address := serveFiler(t, f) + + if completed := executeOn(t, address); !completed.Success { + t.Fatal(completed.ErrorMessage) + } + if f.lists["/logs"] != 1 || f.row("/logs/expired.log") != nil || f.row("/logs/live.log") == nil { + t.Fatalf("lists=%v, want the rule listed once, the expired row removed and the live one kept", f.lists) + } + c := f.cursors()["/logs/"] + if oldest := logStart.UTC().Truncate(time.Minute); c.TsNs != oldest.UnixNano()-1 { + t.Fatalf("cursor = %d, want just before the oldest log %d", c.TsNs, oldest.UnixNano()) + } + if want := time.Unix(held.Unix(), 0).Add(7 * 24 * time.Hour).UnixNano(); c.WalkAtNs != want { + t.Fatalf("lists again at %d, want the live entry's deadline %d", c.WalkAtNs, want) + } + + if completed := executeOn(t, address); !completed.Success { + t.Fatal(completed.ErrorMessage) + } + if f.lists["/logs"] != 1 { + t.Fatalf("lists=%v, want no second listing before that deadline", f.lists) + } +} + +func TestExecuteDoesNotListAQuietRuleAfterOldLogsArePurged(t *testing.T) { + now := time.Now() + f := newTTLFiler(1) + f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1d"}) + f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: 86400, TsNs: now.Add(-30 * 24 * time.Hour).UnixNano()}}) + address := serveFiler(t, f) + + if completed := executeOn(t, address); !completed.Success { + t.Fatal(completed.ErrorMessage) + } + if c := f.cursors()["/logs/"]; c.ReadNs < now.UnixNano() { + t.Fatalf("cursor = %+v, want the replay read up to the run", c) + } + f.keepLogsFrom(now.Add(-time.Hour)) + if completed := executeOn(t, address); !completed.Success { + t.Fatal(completed.ErrorMessage) + } + if len(f.lists) != 0 { + t.Fatalf("lists=%v, want none: nothing the replay left waiting was purged", f.lists) + } +} diff --git a/weed/worker/tasks/filer_ttl/replay.go b/weed/worker/tasks/filer_ttl/replay.go new file mode 100644 index 0000000000..e76f1ef8fb --- /dev/null +++ b/weed/worker/tasks/filer_ttl/replay.go @@ -0,0 +1,443 @@ +package filer_ttl + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "sort" + "strings" + "time" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/storage/needle" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +const ( + cursorDir = filer.DirectoryEtcSeaweedFS + "/filer_ttl" + cursorSaveWait = 5 * time.Second + // cursorTTL is given to the cursors when a TTL rule covers them, so the + // rule's TTL, which the filer applies to an entry without one, does not + // drop them between runs. + cursorTTL = 365 * 24 * time.Hour +) + +type ttlRule struct { + prefix string + ttlSec int32 +} + +// ruleCursor is how far a TTL rule's events are done: no event at or before +// TsNs names an entry that is still waiting for its TTL. ReadNs is how far +// the last replay read with no entry left waiting, so the events up to it +// are no longer needed. WalkAtNs, when set, is when the rule is listed again, +// for a live entry the last listing met whose event the replay does not reach. +type ruleCursor struct { + TtlSec int32 `json:"ttl_sec"` + TsNs int64 `json:"ts_ns"` + ReadNs int64 `json:"read_ns,omitempty"` + WalkAtNs int64 `json:"walk_at_ns,omitempty"` +} + +type savedCursors struct { + Rules map[string]ruleCursor `json:"rules"` +} + +type runStats struct { + directories int64 + entries int64 + events int64 + expired int64 + pending int64 +} + +// ttlRules returns the filer.conf location rules that set a TTL. +func ttlRules(fc *filer.FilerConf) []ttlRule { + var rules []ttlRule + for _, location := range fc.ToProto().Locations { + ttl, err := needle.ReadTTL(location.GetTtl()) + if err != nil || ttl.ToSeconds() == 0 { + continue + } + rules = append(rules, ttlRule{prefix: location.LocationPrefix, ttlSec: int32(ttl.ToSeconds())}) + } + sort.Slice(rules, func(i, j int) bool { return rules[i].prefix < rules[j].prefix }) + return rules +} + +// outermost drops the prefixes another one in the sorted list encloses. +func outermost(prefixes []string) []string { + var outer []string + for _, prefix := range prefixes { + if n := len(outer); n > 0 && strings.HasPrefix(prefix, outer[n-1]) { + continue + } + outer = append(outer, prefix) + } + return outer +} + +// owner is the longest TTL rule prefix of path, the rule whose TTL the filer +// stamps on entries written there. +func owner(rules []ttlRule, path string) string { + found := "" + for _, rule := range rules { + if len(rule.prefix) > len(found) && strings.HasPrefix(path, rule.prefix) { + found = rule.prefix + } + } + return found +} + +// expiresAt is when the filer's lookups and listings start treating entry as +// gone; ok is false for an entry they never expire, and for one whose TTL an +// S3 lifecycle rule set, which the s3_lifecycle job expires. +func expiresAt(entry *filer.Entry) (deadline time.Time, ok bool) { + if entry.IsDirectory() || entry.TtlSec <= 0 || entry.IsExpireS3Enabled() { + return time.Time{}, false + } + return entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second), true +} + +// oldestLogTsNs is when the oldest metadata log the filer keeps starts; the +// events before it are gone. With no log kept it is runNow. +func oldestLogTsNs(ctx context.Context, client filer_pb.SeaweedFilerClient, runNow time.Time) (int64, error) { + day, err := firstName(ctx, client, filer.SystemLogDir, func(name string) bool { + _, err := time.Parse("2006-01-02", name) + return err == nil + }) + if err != nil || day == "" { + return runNow.UnixNano(), err + } + minute, err := firstName(ctx, client, filer.SystemLogDir+"/"+day, func(name string) bool { + if len(name) < 5 { + return false + } + _, err := time.Parse("15-04", name[:5]) + return err == nil + }) + if err != nil { + return 0, err + } + stamp := day + "-00-00" + if minute != "" { + stamp = day + "-" + minute[:5] + } + t, err := time.Parse("2006-01-02-15-04", stamp) + return t.UnixNano(), err +} + +// firstName is the smallest name in dir that valid accepts. The whole +// directory is read, since some stores do not list in name order. +func firstName(ctx context.Context, client filer_pb.SeaweedFilerClient, dir string, valid func(string) bool) (string, error) { + first := "" + err := filer_pb.SeaweedList(ctx, client, dir, "", func(entry *filer_pb.Entry, isLast bool) error { + if valid(entry.Name) && (first == "" || entry.Name < first) { + first = entry.Name + } + return nil + }, "", false, math.MaxInt32) + if errors.Is(err, filer_pb.ErrNotFound) { + err = nil + } + if err != nil { + return "", fmt.Errorf("list %s: %w", dir, err) + } + return first, nil +} + +// cursorName is keyed by the store signature, so cursors that filer.sync +// copies into another cluster's store are never read there. +func cursorName(signature int32) string { + return fmt.Sprintf("cursors-%d.json", signature) +} + +func loadCursors(ctx context.Context, client filer_pb.SeaweedFilerClient, name string) (map[string]ruleCursor, error) { + content, err := filer.ReadInsideFiler(ctx, client, cursorDir, name) + if errors.Is(err, filer_pb.ErrNotFound) { + return map[string]ruleCursor{}, nil + } + if err != nil { + return nil, fmt.Errorf("read cursors: %w", err) + } + var saved savedCursors + if err := json.Unmarshal(content, &saved); err != nil { + glog.Warningf("filer_ttl: decode cursors: %v; starting every rule over", err) + } + if saved.Rules == nil { + saved.Rules = map[string]ruleCursor{} + } + return saved.Rules, nil +} + +// saveCursors runs on its own context, so a run its deadline stopped still +// keeps what it finished. +func saveCursors(client filer_pb.SeaweedFilerClient, rules []ttlRule, name string, cursors map[string]ruleCursor) error { + content, err := json.Marshal(savedCursors{Rules: cursors}) + if err != nil { + return err + } + var ttlSec int32 + if owner(rules, cursorDir+"/"+name) != "" { + ttlSec = int32(cursorTTL / time.Second) + } + ctx, cancel := context.WithTimeout(context.Background(), cursorSaveWait) + defer cancel() + now := time.Now().Unix() + if err := filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{ + Directory: cursorDir, + Entry: &filer_pb.Entry{ + Name: name, + Content: content, + Attributes: &filer_pb.FuseAttributes{ + Mtime: now, + Crtime: now, + FileMode: 0644, + FileSize: uint64(len(content)), + Md5: util.Md5(content), + TtlSec: ttlSec, + }, + }, + }); err != nil { + return fmt.Errorf("save cursors: %w", err) + } + return nil +} + +// expireByEvents replays each TTL rule's metadata events from its cursor and +// has the filer remove every entry whose TTL has passed. A rule without a +// cursor, or whose TTL changed, is listed first: rows written before its +// replay window are only reached that way, and so are the rows of a rule +// whose unfinished events the filer no longer keeps. A live entry such a +// listing meets that was last written before the window, for example one an +// enclosing rule stamped with its longer TTL, has the rule listed again at +// its deadline. +func expireByEvents(ctx context.Context, client filer_pb.SeaweedFilerClient, rules []ttlRule, stats *runStats) error { + conf, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{}) + if err != nil { + return fmt.Errorf("filer configuration: %w", err) + } + name := cursorName(conf.Signature) + saved, err := loadCursors(ctx, client, name) + if err != nil { + return err + } + + runNow := time.Now() + logStart, err := oldestLogTsNs(ctx, client, runNow) + if err != nil { + return fmt.Errorf("metadata log start: %w", err) + } + cursors := make(map[string]ruleCursor, len(rules)) + var walk []string + for _, rule := range rules { + c, found := saved[rule.prefix] + switch { + case !found || c.TtlSec != rule.ttlSec: + window := time.Duration(max(rule.ttlSec, c.TtlSec)) * time.Second + c = ruleCursor{TtlSec: rule.ttlSec, TsNs: runNow.Add(-window).UnixNano()} + case max(c.TsNs, c.ReadNs) < logStart: + c = ruleCursor{TtlSec: c.TtlSec, TsNs: logStart - 1} + case c.WalkAtNs != 0 && c.WalkAtNs <= runNow.UnixNano(): + c.WalkAtNs = 0 + default: + cursors[rule.prefix] = c + continue + } + cursors[rule.prefix] = c + walk = append(walk, rule.prefix) + } + // The entries of a removed rule now belong to the rule enclosing it, + // which takes over what that rule's replay had not finished. + for prefix, c := range saved { + enclosing := owner(rules, prefix) + if _, current := cursors[prefix]; current || enclosing == "" { + continue + } + e := cursors[enclosing] + e.TsNs, e.ReadNs = min(e.TsNs, c.TsNs), min(e.ReadNs, c.ReadNs) + if c.WalkAtNs != 0 && (e.WalkAtNs == 0 || c.WalkAtNs < e.WalkAtNs) { + e.WalkAtNs = c.WalkAtNs + } + cursors[enclosing] = e + } + walking := map[string]bool{} + for _, prefix := range walk { + walking[prefix] = true + } + recordUnreplayed := func(dir util.FullPath, entry *filer_pb.Entry) { + prefix := owner(rules, string(dir.Child(entry.Name))) + if !walking[prefix] { + return + } + deadline, ok := expiresAt(filer.FromPbEntry(string(dir), entry)) + if !ok || !deadline.After(runNow) { + return + } + written := entry.GetAttributes().GetMtime() + if written == 0 { + written = entry.GetAttributes().GetCrtime() + } + c := cursors[prefix] + if time.Unix(written, 0).UnixNano() > c.TsNs { + return + } + if c.WalkAtNs == 0 || deadline.UnixNano() < c.WalkAtNs { + c.WalkAtNs = deadline.UnixNano() + cursors[prefix] = c + } + } + + var failed []string + unwalked := map[string]bool{} + for _, prefix := range outermost(walk) { + if err := walkLocationPrefix(ctx, client, prefix, stats, recordUnreplayed); err != nil { + failed = append(failed, fmt.Sprintf("walk %s: %v", prefix, err)) + for _, p := range walk { + if strings.HasPrefix(p, prefix) { + unwalked[p] = true + } + } + } + } + + for prefix, c := range saved { + if _, current := cursors[prefix]; !current && unwalked[owner(rules, prefix)] { + cursors[prefix] = c + } + } + for _, rule := range rules { + if unwalked[rule.prefix] { + if c, found := saved[rule.prefix]; found { + cursors[rule.prefix] = c + } else { + delete(cursors, rule.prefix) + } + continue + } + c := cursors[rule.prefix] + tsNs, readNs, err := replayRule(ctx, client, rules, rule.prefix, c.TsNs, runNow, stats) + c.TsNs, c.ReadNs = tsNs, readNs + cursors[rule.prefix] = c + if err != nil { + failed = append(failed, fmt.Sprintf("replay %s: %v", rule.prefix, err)) + } + } + + if err := saveCursors(client, rules, name, cursors); err != nil { + failed = append(failed, err.Error()) + } + if len(failed) > 0 { + return errors.New(strings.Join(failed, "; ")) + } + return nil +} + +// replayRule reads the events under prefix after startTsNs up to runNow and +// looks up every entry the rule owns whose TTL has passed; the lookup is what +// makes the filer remove the expired row. It returns how far the events are +// done: the first entry not yet due holds the cursor, so a later run replays +// its event once the TTL has passed. readNs is runNow when the replay read +// to it with no entry left waiting, and 0 otherwise. +func replayRule(ctx context.Context, client filer_pb.SeaweedFilerClient, rules []ttlRule, prefix string, startTsNs int64, runNow time.Time, stats *runStats) (done, readNs int64, err error) { + streamCtx, cancel := context.WithCancel(ctx) + defer cancel() + untilNs := runNow.UnixNano() + stream, err := client.SubscribeMetadata(streamCtx, &filer_pb.SubscribeMetadataRequest{ + ClientName: "filer_ttl", + PathPrefix: prefix, + SinceNs: startTsNs, + UntilNs: untilNs, + ClientId: util.RandomInt32(), + ClientSupportsBatching: true, + }) + if err != nil { + return startTsNs, 0, fmt.Errorf("subscribe: %w", err) + } + + done, held := startTsNs, false + finished := func() (int64, int64, error) { + if held { + return done, 0, nil + } + return done, untilNs, nil + } + handle := func(event *filer_pb.SubscribeMetadataResponse) error { + if event.EventNotification == nil || event.TsNs <= startTsNs { + return nil + } + stats.events++ + waiting, err := expireEventEntry(streamCtx, client, rules, prefix, event, runNow, stats) + if (waiting || err != nil) && !held { + held = true + if done == event.TsNs { + done-- + } + } + if !held { + done = event.TsNs + } + return err + } + for { + resp, err := stream.Recv() + if err == io.EOF { + return finished() + } + if err != nil { + return done, 0, err + } + for _, event := range append([]*filer_pb.SubscribeMetadataResponse{resp}, resp.Events...) { + if event.TsNs > untilNs { + return finished() + } + if err := handle(event); err != nil { + return done, 0, err + } + } + } +} + +// expireEventEntry reports whether the entry an event wrote is still waiting +// for its TTL, after looking it up if the TTL has passed. +func expireEventEntry(ctx context.Context, client filer_pb.SeaweedFilerClient, rules []ttlRule, prefix string, event *filer_pb.SubscribeMetadataResponse, runNow time.Time, stats *runStats) (waiting bool, err error) { + notification := event.EventNotification + if notification.NewEntry == nil { + return false, nil + } + dir := notification.NewParentPath + if dir == "" { + dir = event.Directory + } + if owner(rules, string(util.NewFullPath(dir, notification.NewEntry.Name))) != prefix { + return false, nil + } + deadline, ok := expiresAt(filer.FromPbEntry(dir, notification.NewEntry)) + if !ok { + return false, nil + } + if deadline.After(runNow) { + stats.pending++ + return true, nil + } + resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{Directory: dir, Name: notification.NewEntry.Name}) + if errors.Is(err, filer_pb.ErrNotFound) { + stats.expired++ + return false, nil + } + if err != nil { + return false, fmt.Errorf("lookup %s/%s: %w", dir, notification.NewEntry.Name, err) + } + // The filer, whose clock may trail this one, still serves it. A later + // write that moved its deadline has its own event. + if live, ok := expiresAt(filer.FromPbEntry(dir, resp.Entry)); ok && !live.After(deadline) { + stats.pending++ + return true, nil + } + return false, nil +} diff --git a/weed/worker/tasks/filer_ttl/walk.go b/weed/worker/tasks/filer_ttl/walk.go new file mode 100644 index 0000000000..fce64f8ec2 --- /dev/null +++ b/weed/worker/tasks/filer_ttl/walk.go @@ -0,0 +1,55 @@ +package filer_ttl + +import ( + "context" + "strings" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +const walkPageSize = 1024 + +// walkLocationPrefix lists every entry under a filer.conf location prefix and +// passes each live one to each. Listing is what removes expired rows: the +// filer drops each expired entry it meets and deletes the directories that +// leaves empty. +func walkLocationPrefix(ctx context.Context, client filer_pb.SeaweedFilerClient, locationPrefix string, stats *runStats, each func(dir util.FullPath, entry *filer_pb.Entry)) error { + root, namePrefix := util.FullPath(locationPrefix), "" + if !strings.HasSuffix(locationPrefix, "/") { + dir, name := root.DirAndName() + root, namePrefix = util.FullPath(dir), name + } + return walkDirectory(filer_pb.WithChunksOmitted(ctx), client, root, namePrefix, stats, each) +} + +func walkDirectory(ctx context.Context, client filer_pb.SeaweedFilerClient, dir util.FullPath, namePrefix string, stats *runStats, each func(dir util.FullPath, entry *filer_pb.Entry)) error { + stats.directories++ + startFrom := "" + for { + var subDirs []util.FullPath + listed := 0 + err := filer_pb.SeaweedList(ctx, client, string(dir), namePrefix, func(entry *filer_pb.Entry, isLast bool) error { + listed++ + startFrom = entry.Name + stats.entries++ + if entry.IsDirectory { + subDirs = append(subDirs, dir.Child(entry.Name)) + } else { + each(dir, entry) + } + return nil + }, startFrom, false, walkPageSize) + if err != nil { + return err + } + for _, subDir := range subDirs { + if err := walkDirectory(ctx, client, subDir, "", stats, each); err != nil { + return err + } + } + if listed < walkPageSize { + return nil + } + } +}