From 8760e2778b27e30a2023f9aee6745a65a321c0ea Mon Sep 17 00:00:00 2001 From: Yip Leo Date: Fri, 4 Dec 2026 15:40:58 +0800 Subject: [PATCH] worker: dir_usage takes off what a TTL expires (#13369) * worker: dir_usage takes off what a TTL expires A plain TTL removes an expired row without an event, so a record kept counting it until its bucket was seeded again. An entry's attributes say when listings start leaving it out (Entry.ExpiresAt, which listingExpired now uses), so a record keeps what each directory has still to expire, grouped by the step it expires in, and each run takes off what came off by its position. A step is an hour, or for a TTL of 200 hours or more the largest power of two hours up to 1% of it, so a record stays bounded. An event counts an entry only if the record has not taken it off yet, so an S3 expiry, which logs a delete, comes off once. Record version 2 seeds the records made before again. Part of #13257. Co-Authored-By: Claude Opus 5.5 * dir_usage: decide a seeded directory's share after what expired The seed took off what had expired by its position only after the final share check, so a directory the walk kept could be dropped against a total that still counted those entries. Take them off first, and hand what a dropped directory has still to expire to the directory above. Co-Authored-By: Claude Opus 5.5 * dir_usage: drop a seeded directory below its share with dropTracked A directory below its share has none above its share below it, so dropping it with what is below, its entries staying counted above, is what untrack did. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Chris Lu --- weed/filer/dirusage/dirusage.go | 61 ++++- weed/filer/dirusage/dirusage_test.go | 58 +++++ weed/filer/entry.go | 16 ++ weed/filer/filer.go | 9 +- weed/filer/treewalk/treewalktest/filer.go | 13 + weed/worker/tasks/dir_usage/run.go | 263 ++++++++++++++++---- weed/worker/tasks/dir_usage/run_test.go | 127 +++++++++- weed/worker/tasks/dir_usage/tracker_test.go | 146 +++++++++++ 8 files changed, 631 insertions(+), 62 deletions(-) diff --git a/weed/filer/dirusage/dirusage.go b/weed/filer/dirusage/dirusage.go index e60d540b63..929d6e753f 100644 --- a/weed/filer/dirusage/dirusage.go +++ b/weed/filer/dirusage/dirusage.go @@ -10,6 +10,7 @@ import ( "fmt" "math" "strings" + "time" "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" @@ -23,7 +24,8 @@ const ( Dir = filer.DirectoryEtcSeaweedFS + "/dir_usage" // Version is the version of the record format and of the rules that // pick the directories; a record of another version is made again. - Version = 1 + // Version 2 takes off what a TTL expires. + Version = 2 // MinSharePercent is the share of its bucket's bytes a directory holds // at least to get a record of its own. Directories at one depth do not // overlap, so a bucket has at most 100/MinSharePercent records per level. @@ -71,6 +73,59 @@ func (u Usage) IsZero() bool { return u == Usage{} } +// Value is what an entry adds to the directories above it, and when a record +// takes that off for its TTL. +type Value struct { + Usage + // Expires is when a record takes the entry off, in unix seconds, 0 if + // never: see Expires. + Expires int64 +} + +// EntryValue is what entry adds to the directories above it, and until when. +func EntryValue(entry *filer_pb.Entry) Value { + return Value{Usage: EntryUsage(entry), Expires: Expires(entry)} +} + +// Expires is when a record takes entry off, in unix seconds: the end of the +// step in which listings start leaving it out, or 0 if they never do. The +// plain TTL removes the row without an event, so a record takes off by the +// step what expired in it, and counts an expired entry for at most a step. +func Expires(entry *filer_pb.Entry) int64 { + ttlSec := int64(entry.GetAttributes().GetTtlSec()) + if entry == nil || entry.IsDirectory || ttlSec <= 0 { + return 0 + } + expiresAt, ok := filer.FromPbEntry("/", entry).ExpiresAt() + if !ok { + return 0 + } + step := expiryStep(ttlSec) + if t := expiresAt.Unix(); t > 0 { + return (t + step - 1) / step * step + } + // expired long ago + return step +} + +// expiryStep is an hour, or for a TTL of 200 hours or more the largest power +// of two hours up to 1% of it: a record counts an expired entry for at most +// an hour or 1% of its TTL, and fewer than 200 steps fit in any TTL, so a +// directory has about that many pending for each TTL in it at most. +func expiryStep(ttlSec int64) int64 { + step := int64(time.Hour / time.Second) + for step*2 <= ttlSec/100 { + step *= 2 + } + return step +} + +// TakenOff reports whether a record at tsNs has taken off what comes off at +// expires. +func TakenOff(expires, tsNs int64) bool { + return expires != 0 && expires <= tsNs/int64(time.Second) +} + // Record is what the job keeps of one bucket, or of one directory directly // under / outside the buckets folder. type Record struct { @@ -83,6 +138,10 @@ type Record struct { // Dirs are the totals of Root, at "", and of each directory below it // with a record of its own, by its path relative to Root. Dirs map[string]Usage `json:"dirs"` + // Expiring is what Dirs count that a TTL takes out later, by when it + // comes off (unix seconds, see Expires) and then by the directory in Dirs + // nearest above it. What comes off by TsNs is taken off. + Expiring map[int64]map[string]Usage `json:"expiring,omitempty"` } // Relative is path relative to root, "" for root itself. diff --git a/weed/filer/dirusage/dirusage_test.go b/weed/filer/dirusage/dirusage_test.go index e74329fe09..be73f7f258 100644 --- a/weed/filer/dirusage/dirusage_test.go +++ b/weed/filer/dirusage/dirusage_test.go @@ -1,8 +1,11 @@ package dirusage import ( + "math" "testing" + "time" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/util" ) @@ -36,3 +39,58 @@ func TestRootsOfAPath(t *testing.T) { t.Errorf("what holds the buckets folder counts") } } + +func TestExpiresByTheStepOfItsTTL(t *testing.T) { + expiresAt := time.Date(2026, 12, 4, 10, 20, 0, 0, time.UTC) + file := func(ttl time.Duration) *filer_pb.Entry { + return &filer_pb.Entry{Name: "f", Attributes: &filer_pb.FuseAttributes{ + FileSize: 1, + Crtime: expiresAt.Add(-ttl).Unix(), + TtlSec: int32(ttl / time.Second), + }} + } + for _, c := range []struct{ ttl, step time.Duration }{ + {30 * time.Minute, time.Hour}, + {7 * 24 * time.Hour, time.Hour}, + {200 * time.Hour, 2 * time.Hour}, + {30 * 24 * time.Hour, 4 * time.Hour}, + {365 * 24 * time.Hour, 64 * time.Hour}, + } { + step := int64(c.step / time.Second) + want := (expiresAt.Unix() + step - 1) / step * step + if got := Expires(file(c.ttl)); got != want { + t.Errorf("TTL %v: comes off at %d, want %d, the end of its %v step", c.ttl, got, want, c.step) + } + } + if got := Expires(&filer_pb.Entry{Name: "f", Attributes: &filer_pb.FuseAttributes{TtlSec: 60}}); got != 3600 { + t.Errorf("an entry that expired long ago comes off at %d", got) + } + for _, entry := range []*filer_pb.Entry{nil, {Name: "f", Attributes: &filer_pb.FuseAttributes{FileSize: 1}}, + {Name: "d", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{TtlSec: 60}}} { + if got := Expires(entry); got != 0 { + t.Errorf("%v comes off at %d", entry, got) + } + } +} + +func TestExpiryStepsAreFewAndShort(t *testing.T) { + hour := int64(time.Hour / time.Second) + for ttl := int64(1); ttl <= math.MaxInt32; ttl = ttl*9/8 + 1 { + step := expiryStep(ttl) + if step%hour != 0 || step/hour&(step/hour-1) != 0 { + t.Fatalf("TTL %ds: step %ds is not a power of two hours", ttl, step) + } + if step > max(hour, ttl/100) { + t.Errorf("TTL %ds: step %ds counts an expired entry for longer than an hour or 1%% of it", ttl, step) + } + if ttl/step >= 200 { + t.Errorf("TTL %ds: %d steps of %ds", ttl, ttl/step, step) + } + } + if !TakenOff(10, 10*int64(time.Second)) || TakenOff(10, 10*int64(time.Second)-1) || TakenOff(0, math.MaxInt64) { + t.Errorf("TakenOff") + } + if TakenOff(math.MaxInt64/2, math.MaxInt64) { + t.Errorf("a step beyond the last position is taken off") + } +} diff --git a/weed/filer/entry.go b/weed/filer/entry.go index 0813b75f1c..a0858b2193 100644 --- a/weed/filer/entry.go +++ b/weed/filer/entry.go @@ -229,6 +229,22 @@ func (entry *Entry) IsS3Versioning() (exist bool) { return exist } +// ExpiresAt is when listings start leaving entry out; ok is false for an +// entry they never leave out: a directory, one with no TTL, and a version of +// a versioned S3 object. +func (entry *Entry) ExpiresAt() (expiresAt time.Time, ok bool) { + if entry.TtlSec <= 0 || entry.IsDirectory() { + return time.Time{}, false + } + if entry.IsExpireS3Enabled() { + if entry.IsS3Versioning() { + return time.Time{}, false + } + return entry.GetS3ExpireTime(), true + } + return entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second), true +} + func (entry *Entry) GetS3ExpireTime() (expireTime time.Time) { if entry.Mtime.IsZero() { expireTime = entry.Crtime diff --git a/weed/filer/filer.go b/weed/filer/filer.go index bf6551e9d1..c1c520b3fa 100644 --- a/weed/filer/filer.go +++ b/weed/filer/filer.go @@ -1256,13 +1256,8 @@ func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, sta // listingExpired reports whether a listing leaves the entry out and deletes it. func listingExpired(entry *Entry) bool { - if entry.TtlSec <= 0 || entry.IsDirectory() { - return false - } - if entry.IsExpireS3Enabled() { - return entry.GetS3ExpireTime().Before(time.Now()) && !entry.IsS3Versioning() - } - return entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) + expiresAt, ok := entry.ExpiresAt() + return ok && expiresAt.Before(time.Now()) } // DeleteEmptyParentDirectories recursively checks and deletes parent directories if they become empty. diff --git a/weed/filer/treewalk/treewalktest/filer.go b/weed/filer/treewalk/treewalktest/filer.go index 3aa00bc5e5..0399ab8d00 100644 --- a/weed/filer/treewalk/treewalktest/filer.go +++ b/weed/filer/treewalk/treewalktest/filer.go @@ -155,6 +155,19 @@ func (f *Filer) Put(path util.FullPath, size uint64, chunks int) { f.putEntry(parentOf(path), entry) } +// PutTTL writes a file of size at path, created at crtime with a plain TTL. +func (f *Filer) PutTTL(path util.FullPath, size uint64, crtime time.Time, ttl time.Duration) { + f.mu.Lock() + defer f.mu.Unlock() + entry := &filer_pb.Entry{Name: path.Name(), Attributes: &filer_pb.FuseAttributes{ + FileSize: size, + Crtime: crtime.Unix(), + Mtime: crtime.Unix(), + TtlSec: int32(ttl / time.Second), + }} + f.putEntry(parentOf(path), entry) +} + // Mkdir creates a directory at path, and the missing ones above it. func (f *Filer) Mkdir(path util.FullPath) { f.mu.Lock() diff --git a/weed/worker/tasks/dir_usage/run.go b/weed/worker/tasks/dir_usage/run.go index 2cb8097671..b6b13fb808 100644 --- a/weed/worker/tasks/dir_usage/run.go +++ b/weed/worker/tasks/dir_usage/run.go @@ -103,9 +103,14 @@ func run(ctx context.Context, client filer_pb.FilerClient, now time.Time, stats } stats.removed++ } + for root, record := range t.records { + if takeOffExpired(record, untilNs) { + t.changed[root] = true + } + } for root := range t.changed { record := t.records[root] - record.TsNs = untilNs + record.TsNs = max(record.TsNs, untilNs) if err := store.Save(ctx, record); err != nil { return err } @@ -247,6 +252,8 @@ func (t *tracker) recordOf(path util.FullPath, tsNs int64) (*dirusage.Record, st // side applies what an event did at path: from and to are the entry before // and after, nil where there was none. moved is set when from went elsewhere. +// An entry the record has taken off for its TTL is no longer counted, so an +// event about it changes nothing again. func (t *tracker) side(path util.FullPath, tsNs int64, from, to *filer_pb.Entry, moved bool) { if t.roots.IsRoot(path) { t.rootChanged(path, tsNs, to) @@ -256,8 +263,19 @@ func (t *tracker) side(path util.FullPath, tsNs int64, from, to *filer_pb.Entry, if record == nil { return } - delta := dirusage.EntryUsage(to) - delta.Sub(dirusage.EntryUsage(from)) + var delta dirusage.Usage + if from != nil { + if value := dirusage.EntryValue(from); counted(value, record.TsNs) { + delta.Sub(value.Usage) + expireAt(record, rel, value, -1) + } + } + if to != nil { + if value := dirusage.EntryValue(to); counted(value, record.TsNs) { + delta.Add(value.Usage) + expireAt(record, rel, value, 1) + } + } addUp(record, rel, delta) if from != nil && from.IsDirectory && (to == nil || !to.IsDirectory) { dropTracked(record, joinRelative(rel, path.Name()), rel, moved && to == nil) @@ -265,6 +283,72 @@ func (t *tracker) side(path util.FullPath, tsNs int64, from, to *filer_pb.Entry, t.changed[util.FullPath(record.Root)] = true } +// counted reports whether a record at tsNs counts an entry with value. +func counted(value dirusage.Value, tsNs int64) bool { + return !dirusage.TakenOff(value.Expires, tsNs) +} + +// expireAt adds (sign 1) or withdraws (sign -1) an entry in the directory +// at rel to what comes off when it expires, under the directory with a +// record nearest above it. +func expireAt(record *dirusage.Record, rel string, value dirusage.Value, sign int) { + if value.Expires == 0 { + return + } + if record.Expiring == nil { + record.Expiring = make(map[int64]map[string]dirusage.Usage) + } + totals := record.Expiring[value.Expires] + if totals == nil { + totals = make(map[string]dirusage.Usage) + record.Expiring[value.Expires] = totals + } + at := nearestTracked(record, rel) + usage := totals[at] + if sign > 0 { + usage.Add(value.Usage) + } else { + usage.Sub(value.Usage) + } + if usage.IsZero() { + delete(totals, at) + } else { + totals[at] = usage + } + if len(totals) == 0 { + delete(record.Expiring, value.Expires) + } +} + +// takeOffExpired takes off what expired by tsNs and reports whether +// anything did. +func takeOffExpired(record *dirusage.Record, tsNs int64) bool { + took := false + for expires, totals := range record.Expiring { + if !dirusage.TakenOff(expires, tsNs) { + continue + } + for at, usage := range totals { + var expired dirusage.Usage + expired.Sub(usage) + addUp(record, at, expired) + } + delete(record.Expiring, expires) + took = true + } + return took +} + +// nearestTracked is rel, or the directory with a record nearest above it. +func nearestTracked(record *dirusage.Record, rel string) string { + for { + if _, tracked := record.Dirs[rel]; tracked || rel == "" { + return rel + } + rel = parentRelative(rel) + } +} + // trackedBelow are the directories at or below path with a record, relative // to path. func (t *tracker) trackedBelow(path util.FullPath, tsNs int64) []string { @@ -338,7 +422,9 @@ func addUp(record *dirusage.Record, rel string, delta dirusage.Usage) { // dropTracked drops the record of a removed directory and of what was below // it. A directory deleted with totals left had entries that went without // events, as when a store drops a whole bucket: the rest comes off the -// directories above it. A moved directory's entries each log their own move. +// directories above it, and so does what was still to expire there. A moved +// directory's entries each log their own move, and what they had still to +// expire waits for that under the directory above. func dropTracked(record *dirusage.Record, rel, parentRel string, moved bool) { usage, tracked := record.Dirs[rel] if !tracked { @@ -349,10 +435,27 @@ func dropTracked(record *dirusage.Record, rel, parentRel string, moved bool) { rest.Sub(usage) addUp(record, parentRel, rest) } - delete(record.Dirs, rel) - for below := range record.Dirs { - if strings.HasPrefix(below, rel+"/") { - delete(record.Dirs, below) + below := func(at string) bool { return at == rel || strings.HasPrefix(at, rel+"/") } + for at := range record.Dirs { + if below(at) { + delete(record.Dirs, at) + } + } + above := nearestTracked(record, parentRel) + for expires, totals := range record.Expiring { + for at, usage := range totals { + if !below(at) { + continue + } + delete(totals, at) + if moved { + waiting := totals[above] + waiting.Add(usage) + totals[above] = waiting + } + } + if len(totals) == 0 { + delete(record.Expiring, expires) } } } @@ -385,22 +488,48 @@ func depthOf(rel string) int { // seeding adds up a walk of the buckets folder or of / into the totals of // the roots in it: of each directory being walked, kept once it is done while // it holds its share of what the walk counted of its root so far. A directory -// holding its share of the whole root holds it of any part. +// holding its share of the whole root holds it of any part, unless entries +// went or expired since it was done. type seeding struct { - roots dirusage.Roots - totals map[util.FullPath]map[string]*dirusage.Usage // by root, then by path relative to it + roots dirusage.Roots + dirs map[util.FullPath]map[string]*seedDir // by root, then by path relative to it +} + +// seedDir is what a walk keeps of a directory: its totals, and what of them +// a TTL takes out, by when, for the entries it is the nearest kept directory +// above. +type seedDir struct { + usage dirusage.Usage + expiring map[int64]dirusage.Usage +} + +func (d *seedDir) expire(expires int64, usage dirusage.Usage, sign int) { + if d.expiring == nil { + d.expiring = make(map[int64]dirusage.Usage) + } + total := d.expiring[expires] + if sign > 0 { + total.Add(usage) + } else { + total.Sub(usage) + } + if total.IsZero() { + delete(d.expiring, expires) + } else { + d.expiring[expires] = total + } } // seedRoots walks container, the buckets folder or /, into the roots in it // that toSeed holds, and returns their records. func seedRoots(ctx context.Context, client filer_pb.FilerClient, roots dirusage.Roots, container util.FullPath, toSeed map[util.FullPath]bool) (map[util.FullPath]*dirusage.Record, error) { - s := &seeding{roots: roots, totals: make(map[util.FullPath]map[string]*dirusage.Usage)} - seed := &treewalk.Seed[dirusage.Usage]{ + s := &seeding{roots: roots, dirs: make(map[util.FullPath]map[string]*seedDir)} + seed := &treewalk.Seed[dirusage.Value]{ Client: client, ClientName: clientName, Concurrency: seedConcurrency, PageSize: seedPageSize, - Value: dirusage.EntryUsage, + Value: dirusage.EntryValue, Change: s.change, Started: s.started, Done: s.done, @@ -424,81 +553,123 @@ func seedRoots(ctx context.Context, client filer_pb.FilerClient, roots dirusage. return s.records(atNs), nil } -// of is the totals of the root dir is in, and dir relative to it; nil for -// the container. -func (s *seeding) of(dir util.FullPath) (root util.FullPath, totals map[string]*dirusage.Usage, rel string) { +// of is the directories kept of the root dir is in, and dir relative to it; +// nil for the container. +func (s *seeding) of(dir util.FullPath) (root util.FullPath, dirs map[string]*seedDir, rel string) { root, ok := s.roots.RootOf(dir) if !ok { return "", nil, "" } - return root, s.totals[root], dirusage.Relative(root, dir) + return root, s.dirs[root], dirusage.Relative(root, dir) } func (s *seeding) started(dir util.FullPath, depth int) { - root, totals, rel := s.of(dir) + root, dirs, rel := s.of(dir) switch { case root == "": case rel == "": - s.totals[root] = map[string]*dirusage.Usage{"": {}} - case totals != nil && depthOf(rel) <= dirusage.MaxDepth: - totals[rel] = &dirusage.Usage{} + s.dirs[root] = map[string]*seedDir{"": {}} + case dirs != nil && depthOf(rel) <= dirusage.MaxDepth: + dirs[rel] = &seedDir{} } } // change adds what changed in dir to each directory being walked or kept -// above it. An entry of the container is a root: one that goes away during -// the walk gets no record, since a store that drops a whole bucket logs no -// event for what was in it; the next run seeds it if it comes back. -func (s *seeding) change(dir util.FullPath, name string, from, to *dirusage.Usage) { +// above it, and what of it expires to the nearest. An entry of the container +// is a root: one that goes away during the walk gets no record, since a +// store that drops a whole bucket logs no event for what was in it; the next +// run seeds it if it comes back. +func (s *seeding) change(dir util.FullPath, name string, from, to *dirusage.Value) { if path := dir.Child(name); s.roots.IsRoot(path) { if to == nil { - delete(s.totals, path) + delete(s.dirs, path) } return } - _, totals, rel := s.of(dir) - if totals == nil { + _, dirs, rel := s.of(dir) + if dirs == nil { return } var delta dirusage.Usage if to != nil { - delta.Add(*to) + delta.Add(to.Usage) } if from != nil { - delta.Sub(*from) + delta.Sub(from.Usage) } + var nearest *seedDir for { - if usage := totals[rel]; usage != nil { - usage.Add(delta) + if d := dirs[rel]; d != nil { + d.usage.Add(delta) + if nearest == nil { + nearest = d + } } if rel == "" { - return + break } rel = parentRelative(rel) } + if from != nil && from.Expires != 0 { + nearest.expire(from.Expires, from.Usage, -1) + } + if to != nil && to.Expires != 0 { + nearest.expire(to.Expires, to.Usage, 1) + } } +// done drops a directory below its share, and hands what of it expires to +// the nearest directory kept above. func (s *seeding) done(dir util.FullPath, depth int) { - _, totals, rel := s.of(dir) - if totals == nil || rel == "" { + _, dirs, rel := s.of(dir) + if dirs == nil || rel == "" { return } - if usage := totals[rel]; usage != nil && !holdsShare(*usage, *totals[""]) { - delete(totals, rel) + d := dirs[rel] + if d == nil || holdsShare(d.usage, dirs[""].usage) { + return + } + delete(dirs, rel) + for above := parentRelative(rel); ; above = parentRelative(above) { + if kept := dirs[above]; kept != nil { + for expires, usage := range d.expiring { + kept.expire(expires, usage, 1) + } + return + } } } +// records are the totals of each root at atNs. What expired by then comes off +// first, so a directory the walk kept keeps its record if it holds its share +// of its root at atNs. func (s *seeding) records(atNs int64) map[util.FullPath]*dirusage.Record { - records := make(map[util.FullPath]*dirusage.Record, len(s.totals)) - for root, totals := range s.totals { - rootUsage := *totals[""] - dirs := map[string]dirusage.Usage{"": rootUsage} - for rel, usage := range totals { - if rel != "" && holdsShare(*usage, rootUsage) { - dirs[rel] = *usage + records := make(map[util.FullPath]*dirusage.Record, len(s.dirs)) + for root, dirs := range s.dirs { + record := &dirusage.Record{ + Version: dirusage.Version, + Root: string(root), + TsNs: atNs, + SeededNs: atNs, + Dirs: make(map[string]dirusage.Usage, len(dirs)), + } + for rel, d := range dirs { + record.Dirs[rel] = d.usage + } + for rel, d := range dirs { + for expires, usage := range d.expiring { + expireAt(record, rel, dirusage.Value{Usage: usage, Expires: expires}, 1) } } - records[root] = &dirusage.Record{Version: dirusage.Version, Root: string(root), TsNs: atNs, SeededNs: atNs, Dirs: dirs} + takeOffExpired(record, atNs) + rootUsage := record.Dirs[""] + for rel, usage := range record.Dirs { + if rel != "" && !holdsShare(usage, rootUsage) { + // its entries stay counted above, and none below holds its share + dropTracked(record, rel, parentRelative(rel), true) + } + } + records[root] = record } return records } diff --git a/weed/worker/tasks/dir_usage/run_test.go b/weed/worker/tasks/dir_usage/run_test.go index 683fc5eb59..6d6531e83e 100644 --- a/weed/worker/tasks/dir_usage/run_test.go +++ b/weed/worker/tasks/dir_usage/run_test.go @@ -39,13 +39,16 @@ func addLogStart(f *treewalktest.Filer, start time.Time) { } // totals adds up tree below root by directory, relative to root, leaving out -// what the counts leave out. -func totals(tree map[util.FullPath]*filer_pb.Entry, root util.FullPath) map[string]dirusage.Usage { +// what the counts leave out and what a record at atNs took off for a TTL. +func totals(tree map[util.FullPath]*filer_pb.Entry, root util.FullPath, atNs int64) map[string]dirusage.Usage { sums := map[string]dirusage.Usage{"": {}} for path, entry := range tree { if !path.IsUnder(root) { continue } + if dirusage.TakenOff(dirusage.Expires(entry), atNs) { + continue + } dir, _ := path.DirAndName() if dirusage.Skipped(util.FullPath(dir)) { continue @@ -72,7 +75,7 @@ func totals(tree map[util.FullPath]*filer_pb.Entry, root util.FullPath) map[stri // directory up to MaxDepth below it holding its share, and nothing else. func expectSeeded(t *testing.T, record *dirusage.Record, tree map[util.FullPath]*filer_pb.Entry) { t.Helper() - sums := totals(tree, util.FullPath(record.Root)) + sums := totals(tree, util.FullPath(record.Root), record.TsNs) want := map[string]dirusage.Usage{} for rel, usage := range sums { if rel == "" || depthOf(rel) <= dirusage.MaxDepth && holdsShare(usage, sums[""]) { @@ -82,10 +85,10 @@ func expectSeeded(t *testing.T, record *dirusage.Record, tree map[util.FullPath] expectDirs(t, record, want) } -// expectTracked checks each total a record keeps against the tree. -func expectTracked(t *testing.T, record *dirusage.Record, tree map[util.FullPath]*filer_pb.Entry) { +// expectTracked checks each total a record keeps against the tree at atNs. +func expectTracked(t *testing.T, record *dirusage.Record, tree map[util.FullPath]*filer_pb.Entry, atNs int64) { t.Helper() - sums := totals(tree, util.FullPath(record.Root)) + sums := totals(tree, util.FullPath(record.Root), atNs) for rel, usage := range record.Dirs { if want, found := sums[rel]; !found || usage != want { t.Errorf("%s %q: %+v, the tree has %+v", record.Root, rel, usage, want) @@ -125,7 +128,8 @@ func runAt(t *testing.T, client filer_pb.FilerClient, now time.Time) *runStats { func expectCurrent(t *testing.T, f *treewalktest.Filer, records map[util.FullPath]*dirusage.Record, cursor int64) { t.Helper() for _, record := range records { - expectTracked(t, record, f.At(max(record.TsNs, cursor))) + at := max(record.TsNs, cursor) + expectTracked(t, record, f.At(at), at) } } @@ -254,7 +258,7 @@ func TestRunSeedsWhileTheTreeChanges(t *testing.T) { } records, _ := loadRecords(t, client) for _, record := range records { - expectTracked(t, record, f.At(record.TsNs)) + expectTracked(t, record, f.At(record.TsNs), record.TsNs) } // and the next run picks up from there @@ -378,3 +382,110 @@ func TestRunSavesTheOtherSeededRecordsWhenOneSaveFails(t *testing.T) { } expectCurrent(t, f, records, cursor) } + +func TestRunTakesOffWhatATTLExpires(t *testing.T) { + shortLogMargin(t) + f, client := newTestFiler(t, time.Hour) + now := time.Now() + f.Put("/buckets/b1/a/keep", 1000, 1) + f.PutTTL("/buckets/b1/a/soon", 500, now, 30*time.Minute) + f.PutTTL("/buckets/b1/b/later", 300, now, 240*time.Hour) + // below 1%: what expires there comes off b1 itself + f.PutTTL("/buckets/b1/c/tiny", 5, now, 30*time.Minute) + runOnce(t, client) + records, _ := loadRecords(t, client) + b1 := records["/buckets/b1"] + if b1 == nil || b1.Dirs[""].Bytes != 1805 || len(b1.Expiring) != 2 { + t.Fatalf("seeded b1: %+v", b1) + } + if _, kept := b1.Dirs["c"]; kept { + t.Fatalf("b1 keeps c, below its share") + } + expectSeeded(t, b1, f.At(b1.TsNs)) + + // three hours on, on the filer's clock + f.Skew = 3 * time.Hour + if stats := runOnce(t, client); stats.written != 1 { + t.Errorf("wrote %d records, want b1", stats.written) + } + records, cursor := loadRecords(t, client) + b1 = records["/buckets/b1"] + if b1.Dirs[""].Bytes != 1300 || b1.Dirs["a"].Bytes != 1000 || len(b1.Expiring) != 1 { + t.Errorf("b1 after the first TTL: %+v, expiring %+v", b1.Dirs, b1.Expiring) + } + expectCurrent(t, f, records, cursor) +} + +func TestSeedingSharesAreThoseAfterWhatExpired(t *testing.T) { + start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC) + s := &seeding{roots: dirusage.NewRoots("/buckets"), dirs: make(map[util.FullPath]map[string]*seedDir)} + add := func(dir util.FullPath, entry *filer_pb.Entry) { + value := dirusage.EntryValue(entry) + s.change(dir, entry.Name, nil, &value) + } + s.started("/buckets/b", 0) + add("/buckets/b", testDir("keep")) + add("/buckets/b", testDir("tmp")) + // keep is walked first and holds all the walk counted then; what tmp + // holds expires before the walk ends + s.started("/buckets/b/keep", 1) + add("/buckets/b/keep", testFile("k", 5)) + s.done("/buckets/b/keep", 1) + s.started("/buckets/b/tmp", 1) + add("/buckets/b/tmp", testTTLFile("t", 1000, start.Add(30*time.Minute))) + s.done("/buckets/b/tmp", 1) + s.done("/buckets/b", 0) + record := s.records(hourAfter(start.Add(30*time.Minute)) * int64(time.Second))["/buckets/b"] + expectDirs(t, record, map[string]dirusage.Usage{ + "": {Bytes: 5, Chunks: 1, Files: 1, Dirs: 2}, + "keep": {Bytes: 5, Chunks: 1, Files: 1}, + }) + if len(record.Expiring) != 0 { + t.Errorf("still waiting: %+v", record.Expiring) + } + + // a directory dropped for its share hands what it has still to expire + // to the directory above + s = &seeding{roots: dirusage.NewRoots("/buckets"), dirs: make(map[util.FullPath]map[string]*seedDir)} + s.started("/buckets/b", 0) + add("/buckets/b", testDir("big")) + add("/buckets/b", testDir("small")) + s.started("/buckets/b/small", 1) + add("/buckets/b/small", testTTLFile("s", 5, start.Add(5*time.Hour))) + s.done("/buckets/b/small", 1) + s.started("/buckets/b/big", 1) + add("/buckets/b/big", testFile("g", 1000)) + s.done("/buckets/b/big", 1) + s.done("/buckets/b", 0) + record = s.records(start.UnixNano())["/buckets/b"] + expectDirs(t, record, map[string]dirusage.Usage{ + "": {Bytes: 1005, Chunks: 2, Files: 2, Dirs: 2}, + "big": {Bytes: 1000, Chunks: 1, Files: 1}, + }) + if got := record.Expiring[hourAfter(start.Add(5*time.Hour))]; len(got) != 1 || got[""] != (dirusage.Usage{Bytes: 5, Chunks: 1, Files: 1}) { + t.Errorf("waiting to expire: %+v", record.Expiring) + } +} + +func TestRunSeedsAgainARecordOfAnotherVersion(t *testing.T) { + shortLogMargin(t) + f, client := newTestFiler(t, time.Hour) + buildBuckets(f) + runOnce(t, client) + store := &dirusage.Store{Client: client, Signature: 1, Roots: dirusage.Roots{Buckets: "/buckets"}} + old, err := store.Load(context.Background(), "/buckets/b2") + if err != nil || old == nil { + t.Fatalf("load b2: %v, %v", old, err) + } + old.Version = 1 + if err := store.Save(context.Background(), old); err != nil { + t.Fatal(err) + } + if stats := runOnce(t, client); stats.seeded != 1 { + t.Errorf("seeded %d roots, want b2 again", stats.seeded) + } + records, _ := loadRecords(t, client) + if b2 := records["/buckets/b2"]; b2 == nil || b2.Version != dirusage.Version { + t.Errorf("b2 record %+v", b2) + } +} diff --git a/weed/worker/tasks/dir_usage/tracker_test.go b/weed/worker/tasks/dir_usage/tracker_test.go index 5f83e393f6..7fc71aca38 100644 --- a/weed/worker/tasks/dir_usage/tracker_test.go +++ b/weed/worker/tasks/dir_usage/tracker_test.go @@ -2,9 +2,11 @@ package dir_usage import ( "testing" + "time" "github.com/seaweedfs/seaweedfs/weed/filer/dirusage" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/util" ) @@ -189,3 +191,147 @@ func TestHoldsShare(t *testing.T) { t.Errorf("a non-empty directory of a tiny bucket holds its share; an empty one never does") } } + +// testTTLFile is a file of size that a plain TTL takes out at expiresAt. +func testTTLFile(name string, size uint64, expiresAt time.Time) *filer_pb.Entry { + entry := testFile(name, size) + entry.Attributes.Crtime = expiresAt.Add(-time.Hour).Unix() + entry.Attributes.TtlSec = int32(time.Hour / time.Second) + return entry +} + +func hourAfter(t time.Time) int64 { + return (t.Unix() + 3599) / 3600 * 3600 +} + +func TestTrackerTakesOffWhatATTLExpiresAtTheEndOfItsStep(t *testing.T) { + start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC) + expires := start.Add(90 * time.Minute) + record := testRecord("/buckets/b", start.UnixNano(), map[string]dirusage.Usage{"": {}, "a": {}}) + tr := newTestTracker(record) + applyAll(t, tr, + testEvent(start.UnixNano()+1, "/buckets/b/a/deep", nil, testTTLFile("f", 10, expires), ""), + testEvent(start.UnixNano()+2, "/buckets/b/a", nil, testFile("g", 5), ""), + ) + expectDirs(t, record, map[string]dirusage.Usage{ + "": {Bytes: 15, Chunks: 2, Files: 2}, + "a": {Bytes: 15, Chunks: 2, Files: 2}, + }) + end := hourAfter(expires) + if got := record.Expiring[end]["a"]; got != (dirusage.Usage{Bytes: 10, Chunks: 1, Files: 1}) { + t.Errorf("waiting to expire at %d under a: %+v, all %+v", end, got, record.Expiring) + } + if takeOffExpired(record, end*int64(time.Second)-1) { + t.Errorf("took off before the end of its step") + } + if !takeOffExpired(record, end*int64(time.Second)) { + t.Errorf("took nothing off at the end of its step") + } + expectDirs(t, record, map[string]dirusage.Usage{ + "": {Bytes: 5, Chunks: 1, Files: 1}, + "a": {Bytes: 5, Chunks: 1, Files: 1}, + }) + if len(record.Expiring) != 0 { + t.Errorf("still waiting: %+v", record.Expiring) + } +} + +func TestTrackerWithdrawsAnEntryGoneBeforeItExpires(t *testing.T) { + start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC) + file := testTTLFile("f", 10, start.Add(time.Hour)) + longer := testTTLFile("f", 30, start.Add(5*time.Hour)) + record := testRecord("/buckets/b", start.UnixNano(), map[string]dirusage.Usage{"": {}}) + tr := newTestTracker(record) + applyAll(t, tr, + testEvent(start.UnixNano()+1, "/buckets/b", nil, file, ""), + // written again with a later expiry, then deleted + testEvent(start.UnixNano()+2, "/buckets/b", file, longer, ""), + testEvent(start.UnixNano()+3, "/buckets/b", longer, nil, ""), + ) + expectDirs(t, record, map[string]dirusage.Usage{"": {}}) + if len(record.Expiring) != 0 { + t.Errorf("still waiting: %+v", record.Expiring) + } +} + +func TestTrackerTakesOffAnExpiredEntryOnce(t *testing.T) { + // the step f expired in ended before the record's position, so f was + // taken off then + start := time.Date(2026, 12, 4, 6, 0, 0, 0, time.UTC) + expired := testTTLFile("f", 10, start.Add(-2*time.Hour)) + record := testRecord("/buckets/b", start.UnixNano(), map[string]dirusage.Usage{"": {Bytes: 1, Files: 1, Chunks: 1}}) + tr := newTestTracker(record) + applyAll(t, tr, + // an S3 delete or a listing removes the expired entry, with an event + testEvent(start.UnixNano()+1, "/buckets/b", expired, nil, ""), + // a write whose TTL had passed before it lands never shows + testEvent(start.UnixNano()+2, "/buckets/b", nil, testTTLFile("g", 7, start.Add(-time.Hour)), ""), + ) + expectDirs(t, record, map[string]dirusage.Usage{"": {Bytes: 1, Files: 1, Chunks: 1}}) +} + +func TestTrackerExpiresS3ObjectsUnlessVersioned(t *testing.T) { + start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC) + s3Object := func(name string, versioned bool) *filer_pb.Entry { + entry := testFile(name, 10) + entry.Attributes.Mtime = start.Unix() + entry.Attributes.TtlSec = int32(time.Hour / time.Second) + entry.Extended = map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")} + if versioned { + entry.Extended[s3_constants.ExtVersionIdKey] = []byte("v1") + } + return entry + } + if got, want := dirusage.Expires(s3Object("o", false)), hourAfter(start.Add(time.Hour)); got != want { + t.Errorf("S3 object comes off at %d, want %d", got, want) + } + if got := dirusage.Expires(s3Object("v", true)); got != 0 { + t.Errorf("a version of a versioned object comes off at %d", got) + } + if got := dirusage.Expires(testDir("d")); got != 0 { + t.Errorf("a directory comes off at %d", got) + } +} + +func TestTrackerMovesWhatExpiresWithAMovedDirectory(t *testing.T) { + start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC) + file := testTTLFile("f", 10, start.Add(time.Hour)) + hour := hourAfter(start.Add(time.Hour)) + record := testRecord("/buckets/b", start.UnixNano(), map[string]dirusage.Usage{ + "": {Bytes: 10, Files: 1, Chunks: 1, Dirs: 1}, + "x": {Bytes: 10, Files: 1, Chunks: 1}, + }) + record.Expiring = map[int64]map[string]dirusage.Usage{hour: {"x": {Bytes: 10, Files: 1, Chunks: 1}}} + tr := newTestTracker(record) + applyAll(t, tr, + testEvent(start.UnixNano()+1, "/buckets/b", testDir("x"), testDir("y"), ""), + testEvent(start.UnixNano()+2, "/buckets/b/x", file, file, "/buckets/b/y"), + ) + expectDirs(t, record, map[string]dirusage.Usage{ + "": {Bytes: 10, Files: 1, Chunks: 1, Dirs: 1}, + "y": {Bytes: 10, Files: 1, Chunks: 1}, + }) + if got := record.Expiring[hour]; len(got) != 1 || got["y"] != (dirusage.Usage{Bytes: 10, Files: 1, Chunks: 1}) { + t.Errorf("waiting to expire: %+v", record.Expiring) + } +} + +func TestTrackerDropsWhatExpiresUnderADeletedDirectory(t *testing.T) { + start := time.Date(2026, 12, 4, 0, 0, 0, 0, time.UTC) + hour := hourAfter(start.Add(time.Hour)) + record := testRecord("/buckets/b", start.UnixNano(), map[string]dirusage.Usage{ + "": {Bytes: 15, Files: 2, Chunks: 2, Dirs: 1}, + "x": {Bytes: 10, Files: 1, Chunks: 1}, + }) + record.Expiring = map[int64]map[string]dirusage.Usage{hour: { + "x": {Bytes: 10, Files: 1, Chunks: 1}, + "": {Bytes: 5, Files: 1, Chunks: 1}, + }} + tr := newTestTracker(record) + // deleted with nothing logged for what was in it + applyAll(t, tr, testEvent(start.UnixNano()+1, "/buckets/b", testDir("x"), nil, "")) + expectDirs(t, record, map[string]dirusage.Usage{"": {Bytes: 5, Files: 1, Chunks: 1}}) + if got := record.Expiring[hour]; len(got) != 1 || got[""] != (dirusage.Usage{Bytes: 5, Files: 1, Chunks: 1}) { + t.Errorf("waiting to expire: %+v", record.Expiring) + } +}