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" ) func testFile(name string, size uint64) *filer_pb.Entry { return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{FileSize: size}, Chunks: []*filer_pb.FileChunk{{FileId: "1", Size: size}}} } func testDir(name string) *filer_pb.Entry { return &filer_pb.Entry{Name: name, IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}} } func testEvent(tsNs int64, dir string, oldEntry, newEntry *filer_pb.Entry, newParent string) *filer_pb.SubscribeMetadataResponse { return &filer_pb.SubscribeMetadataResponse{ Directory: dir, TsNs: tsNs, EventNotification: &filer_pb.EventNotification{OldEntry: oldEntry, NewEntry: newEntry, NewParentPath: newParent}, } } func testRecord(root string, tsNs int64, dirs map[string]dirusage.Usage) *dirusage.Record { return &dirusage.Record{Version: dirusage.Version, Root: root, TsNs: tsNs, Dirs: dirs} } func newTestTracker(records ...*dirusage.Record) *tracker { byRoot := make(map[util.FullPath]*dirusage.Record) for _, record := range records { byRoot[util.FullPath(record.Root)] = record } return newTracker(dirusage.Roots{Buckets: "/buckets"}, byRoot) } func applyAll(t *testing.T, tr *tracker, events ...*filer_pb.SubscribeMetadataResponse) { t.Helper() for _, event := range events { if err := tr.apply(event); err != nil { t.Fatalf("apply: %v", err) } } } func expectDirs(t *testing.T, record *dirusage.Record, want map[string]dirusage.Usage) { t.Helper() if len(record.Dirs) != len(want) { t.Errorf("%s keeps %d directories, want %d: %v", record.Root, len(record.Dirs), len(want), record.Dirs) } for rel, usage := range want { if got, found := record.Dirs[rel]; !found || got != usage { t.Errorf("%s %q: %+v (kept %v), want %+v", record.Root, rel, got, found, usage) } } } func TestTrackerAddsAnEntryToEachTrackedDirectoryAboveIt(t *testing.T) { record := testRecord("/buckets/b", 100, map[string]dirusage.Usage{"": {}, "a": {}, "a/b": {}}) tr := newTestTracker(record) applyAll(t, tr, testEvent(101, "/buckets/b/a/b/c", nil, testFile("f", 10), ""), testEvent(102, "/buckets/b/a/b/c", testFile("f", 10), testFile("f", 25), ""), testEvent(103, "/buckets/b/a", nil, testDir("d"), ""), // at or before the record's position: already counted testEvent(100, "/buckets/b/a", nil, testFile("old", 1000), ""), ) expectDirs(t, record, map[string]dirusage.Usage{ "": {Bytes: 25, Chunks: 1, Files: 1, Dirs: 1}, "a": {Bytes: 25, Chunks: 1, Files: 1, Dirs: 1}, "a/b": {Bytes: 25, Chunks: 1, Files: 1}, }) if !tr.changed["/buckets/b"] { t.Errorf("the record is not marked changed") } } func TestTrackerMovesAFileBetweenBuckets(t *testing.T) { from := testRecord("/buckets/b", 100, map[string]dirusage.Usage{"": {Bytes: 10, Files: 1, Chunks: 1, Dirs: 1}, "a": {Bytes: 10, Files: 1, Chunks: 1}}) to := testRecord("/buckets/c", 100, map[string]dirusage.Usage{"": {}}) tr := newTestTracker(from, to) applyAll(t, tr, testEvent(101, "/buckets/b/a", testFile("f", 10), testFile("g", 10), "/buckets/c")) expectDirs(t, from, map[string]dirusage.Usage{"": {Dirs: 1}, "a": {}}) expectDirs(t, to, map[string]dirusage.Usage{"": {Bytes: 10, Files: 1, Chunks: 1}}) } func TestTrackerDropsADeletedTrackedDirectory(t *testing.T) { record := testRecord("/buckets/b", 100, map[string]dirusage.Usage{ "": {Bytes: 30, Files: 2, Chunks: 2, Dirs: 2}, "a": {Bytes: 20, Files: 1, Chunks: 1, Dirs: 1}, "a/b": {Bytes: 20, Files: 1, Chunks: 1}, }) tr := newTestTracker(record) // a recursive delete logs what is below a directory before it applyAll(t, tr, testEvent(101, "/buckets/b/a/b", testFile("f", 20), nil, ""), testEvent(102, "/buckets/b/a", testDir("b"), nil, ""), testEvent(103, "/buckets/b", testDir("a"), nil, ""), ) expectDirs(t, record, map[string]dirusage.Usage{"": {Bytes: 10, Files: 1, Chunks: 1}}) } func TestTrackerTakesOffWhatADeletedDirectoryHeldWithoutEvents(t *testing.T) { record := testRecord("/buckets/b", 100, map[string]dirusage.Usage{ "": {Bytes: 30, Files: 2, Chunks: 2, Dirs: 2}, "a": {Bytes: 20, Files: 1, Chunks: 1, Dirs: 1}, "a/b": {Bytes: 20, Files: 1, Chunks: 1}, }) tr := newTestTracker(record) applyAll(t, tr, testEvent(101, "/buckets/b", testDir("a"), nil, "")) expectDirs(t, record, map[string]dirusage.Usage{"": {Bytes: 10, Files: 1, Chunks: 1}}) } func TestTrackerMovesTheRecordOfAMovedDirectory(t *testing.T) { record := testRecord("/buckets/b", 100, map[string]dirusage.Usage{ "": {Bytes: 20, Files: 1, Chunks: 1, Dirs: 1}, "a": {Bytes: 20, Files: 1, Chunks: 1}, }) tr := newTestTracker(record) // a rename logs the directory and then each entry it moved applyAll(t, tr, testEvent(101, "/buckets/b", testDir("a"), testDir("z"), ""), testEvent(102, "/buckets/b/a", testFile("f", 20), testFile("f", 20), "/buckets/b/z"), ) expectDirs(t, record, map[string]dirusage.Usage{ "": {Bytes: 20, Files: 1, Chunks: 1, Dirs: 1}, "z": {Bytes: 20, Files: 1, Chunks: 1}, }) } func TestTrackerDropsTheRecordOfARemovedBucket(t *testing.T) { gone := testRecord("/buckets/gone", 100, map[string]dirusage.Usage{"": {Bytes: 5, Files: 1}}) tr := newTestTracker(gone) applyAll(t, tr, // seeded by the run, not counted from its events testEvent(101, "/buckets", nil, testDir("new"), ""), testEvent(102, "/buckets/new", nil, testFile("f", 7), ""), testEvent(103, "/", nil, testDir("home"), ""), // a store that drops a whole bucket logs the bucket alone testEvent(104, "/buckets", testDir("gone"), nil, ""), // neither a bucket nor counted testEvent(105, "/buckets", nil, testFile("stray", 3), ""), ) if !tr.removed["/buckets/gone"] || tr.records["/buckets/gone"] != nil { t.Errorf("the dropped bucket's record is kept") } if len(tr.records) != 0 || len(tr.changed) != 0 { t.Errorf("records for %v, changed %v", tr.records, tr.changed) } } func TestTrackerCountsALeftOutDirectoryButNothingInIt(t *testing.T) { etc := testRecord("/etc", 100, map[string]dirusage.Usage{"": {Dirs: 1}}) topics := testRecord("/topics", 100, map[string]dirusage.Usage{"": {Dirs: 1}}) tr := newTestTracker(etc, topics) applyAll(t, tr, testEvent(101, "/etc/seaweedfs", nil, testDir("dir_usage"), ""), testEvent(102, "/etc/seaweedfs/dir_usage/1/buckets", nil, testFile("new.json", 100), ""), testEvent(103, "/topics/.system", nil, testDir("log"), ""), testEvent(104, "/topics/.system/log/2026-12-03", nil, testFile("08-00.1", 100), ""), ) expectDirs(t, etc, map[string]dirusage.Usage{"": {Dirs: 2}}) expectDirs(t, topics, map[string]dirusage.Usage{"": {Dirs: 2}}) } func TestTrackerDropsADirectoryReplacedByAFile(t *testing.T) { record := testRecord("/buckets/b", 100, map[string]dirusage.Usage{ "": {Bytes: 20, Files: 1, Chunks: 1, Dirs: 1}, "x": {Bytes: 20, Files: 1, Chunks: 1}, }) tr := newTestTracker(record) applyAll(t, tr, testEvent(101, "/buckets/b", testDir("x"), testFile("x", 5), "")) expectDirs(t, record, map[string]dirusage.Usage{"": {Bytes: 5, Files: 1, Chunks: 1}}) } func TestHoldsShare(t *testing.T) { total := dirusage.Usage{Bytes: 1000} for _, c := range []struct { bytes int64 holds bool }{{0, false}, {9, false}, {10, true}, {500, true}} { if got := holdsShare(dirusage.Usage{Bytes: c.bytes}, total); got != c.holds { t.Errorf("%d of %d: holds %v, want %v", c.bytes, total.Bytes, got, c.holds) } } if !holdsShare(dirusage.Usage{Bytes: 1}, dirusage.Usage{Bytes: 1}) || holdsShare(dirusage.Usage{}, dirusage.Usage{}) { 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) } }