diff --git a/weed/filer/entry.go b/weed/filer/entry.go index a0858b2193..32dcfc050f 100644 --- a/weed/filer/entry.go +++ b/weed/filer/entry.go @@ -160,6 +160,13 @@ func maxUint64(x, y uint64) uint64 { return y } +// IsDirectoryKeyObject mirrors filer_pb.Entry.IsDirectoryKeyObject, so a +// promoted file's data is kept. +func (entry *Entry) IsDirectoryKeyObject() bool { + _, isPrefixObject := entry.Extended[s3_constants.SeaweedFSPrefixObject] + return entry.IsDirectory() && (entry.Mime != "" || len(entry.GetChunks()) > 0 || len(entry.Content) > 0 || entry.IsInRemoteOnly() || isPrefixObject) +} + func (entry *Entry) IsExpireS3Enabled() (exist bool) { if entry.Extended != nil { _, exist = entry.Extended[s3_constants.SeaweedFSExpiresS3] diff --git a/weed/filer/filer.go b/weed/filer/filer.go index c1c520b3fa..c3b621e94d 100644 --- a/weed/filer/filer.go +++ b/weed/filer/filer.go @@ -1321,6 +1321,9 @@ func (f *Filer) DeleteEmptyParentDirectories(ctx context.Context, dirPath util.F glog.V(2).InfofCtx(ctx, "DeleteEmptyParentDirectories: deleting empty directory %s", dirPath) parentDir, _ := dirPath.DirAndName() if dirEntry, findErr := f.FindEntry(ctx, dirPath); findErr == nil { + if dirEntry.IsDirectoryKeyObject() { + return + } if delErr := f.doDeleteEntryMetaAndData(f.emptyFolderDeleteContext(ctx, dirPath), dirEntry, false, false, nil); delErr == nil { // Successfully deleted, continue checking upwards f.DeleteEmptyParentDirectories(ctx, util.FullPath(parentDir), stopAtPath) @@ -1390,7 +1393,5 @@ func (f *Filer) IsDirectoryKeyObject(ctx context.Context, p util.FullPath) (bool if entry == nil { return false, nil } - // Mirror filer_pb.Entry.IsDirectoryKeyObject so the cleaner keeps a promoted file's data. - _, isPrefixObject := entry.Extended[s3_constants.SeaweedFSPrefixObject] - return entry.IsDirectory() && (entry.Mime != "" || len(entry.GetChunks()) > 0 || len(entry.Content) > 0 || entry.IsInRemoteOnly() || isPrefixObject), nil + return entry.IsDirectoryKeyObject(), nil } diff --git a/weed/filer/filer_expired_entry.go b/weed/filer/filer_expired_entry.go index 3541655874..cc62555f9a 100644 --- a/weed/filer/filer_expired_entry.go +++ b/weed/filer/filer_expired_entry.go @@ -5,6 +5,7 @@ import ( "errors" "time" + "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/util" ) @@ -81,3 +82,22 @@ func (f *Filer) deleteRowIfExpired(ctx context.Context, p util.FullPath) (gone b } return true, nil } + +// RemoveExpiredLeftover is for a lookup that found nothing at p under a +// filer.conf TTL rule. On a store whose rows expire on their own it removes +// what such a row left behind. The directory this may leave empty stays: +// removing one safely takes the empty folder cleaner's checks, which +// DeleteEmptyParentDirectories does not make. +func (f *Filer) RemoveExpiredLeftover(ctx context.Context, p util.FullPath) { + fsw, ok := f.Store.(*FilerStoreWrapper) + if !ok { + return + } + store := fsw.expiredLeftoverStore(p) + if store == nil || f.FilerConf == nil || f.FilerConf.MatchStorageRule(string(p)).GetTtl() == "" { + return + } + if _, err := store.RemoveExpiredLeftover(ctx, p); err != nil { + glog.V(1).InfofCtx(ctx, "remove what expired at %s: %v", p, err) + } +} diff --git a/weed/filer/filer_expired_entry_test.go b/weed/filer/filer_expired_entry_test.go index 866d553224..31c3676ca2 100644 --- a/weed/filer/filer_expired_entry_test.go +++ b/weed/filer/filer_expired_entry_test.go @@ -215,3 +215,81 @@ func TestFindEntryReportsAFailedExpiryDelete(t *testing.T) { t.Fatalf("lookup hid a failed delete of the expired row: %v", err) } } + +// leftoverStore stands for a store whose rows expire on their own, leaving +// something only it can remove. +type leftoverStore struct { + *stubFilerStore + leftovers map[util.FullPath]bool + asked []util.FullPath +} + +func (s *leftoverStore) RemoveExpiredLeftover(_ context.Context, p util.FullPath) (bool, error) { + s.asked = append(s.asked, p) + left := s.leftovers[p] + delete(s.leftovers, p) + return left, nil +} + +// A lookup has the store remove what expiry left of a name under a TTL rule, +// and nothing else: a directory this leaves empty is not removed from here. +func TestRemoveExpiredLeftoverAsksTheStoreAndLeavesDirectories(t *testing.T) { + f, stub := newTestFilerWithStubStore(t) + store := &leftoverStore{stubFilerStore: stub, leftovers: map[util.FullPath]bool{ + "/buckets/cam/day1/a.mp4": true, + "/buckets/cam/.uploads/abc/0001.part": true, + "/buckets/other/day1/a.mp4": true, + }} + f.Store = NewFilerStoreWrapper(store) + f.DirBucketsPath = "/buckets" + f.FilerConf = NewFilerConf() + if err := f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "1h"}); err != nil { + t.Fatal(err) + } + now := time.Now() + dirs := []string{"/buckets", "/buckets/cam", "/buckets/cam/day1", "/buckets/cam/.uploads", "/buckets/cam/.uploads/abc", "/buckets/other", "/buckets/other/day1"} + for _, dir := range dirs { + putSweepTestEntry(t, stub, dir, true, 0, now) + } + ctx := context.Background() + + f.RemoveExpiredLeftover(ctx, "/buckets/other/day1/a.mp4") + if len(store.asked) != 0 { + t.Fatalf("asked the store about %v, which no TTL rule covers", store.asked) + } + + f.RemoveExpiredLeftover(ctx, "/buckets/cam/day1/a.mp4") + f.RemoveExpiredLeftover(ctx, "/buckets/cam/.uploads/abc/0001.part") + if len(store.asked) != 2 || len(store.leftovers) != 1 { + t.Fatalf("asked %v, left %v: want both names under the TTL rule removed", store.asked, store.leftovers) + } + for _, dir := range dirs { + if stub.getEntry(dir) == nil { + t.Fatalf("%s was removed by a lookup's cleanup", dir) + } + } +} + +// A file promoted to a directory by a child write keeps its own object data, +// so it is not an empty parent to remove once its last child is gone. +func TestDeleteEmptyParentDirectoriesKeepsADirectoryHoldingAnObject(t *testing.T) { + f, stub := newTestFilerWithStubStore(t) + f.DirBucketsPath = "/buckets" + now := time.Now() + for _, dir := range []string{"/buckets", "/buckets/cam", "/buckets/cam/day2"} { + putSweepTestEntry(t, stub, dir, true, 0, now) + } + promoted := &Entry{FullPath: "/buckets/cam/day1", Attr: Attr{Mode: os.ModeDir | 0o755, Crtime: now, Mtime: now}, Content: []byte("day1 object")} + if err := stub.InsertEntry(context.Background(), promoted); err != nil { + t.Fatal(err) + } + + f.DeleteEmptyParentDirectories(context.Background(), "/buckets/cam/day1", "/buckets") + if stub.getEntry("/buckets/cam/day1") == nil { + t.Fatal("removed the directory that still holds the day1 object") + } + f.DeleteEmptyParentDirectories(context.Background(), "/buckets/cam/day2", "/buckets") + if stub.getEntry("/buckets/cam/day2") != nil { + t.Fatal("an empty directory holding no object is still stored") + } +} diff --git a/weed/filer/filerstore.go b/weed/filer/filerstore.go index c84af6f176..dfd5fe5bc4 100644 --- a/weed/filer/filerstore.go +++ b/weed/filer/filerstore.go @@ -167,6 +167,15 @@ type ConflictRefusingStore interface { RefusesConflictingCommits() bool } +// ExpiredLeftoverStore is implemented by a store whose rows expire on their +// own and can leave part of an entry behind, as the redis stores leave its +// name in the parent directory's list. +type ExpiredLeftoverStore interface { + // RemoveExpiredLeftover removes what is left of the entry at fullpath + // once its row is gone, and reports whether there was anything. + RemoveExpiredLeftover(ctx context.Context, fullpath util.FullPath) (removed bool, err error) +} + // OverwritingStore is implemented by a store without transactions whose // InsertEntry over an existing entry replaces it at once and whole: the stored // entry, its expiry, and its listing in the directory. A rename can then write diff --git a/weed/filer/filerstore_wrapper.go b/weed/filer/filerstore_wrapper.go index ccb43f6c74..554c4ebc5c 100644 --- a/weed/filer/filerstore_wrapper.go +++ b/weed/filer/filerstore_wrapper.go @@ -567,6 +567,17 @@ func (fsw *FilerStoreWrapper) overwritesAtOnce(path util.FullPath) bool { return ok && overwriting.OverwritesAtOnce() && fsw.getActualStore(path) == fsw.defaultStore } +// expiredLeftoverStore returns the default store when a row of it that expires +// on its own can leave part of an entry behind (ExpiredLeftoverStore) and it +// holds the entry at path, and nil otherwise. +func (fsw *FilerStoreWrapper) expiredLeftoverStore(path util.FullPath) ExpiredLeftoverStore { + leaving, ok := fsw.defaultStore.(ExpiredLeftoverStore) + if !ok || fsw.getActualStore(path) != fsw.defaultStore { + return nil + } + return leaving +} + func (fsw *FilerStoreWrapper) BeginTransaction(ctx context.Context) (context.Context, error) { if err := ctx.Err(); err != nil { return nil, err diff --git a/weed/filer/redis/universal_redis_store.go b/weed/filer/redis/universal_redis_store.go index 68a400ac69..bf18578aa7 100644 --- a/weed/filer/redis/universal_redis_store.go +++ b/weed/filer/redis/universal_redis_store.go @@ -2,6 +2,7 @@ package redis import ( "context" + "errors" "fmt" "slices" "strings" @@ -225,30 +226,64 @@ func (store *UniversalRedisStore) ListDirectoryEntries(ctx context.Context, dirP return lastFileName, err } -func (store *UniversalRedisStore) removeOrphanedDirectoryListMember(ctx context.Context, dirPath util.FullPath, fileName string) { +// RemoveExpiredLeftover removes the directory list member of an entry whose +// value redis expired; a lookup of that entry has nothing else to find it by. +func (store *UniversalRedisStore) RemoveExpiredLeftover(ctx context.Context, fullpath util.FullPath) (removed bool, err error) { + dir, name := fullpath.DirAndName() + if name == "" { + return false, nil + } + // Most misses are of a name that was never written: no member, nothing to do. + if member, err := store.Client.SIsMember(ctx, genDirectoryListKey(dir), name).Result(); err != nil || !member { + return false, err + } + // The lookup may have missed on a lagging replica. The list of an entry the + // master still holds is not touched, not even to be put back afterwards. + if exists, err := store.existsOnMaster(ctx, string(fullpath)); err != nil || exists != 0 { + return false, err + } + return store.removeOrphanedDirectoryListMember(ctx, util.FullPath(dir), name) +} + +// removeOrphanedDirectoryListMember reports whether it removed the member for good. +func (store *UniversalRedisStore) removeOrphanedDirectoryListMember(ctx context.Context, dirPath util.FullPath, fileName string) (removed bool, err error) { // survive the listing request being canceled mid-repair ctx = context.WithoutCancel(ctx) dirListKey := genDirectoryListKey(string(dirPath)) path := util.NewFullPath(string(dirPath), fileName) - if _, err := store.Client.SRem(ctx, dirListKey, fileName).Result(); err != nil { - return + // nothing removed leaves nothing to put back + if n, err := store.Client.SRem(ctx, dirListKey, fileName).Result(); err != nil || n == 0 { + return false, err } // a value present again here belongs to a concurrent recreate whose SAdd raced our SRem - exists, err := store.Client.Exists(ctx, string(path)).Result() + exists, err := store.existsOnMaster(ctx, string(path)) if err == nil && exists == 0 { // empty sets self-delete, so a present child index holds children a recursive delete still needs to reach - children, childrenErr := store.Client.Exists(ctx, genDirectoryListKey(string(path))).Result() + children, childrenErr := store.existsOnMaster(ctx, genDirectoryListKey(string(path))) if childrenErr == nil && children == 0 { - return + return true, nil } } - if err := store.Client.SAdd(ctx, dirListKey, fileName).Err(); err != nil { + // Nothing else puts the member of a live entry back, so a failed restore + // goes on in the background until redis takes it or the store closes. + restore := func() error { return store.Client.SAdd(ctx, dirListKey, fileName).Err() } + if err = restore(); err != nil { glog.V(0).InfofCtx(ctx, "restore %s in %s: %v", fileName, dirPath, err) + go util.RetryUntil("restore "+string(path), restore, func(err error) bool { return !errors.Is(err, redis.ErrClosed) }) + return false, fmt.Errorf("restore %s in %s: %w", fileName, dirPath, err) } + return false, nil +} + +// existsOnMaster runs EXISTS as a script, which always runs on the key's master: +// with replica reads (useReadOnly, routeByLatency) a plain EXISTS can hit a lagging +// replica and misread a live value as absent. +func (store *UniversalRedisStore) existsOnMaster(ctx context.Context, key string) (int64, error) { + return store.Client.Eval(ctx, "return redis.call('EXISTS', KEYS[1])", []string{key}).Int64() } func genDirectoryListKey(dir string) (dirList string) { diff --git a/weed/filer/redis/universal_redis_store_test.go b/weed/filer/redis/universal_redis_store_test.go index 64440c7b32..de3edea28b 100644 --- a/weed/filer/redis/universal_redis_store_test.go +++ b/weed/filer/redis/universal_redis_store_test.go @@ -2,9 +2,11 @@ package redis import ( "context" + "errors" "fmt" "os" "slices" + "sync/atomic" "testing" "time" @@ -140,6 +142,31 @@ func TestListDirectoryEntriesFillsThePagePastOrphanedMembers(t *testing.T) { } } +// A lookup finds nothing once a value is gone, and so cannot reach the member +// it left in the directory list; RemoveExpiredLeftover does. +func TestRemoveExpiredLeftoverRemovesTheMemberAGoneValueLeft(t *testing.T) { + store, dir := newTestStore(t) + ctx := context.Background() + + insertTestEntry(t, store, dir.Child("alive")) + insertTestEntry(t, store, dir.Child("orphan")) + if err := store.Client.Del(ctx, string(dir.Child("orphan"))).Err(); err != nil { + t.Fatalf("drop value key: %v", err) + } + + for _, name := range []string{"alive", "never-written"} { + if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child(name)); err != nil || removed { + t.Fatalf("RemoveExpiredLeftover %s = %v, %v, want nothing removed", name, removed, err) + } + } + if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("orphan")); err != nil || !removed { + t.Fatalf("RemoveExpiredLeftover = %v, %v, want the member removed", removed, err) + } + if members := indexMembers(t, store, dir); len(members) != 1 || members[0] != "alive" { + t.Fatalf("directory index holds %v, want [alive]", members) + } +} + func TestRemoveOrphanedDirectoryListMemberKeepsRecreatedEntry(t *testing.T) { store, dir := newTestStore(t) @@ -156,6 +183,57 @@ func TestRemoveOrphanedDirectoryListMemberKeepsRecreatedEntry(t *testing.T) { } } +// failingCommands fails the next commands of one name before they reach redis. +type failingCommands struct { + name string + left atomic.Int32 +} + +func (h *failingCommands) DialHook(next redis.DialHook) redis.DialHook { return next } + +func (h *failingCommands) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { + return next +} + +func (h *failingCommands) ProcessHook(next redis.ProcessHook) redis.ProcessHook { + return func(ctx context.Context, cmd redis.Cmder) error { + if cmd.Name() == h.name && h.left.Add(-1) >= 0 { + err := errors.New("connection reset by peer") + cmd.SetErr(err) + return err + } + return next(ctx, cmd) + } +} + +// The repair takes the member of an entry that is live again and has to put it +// back, since nothing else does. A restore that fails is reported and goes on +// until redis takes it. +func TestRemoveOrphanedDirectoryListMemberRestoresOnceRedisRecovers(t *testing.T) { + store, dir := newTestStore(t) + ctx := context.Background() + insertTestEntry(t, store, dir.Child("recreated")) + failing := &failingCommands{name: "sadd"} + store.Client.AddHook(failing) + + failing.left.Store(1 << 20) + if removed, err := store.removeOrphanedDirectoryListMember(ctx, dir, "recreated"); err == nil || removed { + t.Fatalf("repair = %v, %v, want the failed restore reported", removed, err) + } + if members := indexMembers(t, store, dir); len(members) != 0 { + t.Fatalf("directory index holds %v while redis refuses the restore", members) + } + + failing.left.Store(0) + for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(50 * time.Millisecond) { + if members := indexMembers(t, store, dir); len(members) == 1 && members[0] == "recreated" { + return + } else if time.Now().After(deadline) { + t.Fatalf("directory index holds %v, want [recreated] once redis recovers", members) + } + } +} + func TestRemoveOrphanedDirectoryListMemberKeepsDirectoryWithChildren(t *testing.T) { store, dir := newTestStore(t) diff --git a/weed/filer/redis2/universal_redis_store.go b/weed/filer/redis2/universal_redis_store.go index c5ee872337..8ff4254da5 100644 --- a/weed/filer/redis2/universal_redis_store.go +++ b/weed/filer/redis2/universal_redis_store.go @@ -280,10 +280,33 @@ func (store *UniversalRedis2Store) getEntries(ctx context.Context, dirPath util. return gets } -func (store *UniversalRedis2Store) removeOrphanedDirectoryListMember(ctx context.Context, dirPath util.FullPath, fileName string) { +// RemoveExpiredLeftover removes the directory list member of an entry whose +// value redis expired; a lookup of that entry has nothing else to find it by. +func (store *UniversalRedis2Store) RemoveExpiredLeftover(ctx context.Context, fullpath util.FullPath) (removed bool, err error) { + dir, name := fullpath.DirAndName() + if name == "" { + return false, nil + } + // Most misses are of a name that was never written: no member, nothing to do. + if err := store.Client.ZScore(ctx, store.getKey(genDirectoryListKey(dir)), name).Err(); err != nil { + if err == redis.Nil { + return false, nil + } + return false, err + } + // The lookup may have missed on a lagging replica. The list of an entry the + // master still holds is not touched, not even to be put back afterwards. + if exists, err := store.existsOnMaster(ctx, store.getKey(string(fullpath))); err != nil || exists != 0 { + return false, err + } + return store.removeOrphanedDirectoryListMember(ctx, util.FullPath(dir), name) +} + +// removeOrphanedDirectoryListMember reports whether it removed the member for good. +func (store *UniversalRedis2Store) removeOrphanedDirectoryListMember(ctx context.Context, dirPath util.FullPath, fileName string) (removed bool, err error) { // a directory converted to super large after accumulating members still has a legacy index if store.isSuperLargeDirectory(string(dirPath)) { - return + return false, nil } // survive the listing request being canceled mid-repair @@ -292,8 +315,9 @@ func (store *UniversalRedis2Store) removeOrphanedDirectoryListMember(ctx context dirListKey := store.getKey(genDirectoryListKey(string(dirPath))) path := util.NewFullPath(string(dirPath), fileName) - if err := store.Client.ZRem(ctx, dirListKey, fileName).Err(); err != nil { - return + // nothing removed leaves nothing to put back + if n, err := store.Client.ZRem(ctx, dirListKey, fileName).Result(); err != nil || n == 0 { + return false, err } // InsertEntry writes the value before adding the member, so a value present @@ -305,13 +329,19 @@ func (store *UniversalRedis2Store) removeOrphanedDirectoryListMember(ctx context // so a present index holds children a recursive delete still needs to reach children, childrenErr := store.existsOnMaster(ctx, store.getKey(genDirectoryListKey(string(path)))) if childrenErr == nil && children == 0 { - return + return true, nil } } - if err := store.Client.ZAddNX(ctx, dirListKey, redis.Z{Score: 0, Member: fileName}).Err(); err != nil { + // Nothing else puts the member of a live entry back, so a failed restore + // goes on in the background until redis takes it or the store closes. + restore := func() error { return store.Client.ZAddNX(ctx, dirListKey, redis.Z{Score: 0, Member: fileName}).Err() } + if err = restore(); err != nil { glog.V(0).InfofCtx(ctx, "restore %s in %s: %v", fileName, dirPath, err) + go util.RetryUntil("restore "+string(path), restore, func(err error) bool { return !errors.Is(err, redis.ErrClosed) }) + return false, fmt.Errorf("restore %s in %s: %w", fileName, dirPath, err) } + return false, nil } const ( diff --git a/weed/filer/redis2/universal_redis_store_test.go b/weed/filer/redis2/universal_redis_store_test.go index e8295eb7b1..5ee3c4ef2f 100644 --- a/weed/filer/redis2/universal_redis_store_test.go +++ b/weed/filer/redis2/universal_redis_store_test.go @@ -5,14 +5,17 @@ import ( "crypto/fips140" "crypto/sha1" "encoding/hex" + "errors" "fmt" "os" + "sync/atomic" "testing" "time" "github.com/redis/go-redis/v9" "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/util" ) @@ -222,6 +225,56 @@ func TestListDirectoryEntriesRemovesIndexMembersExpiredByRedis(t *testing.T) { } } +// A lookup finds nothing once redis has expired a value, and so cannot reach +// the member it left in the directory list; RemoveExpiredLeftover does. +func TestRemoveExpiredLeftoverRemovesTheMemberRedisLeft(t *testing.T) { + for _, keyPrefix := range []string{"", "sw:"} { + t.Run("keyPrefix="+keyPrefix, func(t *testing.T) { + store, dir := newTestStore(t, keyPrefix) + ctx := context.Background() + + insertTestEntry(t, store, dir.Child("expired"), 1) + insertTestEntry(t, store, dir.Child("live"), 0) + deadline := time.Now().Add(5 * time.Second) + for { + exists, err := store.Client.Exists(ctx, store.getKey(string(dir.Child("expired")))).Result() + if err != nil { + t.Fatalf("check value key: %v", err) + } + if exists == 0 { + break + } + if time.Now().After(deadline) { + t.Fatal("redis did not expire the value key") + } + time.Sleep(50 * time.Millisecond) + } + + if _, err := store.FindEntry(ctx, dir.Child("expired")); err != filer_pb.ErrNotFound { + t.Fatalf("FindEntry = %v, want not found", err) + } + if members := indexMembers(t, store, dir); len(members) != 2 { + t.Fatalf("directory index holds %v after the lookup, want the expired member left in it", members) + } + + for _, name := range []string{"live", "never-written"} { + if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child(name)); err != nil || removed { + t.Fatalf("RemoveExpiredLeftover %s = %v, %v, want nothing removed", name, removed, err) + } + } + if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("expired")); err != nil || !removed { + t.Fatalf("RemoveExpiredLeftover = %v, %v, want the member removed", removed, err) + } + if members := indexMembers(t, store, dir); len(members) != 1 || members[0] != "live" { + t.Fatalf("directory index holds %v, want only the live entry", members) + } + if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("expired")); err != nil || removed { + t.Fatalf("second RemoveExpiredLeftover = %v, %v, want nothing left to remove", removed, err) + } + }) + } +} + // logically expired (Crtime + TtlSec long past) while the physical key survives, // because the redis TTL re-arms from the SET time func insertLogicallyExpiredTestEntry(t *testing.T, store *UniversalRedis2Store, path util.FullPath) { @@ -512,3 +565,89 @@ func TestInsertEntryOverAnExistingEntryReplacesIt(t *testing.T) { }) } } + +// A lookup can miss an entry the master holds, on a lagging replica. Its list +// is then not touched at all: removing the member and putting it back would +// reset the score given to it here. +func TestRemoveExpiredLeftoverLeavesTheListOfALiveEntryAlone(t *testing.T) { + store, dir := newTestStore(t, "") + ctx := context.Background() + insertTestEntry(t, store, dir.Child("live"), 0) + dirListKey := store.getKey(genDirectoryListKey(string(dir))) + if err := store.Client.ZAdd(ctx, dirListKey, redis.Z{Score: 7, Member: "live"}).Err(); err != nil { + t.Fatalf("mark the member: %v", err) + } + t.Cleanup(func() { store.Client.ZAdd(ctx, dirListKey, redis.Z{Score: 0, Member: "live"}) }) + + if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("live")); err != nil || removed { + t.Fatalf("RemoveExpiredLeftover = %v, %v, want nothing removed", removed, err) + } + if score, err := store.Client.ZScore(ctx, dirListKey, "live").Result(); err != nil || score != 7 { + t.Fatalf("member score = %v, %v, want the list of a live entry left alone", score, err) + } +} + +// failingCommands fails the next commands of one name before they reach redis. +type failingCommands struct { + name string + left atomic.Int32 +} + +func (h *failingCommands) DialHook(next redis.DialHook) redis.DialHook { return next } + +func (h *failingCommands) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { + return next +} + +func (h *failingCommands) ProcessHook(next redis.ProcessHook) redis.ProcessHook { + return func(ctx context.Context, cmd redis.Cmder) error { + if cmd.Name() == h.name && h.left.Add(-1) >= 0 { + err := errors.New("connection reset by peer") + cmd.SetErr(err) + return err + } + return next(ctx, cmd) + } +} + +// The repair takes the member of an entry that is live again and has to put it +// back, since nothing else does. A restore that fails is reported and goes on +// until redis takes it. +func TestRemoveOrphanedDirectoryListMemberRestoresOnceRedisRecovers(t *testing.T) { + store, dir := newTestStore(t, "") + ctx := context.Background() + insertTestEntry(t, store, dir.Child("recreated"), 0) + failing := &failingCommands{name: "zadd"} + store.Client.AddHook(failing) + + failing.left.Store(1 << 20) + if removed, err := store.removeOrphanedDirectoryListMember(ctx, dir, "recreated"); err == nil || removed { + t.Fatalf("repair = %v, %v, want the failed restore reported", removed, err) + } + if members := indexMembers(t, store, dir); len(members) != 0 { + t.Fatalf("directory index holds %v while redis refuses the restore", members) + } + + failing.left.Store(0) + for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(50 * time.Millisecond) { + if members := indexMembers(t, store, dir); len(members) == 1 && members[0] == "recreated" { + return + } else if time.Now().After(deadline) { + t.Fatalf("directory index holds %v, want [recreated] once redis recovers", members) + } + } +} + +func TestRemoveExpiredLeftoverReportsAFailedRemoval(t *testing.T) { + store, dir := newTestStore(t, "") + ctx := context.Background() + dirListKey := store.getKey(genDirectoryListKey(string(dir))) + if err := store.Client.Set(ctx, dirListKey, "not a sorted set", 0).Err(); err != nil { + t.Fatalf("set %s: %v", dirListKey, err) + } + t.Cleanup(func() { store.Client.Del(ctx, dirListKey) }) + + if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("expired")); err == nil || removed { + t.Fatalf("RemoveExpiredLeftover = %v, %v, want the failed removal reported", removed, err) + } +} diff --git a/weed/server/filer_grpc_server.go b/weed/server/filer_grpc_server.go index f2908c676f..7221de0204 100644 --- a/weed/server/filer_grpc_server.go +++ b/weed/server/filer_grpc_server.go @@ -57,6 +57,7 @@ func (fs *FilerServer) LookupDirectoryEntry(ctx context.Context, req *filer_pb.L entry, logTsNs, err := fs.fencedFindEntry(ctx, util.JoinPath(req.Directory, req.Name)) if err == filer_pb.ErrNotFound { + fs.filer.RemoveExpiredLeftover(ctx, util.JoinPath(req.Directory, req.Name)) return &filer_pb.LookupDirectoryEntryResponse{LogTsNs: logTsNs, LogSignature: fs.filer.Signature}, err } if err != nil { diff --git a/weed/server/filer_grpc_server_lookup_expired_test.go b/weed/server/filer_grpc_server_lookup_expired_test.go new file mode 100644 index 0000000000..359ce97432 --- /dev/null +++ b/weed/server/filer_grpc_server_lookup_expired_test.go @@ -0,0 +1,45 @@ +package weed_server + +import ( + "context" + "errors" + "slices" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// leftoverTestStore stands for a store whose rows expire on their own. +type leftoverTestStore struct { + *renameTestStore + asked []util.FullPath +} + +func (s *leftoverTestStore) RemoveExpiredLeftover(_ context.Context, p util.FullPath) (bool, error) { + s.asked = append(s.asked, p) + return false, nil +} + +// A lookup that finds nothing under a TTL rule may be of an entry such a +// store expired, which only the store can clear the rest of. +func TestLookupMissUnderATTLRuleAsksTheStoreForWhatExpiryLeft(t *testing.T) { + fs, store := newTxnTestServer(t, nil) + leaving := &leftoverTestStore{renameTestStore: store} + fs.filer.Store = filer.NewFilerStoreWrapper(leaving) + fs.filer.FilerConf = filer.NewFilerConf() + if err := fs.filer.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "1h"}); err != nil { + t.Fatal(err) + } + + for _, bucket := range []string{"cam", "other"} { + _, err := fs.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{Directory: "/buckets/" + bucket + "/day1", Name: "a.mp4"}) + if !errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("lookup in %s: %v, want not found", bucket, err) + } + } + if want := []util.FullPath{"/buckets/cam/day1/a.mp4"}; !slices.Equal(leaving.asked, want) { + t.Fatalf("store asked about %v, want %v", leaving.asked, want) + } +}