diff --git a/weed/filer/filer_ttl_sweep.go b/weed/filer/filer_ttl_sweep.go new file mode 100644 index 0000000000..c039eedb60 --- /dev/null +++ b/weed/filer/filer_ttl_sweep.go @@ -0,0 +1,164 @@ +package filer + +import ( + "context" + "sort" + "strings" + "time" + + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/storage/needle" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +const ( + expiredEntrySweepMinInterval = time.Hour + expiredEntrySweepMaxInterval = 24 * time.Hour + expiredEntrySweepPageSize = 1024 +) + +// loopSweepingExpiredEntries walks the paths that have a TTL rule. Expiry is +// otherwise applied only when an entry is looked up or its directory listed, +// so on a store without native TTL the rows of entries nobody visits again +// outlive their volumes. +func (f *Filer) loopSweepingExpiredEntries(self pb.ServerAddress) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { + <-f.deletionQuit + cancel() + }() + + lastSwept := make(map[string]time.Time) + ticker := time.NewTicker(expiredEntrySweepMinInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + f.sweepExpiredEntries(ctx, self, lastSwept, time.Now()) + } +} + +func (f *Filer) sweepExpiredEntries(ctx context.Context, self pb.ServerAddress, lastSwept map[string]time.Time, now time.Time) { + fc := f.FilerConf + if fc == nil { + return + } + for locationPrefix, interval := range expiredEntrySweepPrefixes(fc) { + if now.Sub(lastSwept[locationPrefix]) < interval || !f.sweepsExpiredEntries(locationPrefix, self) { + continue + } + expired, err := f.sweepExpiredEntriesUnder(ctx, locationPrefix) + if err != nil { + glog.V(0).Infof("sweep expired entries under %s: %v", locationPrefix, err) + continue + } + lastSwept[locationPrefix] = now + if expired > 0 { + glog.V(0).Infof("removed %d expired entries under %s", expired, locationPrefix) + } + } +} + +// expiredEntrySweepPrefixes maps each TTL rule that no other TTL rule +// encloses to how often it is swept: its TTL, kept between an hour and a day. +func expiredEntrySweepPrefixes(fc *FilerConf) map[string]time.Duration { + intervals := make(map[string]time.Duration) + for _, rule := range fc.ToProto().Locations { + ttl, err := needle.ReadTTL(rule.GetTtl()) + if err != nil || ttl.ToSeconds() == 0 { + continue + } + interval := time.Duration(ttl.ToSeconds()) * time.Second + if interval < expiredEntrySweepMinInterval { + interval = expiredEntrySweepMinInterval + } else if interval > expiredEntrySweepMaxInterval { + interval = expiredEntrySweepMaxInterval + } + intervals[rule.LocationPrefix] = interval + } + prefixes := make([]string, 0, len(intervals)) + for locationPrefix := range intervals { + prefixes = append(prefixes, locationPrefix) + } + sort.Strings(prefixes) + swept := make(map[string]time.Duration) + enclosing := "" + for _, locationPrefix := range prefixes { + if enclosing != "" && strings.HasPrefix(locationPrefix, enclosing) { + if intervals[locationPrefix] < swept[enclosing] { + swept[enclosing] = intervals[locationPrefix] + } + continue + } + enclosing = locationPrefix + swept[locationPrefix] = intervals[locationPrefix] + } + return swept +} + +// sweepsExpiredEntries leaves a prefix to its lock-ring owner when that filer +// runs on this filer's store; a filer with a store of its own sweeps it. +func (f *Filer) sweepsExpiredEntries(locationPrefix string, self pb.ServerAddress) bool { + if f.Dlm == nil { + return true + } + primary := f.Dlm.LockRing.GetPrimary(locationPrefix) + if primary == "" || primary == self { + return true + } + return f.MetaAggregator == nil || !f.MetaAggregator.SharesStore(primary) +} + +func (f *Filer) sweepExpiredEntriesUnder(ctx context.Context, locationPrefix string) (int64, error) { + ctx = context.WithValue(ctx, lazyListContextKey{}, true) + if strings.HasSuffix(locationPrefix, "/") { + dir := strings.TrimSuffix(locationPrefix, "/") + if dir == "" { + dir = "/" + } + return f.sweepExpiredEntriesIn(ctx, util.FullPath(dir), "") + } + dir, name := util.FullPath(locationPrefix).DirAndName() + return f.sweepExpiredEntriesIn(ctx, util.FullPath(dir), name) +} + +// sweepExpiredEntriesIn lists dir and everything below it, so the listing +// removes the expired entries it passes, then drops dir if that emptied it. +func (f *Filer) sweepExpiredEntriesIn(ctx context.Context, dir util.FullPath, namePrefix string) (expired int64, err error) { + startFileName := "" + for { + var subDirs []util.FullPath + var listed int64 + expiredCount, lastFileName, listErr := f.doListDirectoryEntries(ctx, dir, startFileName, false, expiredEntrySweepPageSize, namePrefix, func(entry *Entry) (bool, error) { + listed++ + if entry.IsDirectory() { + subDirs = append(subDirs, entry.FullPath) + } + return true, nil + }) + if listErr != nil { + return expired, listErr + } + expired += expiredCount + for _, subDir := range subDirs { + subExpired, subErr := f.sweepExpiredEntriesIn(ctx, subDir, "") + expired += subExpired + if subErr != nil { + return expired, subErr + } + } + if listed+expiredCount < expiredEntrySweepPageSize || lastFileName == "" { + break + } + startFileName = lastFileName + } + if expired > 0 && dir != "/" { + f.DeleteEmptyParentDirectories(ctx, dir, util.FullPath(f.DirBucketsPath)) + } + return expired, nil +} diff --git a/weed/filer/filer_ttl_sweep_test.go b/weed/filer/filer_ttl_sweep_test.go new file mode 100644 index 0000000000..e04dd31348 --- /dev/null +++ b/weed/filer/filer_ttl_sweep_test.go @@ -0,0 +1,149 @@ +package filer + +import ( + "context" + "fmt" + "os" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "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 TestSweepExpiredEntriesRemovesRowsNobodyVisits(t *testing.T) { + f, store := newTestFilerWithStubStore(t) + f.DirBucketsPath = "/buckets" + f.FilerConf = NewFilerConf() + for _, rule := range []*filer_pb.FilerConf_PathConf{ + {LocationPrefix: "/buckets/ttl-demo/", Ttl: "2m"}, + {LocationPrefix: "/ttl-http/logs", Ttl: "3d"}, + } { + if err := f.FilerConf.SetLocationConf(rule); err != nil { + t.Fatal(err) + } + } + + now := time.Now() + old := now.Add(-time.Hour) + for _, dir := range []string{"/buckets", "/buckets/ttl-demo", "/buckets/other", "/ttl-http"} { + putSweepTestEntry(t, store, dir, true, 0, old) + } + for _, dir := range []string{"day01", "day02", "day03"} { + putSweepTestEntry(t, store, "/buckets/ttl-demo/"+dir, true, 0, old) + } + for i := 0; i < expiredEntrySweepPageSize+300; i++ { + putSweepTestEntry(t, store, fmt.Sprintf("/buckets/ttl-demo/day01/f%05d", i), false, 120, old) + } + putSweepTestEntry(t, store, "/buckets/ttl-demo/day02/f1", false, 120, old) + putSweepTestEntry(t, store, "/buckets/ttl-demo/day03/old", false, 120, old) + putSweepTestEntry(t, store, "/buckets/ttl-demo/day03/fresh", false, 120, now) + putSweepTestEntry(t, store, "/buckets/other/old", false, 120, old) + putSweepTestEntry(t, store, "/ttl-http/logs1", false, 120, old) + putSweepTestEntry(t, store, "/ttl-http/other", false, 120, old) + + lastSwept := make(map[string]time.Time) + f.sweepExpiredEntries(context.Background(), "", lastSwept, now) + + gone := []string{ + "/buckets/ttl-demo/day01", "/buckets/ttl-demo/day01/f00000", "/buckets/ttl-demo/day01/f01300", + "/buckets/ttl-demo/day02", "/buckets/ttl-demo/day02/f1", + "/buckets/ttl-demo/day03/old", "/ttl-http/logs1", + } + for _, p := range gone { + if store.getEntry(p) != nil { + t.Errorf("%s still stored after the sweep", p) + } + } + kept := []string{ + "/buckets/ttl-demo", "/buckets/ttl-demo/day03", "/buckets/ttl-demo/day03/fresh", + "/buckets/other/old", "/ttl-http/other", + } + for _, p := range kept { + if store.getEntry(p) == nil { + t.Errorf("%s removed by the sweep", p) + } + } + if !lastSwept["/buckets/ttl-demo/"].Equal(now) || !lastSwept["/ttl-http/logs"].Equal(now) { + t.Fatalf("sweep times not recorded: %v", lastSwept) + } + + putSweepTestEntry(t, store, "/buckets/ttl-demo/day03/later", false, 120, old) + f.sweepExpiredEntries(context.Background(), "", lastSwept, now.Add(30*time.Minute)) + if store.getEntry("/buckets/ttl-demo/day03/later") == nil { + t.Fatal("swept again before its interval passed") + } + f.sweepExpiredEntries(context.Background(), "", lastSwept, now.Add(expiredEntrySweepMinInterval)) + if store.getEntry("/buckets/ttl-demo/day03/later") != nil { + t.Fatal("not swept once its interval passed") + } +} + +func TestExpiredEntrySweepPrefixes(t *testing.T) { + fc := NewFilerConf() + for _, rule := range []*filer_pb.FilerConf_PathConf{ + {LocationPrefix: "/a/", Ttl: "3d"}, + {LocationPrefix: "/a/b/", Ttl: "2m"}, + {LocationPrefix: "/a0/", Ttl: "1w"}, + {LocationPrefix: "/c/", Collection: "c"}, + {LocationPrefix: "/d/", Ttl: "5h"}, + } { + if err := fc.SetLocationConf(rule); err != nil { + t.Fatal(err) + } + } + got := expiredEntrySweepPrefixes(fc) + want := map[string]time.Duration{ + "/a/": expiredEntrySweepMinInterval, + "/a0/": expiredEntrySweepMaxInterval, + "/d/": 5 * time.Hour, + } + if len(got) != len(want) { + t.Fatalf("got %v, want %v", got, want) + } + for prefix, interval := range want { + if got[prefix] != interval { + t.Errorf("%s: got %v, want %v", prefix, got[prefix], interval) + } + } +} + +func TestSweepsExpiredEntriesOnlyOnceForASharedStore(t *testing.T) { + f, _ := newTestFilerWithStubStore(t) + self, peer := pb.ServerAddress("filer1:8888"), pb.ServerAddress("filer2:8888") + f.Dlm.LockRing.SetSnapshot([]pb.ServerAddress{self, peer}, 1) + f.MetaAggregator = &MetaAggregator{peerSharesStore: map[pb.ServerAddress]bool{peer: true}} + + var ownedBySelf, ownedByPeer string + for i := 0; ownedBySelf == "" || ownedByPeer == ""; i++ { + prefix := fmt.Sprintf("/buckets/b%d/", i) + if f.Dlm.LockRing.GetPrimary(prefix) == self { + ownedBySelf = prefix + } else { + ownedByPeer = prefix + } + } + if !f.sweepsExpiredEntries(ownedBySelf, self) { + t.Errorf("%s: owner does not sweep", ownedBySelf) + } + if f.sweepsExpiredEntries(ownedByPeer, self) { + t.Errorf("%s: swept here although its owner shares this store", ownedByPeer) + } + f.MetaAggregator.peerSharesStore[peer] = false + if !f.sweepsExpiredEntries(ownedByPeer, self) { + t.Errorf("%s: not swept here although its owner has a store of its own", ownedByPeer) + } +}