mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
redis3: remove names left by expired entries, fix skip-list split and listing (#13408)
* redis3: a listing removes the names of expired entries from the directory A listing skipped the name of an entry whose value redis expired and left it in the directory's list for good, so the list key also outlived the directory's last entry. For an entry past its TTL it ran ZREM on the list, which in this store is a string key, so that name stayed as well. Both now leave the directory's list once the walk ends, under the list's lock and only when the master holds no value for the name, so an insert that wrote its value first keeps its name. An entry past its TTL is deleted only if it still holds the bytes the listing judged expired. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: a lookup removes what a redis-expired entry left behind The filer asks a store that implements ExpiredLeftoverStore to clean up after a lookup that missed under a TTL rule, as the redis and redis2 stores do. redis3 now removes the name from the directory's list too, checking the list first so a miss on a name never written costs only the reads of the list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: key the upper half of a split node by its smallest name When a full node splits and the new name goes to the lower half, the upper half was keyed by that new name, which it does not hold. Deleting the name then matched the upper node by key and removed nothing, so the name stayed listed, and listings from a start name could come back out of order. Only a directory list of more than one node splits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: list from a start name inside an earlier node A listing from a start name that falls inside a node, rather than on a node's key, began at the next node and skipped the rest of the node that holds the start name. A paged directory listing resumes from the last name it returned, so every page after the first lost names once the directory's list had more than one node. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: check a lookup's name against the one node that would hold it The check that a missed name is still listed walked the list from that name, which fetched the rest of its node, up to a million names, to look at the first. It now asks that node for the one name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: stop a list change on a failed read of a node's smallest name NodeMin returned "" for a failed read as for an empty node. Deleting a node's key name then dropped the whole node with the names it still held, and a split keyed a node by the empty name. It now returns the error, and both stop on it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: an update that finds its value expired lists the name again UpdateEntry only wrote the value. When redis expired the value between the caller's read and the update, a lookup or listing could take the name out of the directory in between, and the update left a live entry that no listing shows. The value is now written by a script that also reports whether one was stored, and an update that found none adds the name back, under the list's lock as an insert does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: read a split node's new smallest name before changing the list A split that failed this read had already unlinked the node and saved the new lower node, and returned before the list header was saved, so the names of the node were no longer reachable. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: return a failed read of a node's membership A failed read passed for a missing name: a lookup's leftover check reported no leftover, and a delete returned success with the name still listed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: take back an update's value when listing its name fails An update that found its value expired wrote it again and then listed the name. If listing the name failed, the value stayed, so a retry found it stored and returned without listing the name. The value is now deleted again if it is still the one written. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: stop a list change on a failed count of a node's names NodeSize and NodeInnerPosition read 0 from a failed ZLEXCOUNT. A delete then took the node for emptied and dropped it with the names it still held, and a split added the name in a node of its own ahead of the names before it, so listings came back out of order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: read the directory list from the masters when changing it With useReadOnly or routeByLatency, redis_cluster3 sent the reads of a list change to replicas. A lagging replica could miss a node's other names, and the delete that read it dropped the node with them; a listing or a lookup that removes an expired name now runs that delete too. List changes and the EXISTS checks before them go through a second cluster client that reads from the masters, created only when the store reads from replicas. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: list an expired update's name before writing its value back An update that wrote back an expired value and then failed to list the name deleted the value again when it still held the update's bytes. A concurrent write of the same bytes was deleted with it, and a failed delete or a concurrent update of other bytes left the value without its name for a retry that no longer looked. The update now writes with SET XX. When the value is missing, it lists the name and then writes the value under the list's lock, which the removal of an expired name also takes. A failure leaves the value missing, so the retry lists the name again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: list an updated name again when the list lock's lease ran out An update that finds its value missing lists the name and writes the value under the list lock. If the write outlasts the lock's lease, another filer's cleanup can take the lock, see no value and remove the name before the value lands, leaving a value no listing shows. Unlock now reports a lost lease, and the name is then listed again under a new lock. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: list a cleaned-up name again when the list lock's lease ran out A listing or lookup removes a name after finding its value missing under the list lock. If the removal outlasts the lock's lease, an update can list the name and write its value in between, and the removal then takes out the name of a live value. Unlock now reports a lost lease, and the name is then listed again; if its value is still missing, the next listing removes it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: list the name again when a change fails after the lease ran out A cleanup that lost its lease could remove the name from its node and then fail on the next read. The failed change skipped the lease check, so the name of a value written in between stayed removed. The lease is now checked whenever a write or check ran under the lock, and the change's own error is kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: retry listing a name again after the lease ran out Listing the name again after a lost lease is the only thing that lists a value another filer wrote in between. A transient failure of that one attempt left the value unlisted, so it is now retried. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * redis3: list an inserted name again when the list lock's lease ran out An insert's list change made after the lease ran out could be overwritten by another filer's change based on an earlier read of the list, dropping the name while its value stays stored. Every insertChild now ends with the lease check, so the name is listed again, as an update's already was. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
63c50b8cfe
commit
0ce344d559
7 files changed
+904
-52
No files matched your search
@@ -113,7 +113,10 @@ func (nl *ItemList) WriteName(name string) error {
|
||||
}
|
||||
|
||||
// case 2.3
|
||||
x := nl.NodeInnerPosition(prevNodeReference, name)
|
||||
x, err := nl.NodeInnerPosition(prevNodeReference, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
y := nodeSize - x
|
||||
addToX := x <= y
|
||||
// add to a new node
|
||||
@@ -124,6 +127,12 @@ func (nl *ItemList) WriteName(name string) error {
|
||||
return nil
|
||||
}
|
||||
if addToX {
|
||||
// current Y keeps the names after name and is keyed by the smallest of them,
|
||||
// read before anything is changed
|
||||
minName, err := nl.NodeMin(prevNodeReference, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// collect names before name, add them to X
|
||||
namesToX, err := nl.NodeRangeBeforeExclusive(prevNodeReference, name)
|
||||
if err != nil {
|
||||
@@ -144,7 +153,7 @@ func (nl *ItemList) WriteName(name string) error {
|
||||
}
|
||||
|
||||
// point skip list to current Y
|
||||
if err := nl.ItemAdd(lookupKey, prevNodeReference.ElementPointer); err != nil {
|
||||
if err := nl.ItemAdd([]byte(minName), prevNodeReference.ElementPointer); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@@ -170,7 +179,10 @@ func (nl *ItemList) WriteName(name string) error {
|
||||
|
||||
// case 2.4
|
||||
if nextNode != nil {
|
||||
nodeSize := nl.NodeSize(nextNode.Reference())
|
||||
nodeSize, err := nl.NodeSize(nextNode.Reference())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if nodeSize < nl.batchSize {
|
||||
if id, err := nl.skipList.DeleteByKey(nextNode.Key); err != nil {
|
||||
return err
|
||||
@@ -245,7 +257,10 @@ func (nl *ItemList) DeleteName(name string) error {
|
||||
if err := nl.NodeDeleteMember(nextNode.Reference(), name); err != nil {
|
||||
return err
|
||||
}
|
||||
minName := nl.NodeMin(nextNode.Reference())
|
||||
minName, err := nl.NodeMin(nextNode.Reference(), name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if minName == "" {
|
||||
return nl.NodeDelete(nextNode.Reference())
|
||||
}
|
||||
@@ -271,22 +286,28 @@ func (nl *ItemList) DeleteName(name string) error {
|
||||
// case 2.1
|
||||
return nil
|
||||
}
|
||||
if !nl.NodeContainsItem(prevNode.Reference(), name) {
|
||||
return nil
|
||||
if contains, err := nl.NodeContainsItem(prevNode.Reference(), name); err != nil || !contains {
|
||||
return err
|
||||
}
|
||||
|
||||
// case 3
|
||||
if err := nl.NodeDeleteMember(prevNode.Reference(), name); err != nil {
|
||||
return err
|
||||
}
|
||||
prevSize := nl.NodeSize(prevNode.Reference())
|
||||
prevSize, err := nl.NodeSize(prevNode.Reference())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if prevSize == 0 {
|
||||
if _, err := nl.skipList.DeleteByKey(prevNode.Key); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
nextSize := nl.NodeSize(nextNode.Reference())
|
||||
nextSize, err := nl.NodeSize(nextNode.Reference())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if nextSize > 0 && prevSize+nextSize < nl.batchSize {
|
||||
// case 3.1 merge nextNode and prevNode
|
||||
if _, err := nl.skipList.DeleteByKey(nextNode.Key); err != nil {
|
||||
@@ -315,6 +336,11 @@ func (nl *ItemList) ListNames(startFrom string, visitNamesFn func(name string) b
|
||||
}
|
||||
if found && bytes.Compare(nextNode.Key, lookupKey) == 0 {
|
||||
prevNode = nil
|
||||
} else if found {
|
||||
// the names from startFrom up to the next node's key are in the node before it
|
||||
if prevNode, err = nl.skipList.LoadElement(nextNode.Prev); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
prevNode, err = nl.skipList.GetLargestNode()
|
||||
@@ -342,6 +368,28 @@ func (nl *ItemList) ListNames(startFrom string, visitNamesFn func(name string) b
|
||||
return nil
|
||||
}
|
||||
|
||||
// ContainsName reports whether name is in the list, reading only the node that would hold it.
|
||||
func (nl *ItemList) ContainsName(name string) (bool, error) {
|
||||
lookupKey := []byte(name)
|
||||
_, nextNode, found, err := nl.skipList.FindGreaterOrEqual(lookupKey)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if found && bytes.Compare(nextNode.Key, lookupKey) == 0 {
|
||||
return true, nil
|
||||
}
|
||||
var node *skiplist.SkipListElement
|
||||
if found {
|
||||
node, err = nl.skipList.LoadElement(nextNode.Prev)
|
||||
} else {
|
||||
node, err = nl.skipList.GetLargestNode()
|
||||
}
|
||||
if err != nil || node == nil {
|
||||
return false, err
|
||||
}
|
||||
return nl.NodeContainsItem(node.Reference(), name)
|
||||
}
|
||||
|
||||
func (nl *ItemList) IsEmpty() bool {
|
||||
return nl.skipList.StartLevels[0] == nil
|
||||
}
|
||||
@@ -371,24 +419,22 @@ func (nl *ItemList) RemoteAllListElement() error {
|
||||
|
||||
}
|
||||
|
||||
func (nl *ItemList) NodeContainsItem(node *skiplist.SkipListElementReference, item string) bool {
|
||||
func (nl *ItemList) NodeContainsItem(node *skiplist.SkipListElementReference, item string) (bool, error) {
|
||||
key := fmt.Sprintf("%s%dm", nl.prefix, node.ElementPointer)
|
||||
_, err := nl.client.ZScore(context.Background(), key, item).Result()
|
||||
if err == redis.Nil {
|
||||
return false
|
||||
return false, nil
|
||||
}
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
func (nl *ItemList) NodeSize(node *skiplist.SkipListElementReference) int {
|
||||
func (nl *ItemList) NodeSize(node *skiplist.SkipListElementReference) (int, error) {
|
||||
if node == nil {
|
||||
return 0
|
||||
return 0, nil
|
||||
}
|
||||
key := fmt.Sprintf("%s%dm", nl.prefix, node.ElementPointer)
|
||||
return int(nl.client.ZLexCount(context.Background(), key, "-", "+").Val())
|
||||
n, err := nl.client.ZLexCount(context.Background(), key, "-", "+").Result()
|
||||
return int(n), err
|
||||
}
|
||||
|
||||
func (nl *ItemList) NodeAddMember(node *skiplist.SkipListElementReference, names ...string) error {
|
||||
@@ -412,24 +458,25 @@ func (nl *ItemList) NodeDelete(node *skiplist.SkipListElementReference) error {
|
||||
return nl.client.Del(context.Background(), key).Err()
|
||||
}
|
||||
|
||||
func (nl *ItemList) NodeInnerPosition(node *skiplist.SkipListElementReference, name string) int {
|
||||
func (nl *ItemList) NodeInnerPosition(node *skiplist.SkipListElementReference, name string) (int, error) {
|
||||
key := fmt.Sprintf("%s%dm", nl.prefix, node.ElementPointer)
|
||||
return int(nl.client.ZLexCount(context.Background(), key, "-", "("+name).Val())
|
||||
n, err := nl.client.ZLexCount(context.Background(), key, "-", "("+name).Result()
|
||||
return int(n), err
|
||||
}
|
||||
|
||||
func (nl *ItemList) NodeMin(node *skiplist.SkipListElementReference) string {
|
||||
// NodeMin returns the node's smallest name after the given one, or "" if there is none.
|
||||
func (nl *ItemList) NodeMin(node *skiplist.SkipListElementReference, after string) (string, error) {
|
||||
key := fmt.Sprintf("%s%dm", nl.prefix, node.ElementPointer)
|
||||
slice := nl.client.ZRangeByLex(context.Background(), key, &redis.ZRangeBy{
|
||||
Min: "-",
|
||||
slice, err := nl.client.ZRangeByLex(context.Background(), key, &redis.ZRangeBy{
|
||||
Min: "(" + after,
|
||||
Max: "+",
|
||||
Offset: 0,
|
||||
Count: 1,
|
||||
}).Val()
|
||||
if len(slice) > 0 {
|
||||
s := slice[0]
|
||||
return s
|
||||
}).Result()
|
||||
if err != nil || len(slice) == 0 {
|
||||
return "", err
|
||||
}
|
||||
return ""
|
||||
return slice[0], nil
|
||||
}
|
||||
|
||||
func (nl *ItemList) NodeScanInclusiveAfter(node *skiplist.SkipListElementReference, startFrom string, visitNamesFn func(name string) bool) bool {
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
package redis3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// itemListOp runs fn on the directory list of dir with a small batch size, so
|
||||
// a few names already split it into several nodes, and saves what fn changed.
|
||||
func itemListOp(t *testing.T, store *UniversalRedis3Store, key string, fn func(nl *ItemList) error) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
data, err := store.Client.Get(ctx, key).Result()
|
||||
if err != nil && err != redis.Nil {
|
||||
t.Fatalf("get %s: %v", key, err)
|
||||
}
|
||||
nl := LoadItemList([]byte(data), key, store.Client, newSkipListElementStore(key, store.Client), 2)
|
||||
if err := fn(nl); err != nil {
|
||||
t.Fatalf("item list %s: %v", key, err)
|
||||
}
|
||||
if nl.HasChanges() {
|
||||
if err := store.Client.Set(ctx, key, nl.ToBytes(), 0).Err(); err != nil {
|
||||
t.Fatalf("set %s: %v", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func itemListNames(t *testing.T, store *UniversalRedis3Store, key string, startFrom string) string {
|
||||
t.Helper()
|
||||
var names []string
|
||||
itemListOp(t, store, key, func(nl *ItemList) error {
|
||||
return nl.ListNames(startFrom, func(name string) bool {
|
||||
names = append(names, name)
|
||||
return true
|
||||
})
|
||||
})
|
||||
return fmt.Sprint(names)
|
||||
}
|
||||
|
||||
// A full node [a c] splits on b into [a b] and [c]. The upper node has to be
|
||||
// keyed by c: keyed by b, deleting b found it there and left b listed.
|
||||
func TestItemListSplitKeysTheUpperNodeByItsSmallestName(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
for _, name := range []string{"a", "c", "b"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.DeleteName("b") })
|
||||
if got := itemListNames(t, store, key, ""); got != "[a c]" {
|
||||
t.Fatalf("after deleting b: %s, want [a c]", got)
|
||||
}
|
||||
}
|
||||
|
||||
// With nodes [a b] and [c], a listing from b starts inside the first node. A
|
||||
// paged listing resumes from the last name it returned, so it skipped what
|
||||
// that node held after it.
|
||||
func TestItemListListsFromInsideAnEarlierNode(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
for _, name := range []string{"a", "b", "c"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
if got := itemListNames(t, store, key, "b"); got != "[b c]" {
|
||||
t.Fatalf("list from b: %s, want [b c]", got)
|
||||
}
|
||||
if got := itemListNames(t, store, key, "a0"); got != "[b c]" {
|
||||
t.Fatalf("list from a0: %s, want [b c]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestItemListContainsName(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
// nodes [b d] and [f]
|
||||
for _, name := range []string{"b", "d", "f"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
for name, want := range map[string]bool{"a": false, "b": true, "c": false, "d": true, "e": false, "f": true, "g": false} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error {
|
||||
got, err := nl.ContainsName(name)
|
||||
if err == nil && got != want {
|
||||
t.Errorf("ContainsName(%q) = %v, want %v", name, got, want)
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A failed read of the node that would hold a name is an error, not a missing name.
|
||||
func TestItemListContainsNameFailingARead(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
for _, name := range []string{"b", "d"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
|
||||
failing := &failingCommands{name: "zscore"}
|
||||
store.Client.AddHook(failing)
|
||||
failing.left.Store(1)
|
||||
data, err := store.Client.Get(context.Background(), key).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("get %s: %v", key, err)
|
||||
}
|
||||
nl := LoadItemList([]byte(data), key, store.Client, newSkipListElementStore(key, store.Client), 2)
|
||||
if got, err := nl.ContainsName("d"); err == nil {
|
||||
t.Fatalf("ContainsName = %v, nil although reading the node failed", got)
|
||||
}
|
||||
failing.left.Store(1)
|
||||
if err := nl.DeleteName("d"); err == nil {
|
||||
t.Fatalf("DeleteName succeeded although reading the node failed")
|
||||
}
|
||||
}
|
||||
|
||||
// failingCommands lets the next skip commands of one name through, then fails
|
||||
// the next left of them before they reach redis.
|
||||
type failingCommands struct {
|
||||
name string
|
||||
skip atomic.Int32
|
||||
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.skip.Add(-1) < 0 && h.left.Add(-1) >= 0 {
|
||||
err := errors.New("connection reset by peer")
|
||||
cmd.SetErr(err)
|
||||
return err
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
// afterCommand runs fn once, right after the first command of one name on key
|
||||
// has reached redis.
|
||||
type afterCommand struct {
|
||||
name string
|
||||
key string
|
||||
fn func()
|
||||
ran atomic.Bool
|
||||
}
|
||||
|
||||
func (h *afterCommand) DialHook(next redis.DialHook) redis.DialHook { return next }
|
||||
|
||||
func (h *afterCommand) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
|
||||
func (h *afterCommand) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
err := next(ctx, cmd)
|
||||
if args := cmd.Args(); cmd.Name() == h.name && len(args) > 1 && args[1] == h.key && h.ran.CompareAndSwap(false, true) {
|
||||
h.fn()
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Deleting the name a node is keyed by reads the node's next smallest name to
|
||||
// key it by. A failed read must not pass for an emptied node, which is dropped
|
||||
// with the names it still holds.
|
||||
func TestItemListDeleteKeepsANodeItFailedToRead(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
for _, name := range []string{"a", "b"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
|
||||
failing := &failingCommands{name: "zrangebylex"}
|
||||
store.Client.AddHook(failing)
|
||||
failing.left.Store(1)
|
||||
data, err := store.Client.Get(context.Background(), key).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("get %s: %v", key, err)
|
||||
}
|
||||
nl := LoadItemList([]byte(data), key, store.Client, newSkipListElementStore(key, store.Client), 2)
|
||||
node := nl.skipList.GetLargestNodeReference()
|
||||
if err := nl.DeleteName("a"); err == nil {
|
||||
t.Fatalf("DeleteName succeeded although reading the node failed")
|
||||
}
|
||||
if n, err := store.Client.ZCard(context.Background(), fmt.Sprintf("%s%dm", key, node.ElementPointer)).Result(); err != nil || n != 1 {
|
||||
t.Fatalf("node holds %d names (err %v), want b kept", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A split that fails to read the node it splits returns before it changes the
|
||||
// list, so the saved list still reaches every name.
|
||||
func TestItemListSplitFailingAReadKeepsEveryName(t *testing.T) {
|
||||
for _, command := range []string{"zrangebylex", "zlexcount"} {
|
||||
t.Run(command, func(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
for _, name := range []string{"a", "c"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
|
||||
failing := &failingCommands{name: command}
|
||||
store.Client.AddHook(failing)
|
||||
for skip := int32(0); ; skip++ {
|
||||
failing.skip.Store(skip)
|
||||
failing.left.Store(1)
|
||||
data, err := store.Client.Get(context.Background(), key).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("get %s: %v", key, err)
|
||||
}
|
||||
nl := LoadItemList([]byte(data), key, store.Client, newSkipListElementStore(key, store.Client), 2)
|
||||
if err := nl.WriteName("b"); err == nil {
|
||||
if err := store.Client.Set(context.Background(), key, nl.ToBytes(), 0).Err(); err != nil {
|
||||
t.Fatalf("set %s: %v", key, err)
|
||||
}
|
||||
break
|
||||
}
|
||||
if got := itemListNames(t, store, key, ""); got != "[a c]" {
|
||||
t.Fatalf("after failing read %d of the split, listed %s, want [a c]", skip+1, got)
|
||||
}
|
||||
}
|
||||
failing.left.Store(0)
|
||||
if got := itemListNames(t, store, key, ""); got != "[a b c]" {
|
||||
t.Fatalf("listed %s, want [a b c]", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Deleting a name counts the names left in its node. A failed count must not
|
||||
// pass for an emptied node, which is dropped with the names it still holds.
|
||||
func TestItemListDeleteKeepsANodeItFailedToCount(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
for _, name := range []string{"a", "b"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
|
||||
failing := &failingCommands{name: "zlexcount"}
|
||||
store.Client.AddHook(failing)
|
||||
failing.left.Store(1)
|
||||
data, err := store.Client.Get(context.Background(), key).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("get %s: %v", key, err)
|
||||
}
|
||||
nl := LoadItemList([]byte(data), key, store.Client, newSkipListElementStore(key, store.Client), 2)
|
||||
if err := nl.DeleteName("b"); err == nil {
|
||||
if err := store.Client.Set(context.Background(), key, nl.ToBytes(), 0).Err(); err != nil {
|
||||
t.Fatalf("set %s: %v", key, err)
|
||||
}
|
||||
t.Errorf("DeleteName succeeded although counting the node failed")
|
||||
}
|
||||
if got := itemListNames(t, store, key, ""); got != "[a]" {
|
||||
t.Fatalf("listed %s, want [a]", got)
|
||||
}
|
||||
}
|
||||
@@ -4,24 +4,34 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
redsync "github.com/go-redsync/redsync/v4"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
const maxNameBatchSizeLimit = 1000000
|
||||
|
||||
func insertChild(ctx context.Context, redisStore *UniversalRedis3Store, key string, name string) error {
|
||||
// insertChild adds name to the list at key. A non-nil write runs under the
|
||||
// list's lock once the name is listed, so no removeChild of the name runs
|
||||
// between the two.
|
||||
func insertChild(ctx context.Context, redisStore *UniversalRedis3Store, key string, name string, write func() error) (err error) {
|
||||
|
||||
// lock and unlock
|
||||
mutex := redisStore.redsync.NewMutex(key + "lock")
|
||||
if err := mutex.Lock(); err != nil {
|
||||
return fmt.Errorf("lock %s: %v", key, err)
|
||||
}
|
||||
relist := false
|
||||
defer func() {
|
||||
mutex.Unlock()
|
||||
if !relist {
|
||||
mutex.Unlock()
|
||||
} else if relistErr := unlockOrRelist(ctx, redisStore, mutex, key, name); err == nil {
|
||||
err = relistErr
|
||||
}
|
||||
}()
|
||||
|
||||
client := redisStore.Client
|
||||
client := redisStore.onMaster()
|
||||
data, err := client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if err != redis.Nil {
|
||||
@@ -31,32 +41,65 @@ func insertChild(ctx context.Context, redisStore *UniversalRedis3Store, key stri
|
||||
store := newSkipListElementStore(key, client)
|
||||
nameList := LoadItemList([]byte(data), key, client, store, maxNameBatchSizeLimit)
|
||||
|
||||
relist = true
|
||||
if err := nameList.WriteName(name); err != nil {
|
||||
glog.ErrorfCtx(ctx, "add %s %s: %v", key, name, err)
|
||||
return err
|
||||
}
|
||||
|
||||
if !nameList.HasChanges() {
|
||||
return nil
|
||||
if nameList.HasChanges() {
|
||||
if err := client.Set(ctx, key, nameList.ToBytes(), 0).Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := client.Set(ctx, key, nameList.ToBytes(), 0).Err(); err != nil {
|
||||
return err
|
||||
if write != nil {
|
||||
return write()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeChild(ctx context.Context, redisStore *UniversalRedis3Store, key string, name string) error {
|
||||
// unlockOrRelist releases mutex after a change to name's listing or value, or a
|
||||
// check of its value, made under it. If the lock's lease ran out first, another
|
||||
// filer may have changed the list in between and dropped name, so name is
|
||||
// listed again: the next listing removes a name without a value, but nothing
|
||||
// lists a value whose name is missing.
|
||||
func unlockOrRelist(ctx context.Context, redisStore *UniversalRedis3Store, mutex *redsync.Mutex, key string, name string) error {
|
||||
if held, err := mutex.Unlock(); held && err == nil {
|
||||
return nil
|
||||
}
|
||||
return util.Retry("relist "+key+" "+name, func() error {
|
||||
return insertChild(ctx, redisStore, key, name, nil)
|
||||
})
|
||||
}
|
||||
|
||||
// removeChild removes name from the list at key. A non-nil keep runs under the
|
||||
// list's lock, so no insertChild of the name runs during it, and a true from it
|
||||
// leaves the name in place.
|
||||
func removeChild(ctx context.Context, redisStore *UniversalRedis3Store, key string, name string, keep func() (bool, error)) (err error) {
|
||||
|
||||
// lock and unlock
|
||||
mutex := redisStore.redsync.NewMutex(key + "lock")
|
||||
if err := mutex.Lock(); err != nil {
|
||||
return fmt.Errorf("lock %s: %v", key, err)
|
||||
}
|
||||
defer mutex.Unlock()
|
||||
relist := false
|
||||
defer func() {
|
||||
if !relist {
|
||||
mutex.Unlock()
|
||||
} else if relistErr := unlockOrRelist(ctx, redisStore, mutex, key, name); err == nil {
|
||||
err = relistErr
|
||||
}
|
||||
}()
|
||||
|
||||
client := redisStore.Client
|
||||
if keep != nil {
|
||||
if kept, err := keep(); err != nil || kept {
|
||||
return err
|
||||
}
|
||||
relist = true
|
||||
}
|
||||
|
||||
client := redisStore.onMaster()
|
||||
data, err := client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if err != redis.Nil {
|
||||
@@ -101,7 +144,7 @@ func removeChildren(ctx context.Context, redisStore *UniversalRedis3Store, key s
|
||||
}
|
||||
defer mutex.Unlock()
|
||||
|
||||
client := redisStore.Client
|
||||
client := redisStore.onMaster()
|
||||
data, err := client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if err != redis.Nil {
|
||||
@@ -129,6 +172,19 @@ func removeChildren(ctx context.Context, redisStore *UniversalRedis3Store, key s
|
||||
|
||||
}
|
||||
|
||||
func hasChild(ctx context.Context, redisStore *UniversalRedis3Store, key string, name string) (bool, error) {
|
||||
client := redisStore.Client
|
||||
data, err := client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if err != redis.Nil {
|
||||
return false, fmt.Errorf("read %s: %v", key, err)
|
||||
}
|
||||
}
|
||||
store := newSkipListElementStore(key, client)
|
||||
nameList := LoadItemList([]byte(data), key, client, store, maxNameBatchSizeLimit)
|
||||
return nameList.ContainsName(name)
|
||||
}
|
||||
|
||||
func listChildren(ctx context.Context, redisStore *UniversalRedis3Store, key string, startFileName string, eachFn func(name string) bool) error {
|
||||
client := redisStore.Client
|
||||
data, err := client.Get(ctx, key).Result()
|
||||
|
||||
@@ -59,6 +59,11 @@ func (store *RedisCluster3Store) initialize(addresses []string, username string,
|
||||
TLSConfig: tlsConfig,
|
||||
}
|
||||
settings.ApplyToCluster(options)
|
||||
if readOnly || routeByLatency {
|
||||
masterOptions := *options
|
||||
masterOptions.ReadOnly, masterOptions.RouteByLatency = false, false
|
||||
store.masterClient = redis.NewClusterClient(&masterOptions)
|
||||
}
|
||||
store.Client = redis.NewClusterClient(options)
|
||||
store.redsync = redsync.New(goredis.NewPool(store.Client))
|
||||
store.keyPrefix = keyPrefix
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package redis3
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer/redis_conf"
|
||||
)
|
||||
|
||||
func TestClusterStoreChangesListsOnMasters(t *testing.T) {
|
||||
for _, routing := range []struct{ readOnly, routeByLatency bool }{{true, false}, {false, true}} {
|
||||
store := &RedisCluster3Store{}
|
||||
if err := store.initialize([]string{"127.0.0.1:1"}, "", "", "", routing.readOnly, routing.routeByLatency, nil, redis_conf.Settings{}); err != nil {
|
||||
t.Fatalf("initialize %+v: %v", routing, err)
|
||||
}
|
||||
if !store.Client.(*redis.ClusterClient).Options().ReadOnly {
|
||||
t.Errorf("%+v: Client does not read from replicas", routing)
|
||||
}
|
||||
if options := store.onMaster().(*redis.ClusterClient).Options(); options.ReadOnly || options.RouteByLatency || options.RouteRandomly {
|
||||
t.Errorf("%+v: list changes read from replicas", routing)
|
||||
}
|
||||
store.Shutdown()
|
||||
}
|
||||
|
||||
store := &RedisCluster3Store{}
|
||||
if err := store.initialize([]string{"127.0.0.1:1"}, "", "", "", false, false, nil, redis_conf.Settings{}); err != nil {
|
||||
t.Fatalf("initialize: %v", err)
|
||||
}
|
||||
if store.onMaster() != store.Client {
|
||||
t.Errorf("a second client without replica reads")
|
||||
}
|
||||
store.Shutdown()
|
||||
}
|
||||
@@ -19,9 +19,20 @@ const (
|
||||
)
|
||||
|
||||
type UniversalRedis3Store struct {
|
||||
Client redis.UniversalClient
|
||||
redsync *redsync.Redsync
|
||||
keyPrefix string
|
||||
Client redis.UniversalClient
|
||||
// set when Client reads from replicas
|
||||
masterClient redis.UniversalClient
|
||||
redsync *redsync.Redsync
|
||||
keyPrefix string
|
||||
}
|
||||
|
||||
// onMaster returns a client that reads every key from its master. A list change
|
||||
// decided on a lagging replica's read can drop names the master holds.
|
||||
func (store *UniversalRedis3Store) onMaster() redis.UniversalClient {
|
||||
if store.masterClient != nil {
|
||||
return store.masterClient
|
||||
}
|
||||
return store.Client
|
||||
}
|
||||
|
||||
func (store *UniversalRedis3Store) getKey(key string) string {
|
||||
@@ -49,6 +60,7 @@ func (store *UniversalRedis3Store) OverwritesAtOnce() bool {
|
||||
}
|
||||
|
||||
var _ filer.OverwritingStore = (*UniversalRedis3Store)(nil)
|
||||
var _ filer.ExpiredLeftoverStore = (*UniversalRedis3Store)(nil)
|
||||
|
||||
func (store *UniversalRedis3Store) BeginTransaction(ctx context.Context) (context.Context, error) {
|
||||
return ctx, nil
|
||||
@@ -69,7 +81,7 @@ func (store *UniversalRedis3Store) InsertEntry(ctx context.Context, entry *filer
|
||||
dir, name := entry.FullPath.DirAndName()
|
||||
|
||||
if name != "" {
|
||||
if err = insertChild(ctx, store, store.getKey(genDirectoryListKey(dir)), name); err != nil {
|
||||
if err = insertChild(ctx, store, store.getKey(genDirectoryListKey(dir)), name, nil); err != nil {
|
||||
return fmt.Errorf("persisting %s in parent dir: %v", entry.FullPath, err)
|
||||
}
|
||||
}
|
||||
@@ -77,15 +89,23 @@ func (store *UniversalRedis3Store) InsertEntry(ctx context.Context, entry *filer
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *UniversalRedis3Store) doInsertEntry(ctx context.Context, entry *filer.Entry) error {
|
||||
func encodeEntry(entry *filer.Entry) ([]byte, error) {
|
||||
value, err := entry.EncodeAttributesAndChunks()
|
||||
if err != nil {
|
||||
return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
|
||||
return nil, fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
|
||||
}
|
||||
|
||||
if len(entry.GetChunks()) > filer.CountEntryChunksForGzip {
|
||||
value = util.MaybeGzipData(value)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (store *UniversalRedis3Store) doInsertEntry(ctx context.Context, entry *filer.Entry) error {
|
||||
value, err := encodeEntry(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = store.Client.Set(ctx, store.getKey(string(entry.FullPath)), value, time.Duration(entry.TtlSec)*time.Second).Err(); err != nil {
|
||||
return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
|
||||
@@ -95,7 +115,29 @@ func (store *UniversalRedis3Store) doInsertEntry(ctx context.Context, entry *fil
|
||||
|
||||
func (store *UniversalRedis3Store) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
|
||||
|
||||
return store.doInsertEntry(ctx, entry)
|
||||
value, err := encodeEntry(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
updated, err := store.Client.SetXX(ctx, store.getKey(string(entry.FullPath)), value, time.Duration(entry.TtlSec)*time.Second).Result()
|
||||
if err != nil {
|
||||
return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
|
||||
}
|
||||
if updated {
|
||||
return nil
|
||||
}
|
||||
|
||||
// The value expired since the caller read it, and a lookup or listing may
|
||||
// have taken its name out of the directory since. The name is listed before
|
||||
// the value is written back, under the lock such a removal takes, so a failure
|
||||
// leaves the value missing and a retry lists the name again.
|
||||
dir, name := entry.FullPath.DirAndName()
|
||||
if name == "" {
|
||||
return store.doInsertEntry(ctx, entry)
|
||||
}
|
||||
return insertChild(ctx, store, store.getKey(genDirectoryListKey(dir)), name, func() error {
|
||||
return store.doInsertEntry(ctx, entry)
|
||||
})
|
||||
}
|
||||
|
||||
func (store *UniversalRedis3Store) FindEntry(ctx context.Context, fullpath util.FullPath) (entry *filer.Entry, err error) {
|
||||
@@ -134,7 +176,7 @@ func (store *UniversalRedis3Store) DeleteEntry(ctx context.Context, fullpath uti
|
||||
dir, name := fullpath.DirAndName()
|
||||
|
||||
if name != "" {
|
||||
if err = removeChild(ctx, store, store.getKey(genDirectoryListKey(dir)), name); err != nil {
|
||||
if err = removeChild(ctx, store, store.getKey(genDirectoryListKey(dir)), name, nil); err != nil {
|
||||
return fmt.Errorf("DeleteEntry %s in parent dir: %v", fullpath, err)
|
||||
}
|
||||
}
|
||||
@@ -175,6 +217,14 @@ func (store *UniversalRedis3Store) ListDirectoryEntries(ctx context.Context, dir
|
||||
dirListKey := store.getKey(genDirectoryListKey(string(dirPath)))
|
||||
counter := int64(0)
|
||||
|
||||
// removing a name restructures the list being walked, so wait for the walk to end
|
||||
var orphans []string
|
||||
defer func() {
|
||||
for _, fileName := range orphans {
|
||||
store.removeOrphanedDirectoryListMember(ctx, dirPath, fileName)
|
||||
}
|
||||
}()
|
||||
|
||||
var callbackErr error
|
||||
err = listChildren(ctx, store, dirListKey, startFileName, func(fileName string) bool {
|
||||
if startFileName != "" {
|
||||
@@ -189,15 +239,15 @@ func (store *UniversalRedis3Store) ListDirectoryEntries(ctx context.Context, dir
|
||||
if err != nil {
|
||||
glog.V(0).InfofCtx(ctx, "list %s : %v", path, err)
|
||||
if err == filer_pb.ErrNotFound {
|
||||
orphans = append(orphans, fileName)
|
||||
return true
|
||||
}
|
||||
} else {
|
||||
if entry.TtlSec > 0 {
|
||||
if entry.Attr.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
|
||||
store.Client.Del(ctx, store.getKey(string(path))).Result()
|
||||
store.Client.ZRem(ctx, dirListKey, fileName).Result()
|
||||
return true
|
||||
if isLogicallyExpired(entry) {
|
||||
if store.deleteExpiredEntry(ctx, path) {
|
||||
orphans = append(orphans, fileName)
|
||||
}
|
||||
return true
|
||||
}
|
||||
counter++
|
||||
|
||||
@@ -229,10 +279,97 @@ func (store *UniversalRedis3Store) ListDirectoryEntries(ctx context.Context, dir
|
||||
return lastFileName, err
|
||||
}
|
||||
|
||||
// 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 *UniversalRedis3Store) 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 listed, err := hasChild(ctx, store, store.getKey(genDirectoryListKey(dir)), name); err != nil || !listed {
|
||||
return false, err
|
||||
}
|
||||
return store.removeOrphanedDirectoryListMember(ctx, util.FullPath(dir), name)
|
||||
}
|
||||
|
||||
// removeOrphanedDirectoryListMember reports whether it removed the member.
|
||||
func (store *UniversalRedis3Store) 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)
|
||||
path := util.NewFullPath(string(dirPath), fileName)
|
||||
|
||||
// InsertEntry writes the value before it takes the list's lock to add the
|
||||
// name, so a value absent under the lock belongs to no insert in progress.
|
||||
err = removeChild(ctx, store, store.getKey(genDirectoryListKey(string(dirPath))), fileName, func() (bool, error) {
|
||||
exists, err := store.existsOnMaster(ctx, store.getKey(string(path)))
|
||||
if err != nil || exists != 0 {
|
||||
return true, err
|
||||
}
|
||||
// an expired directory may still list children a recursive delete needs to reach
|
||||
children, err := store.existsOnMaster(ctx, store.getKey(genDirectoryListKey(string(path))))
|
||||
removed = err == nil && children == 0
|
||||
return !removed, err
|
||||
})
|
||||
if err != nil {
|
||||
glog.V(0).InfofCtx(ctx, "remove orphaned %s in %s: %v", fileName, dirPath, err)
|
||||
return false, err
|
||||
}
|
||||
return removed, nil
|
||||
}
|
||||
|
||||
// existsOnMaster checks the key's master: a lagging replica can misread a live
|
||||
// value as absent.
|
||||
func (store *UniversalRedis3Store) existsOnMaster(ctx context.Context, key string) (int64, error) {
|
||||
return store.onMaster().Exists(ctx, key).Result()
|
||||
}
|
||||
|
||||
func isLogicallyExpired(entry *filer.Entry) bool {
|
||||
return entry.TtlSec > 0 && entry.Attr.Crtime.Add(time.Duration(entry.TtlSec)*time.Second).Before(time.Now())
|
||||
}
|
||||
|
||||
// deletes the value only when it still holds exactly the bytes the expiry decision was made on;
|
||||
// -1: already gone, 0: changed under us, 1: deleted
|
||||
const deleteIfUnchangedScript = `
|
||||
local v = redis.call('GET', KEYS[1])
|
||||
if v == false then
|
||||
return -1
|
||||
end
|
||||
if v == ARGV[1] then
|
||||
return redis.call('DEL', KEYS[1])
|
||||
end
|
||||
return 0`
|
||||
|
||||
// deleteExpiredEntry deletes the value of a logically expired entry unless a
|
||||
// concurrent insert recreated it, and reports whether the value is gone.
|
||||
func (store *UniversalRedis3Store) deleteExpiredEntry(ctx context.Context, path util.FullPath) (gone bool) {
|
||||
// survive the listing request being canceled mid-delete
|
||||
ctx = context.WithoutCancel(ctx)
|
||||
valueKey := store.getKey(string(path))
|
||||
|
||||
// re-read so the delete can be conditioned on exactly the bytes checked
|
||||
data, err := store.Client.Get(ctx, valueKey).Bytes()
|
||||
if err == redis.Nil {
|
||||
return true
|
||||
}
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
entry := &filer.Entry{FullPath: path}
|
||||
if err := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil || !isLogicallyExpired(entry) {
|
||||
return false
|
||||
}
|
||||
deleted, err := store.Client.Eval(ctx, deleteIfUnchangedScript, []string{valueKey}, data).Int()
|
||||
return err == nil && deleted != 0
|
||||
}
|
||||
|
||||
func genDirectoryListKey(dir string) (dirList string) {
|
||||
return dir + DIR_LIST_MARKER
|
||||
}
|
||||
|
||||
func (store *UniversalRedis3Store) Shutdown() {
|
||||
store.Client.Close()
|
||||
if store.masterClient != nil {
|
||||
store.masterClient.Close()
|
||||
}
|
||||
}
|
||||
@@ -231,3 +231,316 @@ func TestInsertEntryOverAnExistingEntryReplacesIt(t *testing.T) {
|
||||
t.Fatalf("listed %v, want [replaced]", names)
|
||||
}
|
||||
}
|
||||
|
||||
func insertTestEntry(t *testing.T, store *UniversalRedis3Store, path util.FullPath, crtime time.Time, ttlSec int32) {
|
||||
t.Helper()
|
||||
if err := store.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: crtime, Mtime: crtime, Mode: 0644, TtlSec: ttlSec},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func listingKeyExists(t *testing.T, store *UniversalRedis3Store, dir util.FullPath) bool {
|
||||
t.Helper()
|
||||
n, err := store.Client.Exists(context.Background(), store.getKey(genDirectoryListKey(string(dir)))).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("exists %s: %v", dir, err)
|
||||
}
|
||||
return n != 0
|
||||
}
|
||||
|
||||
// A listing that meets the name of an entry redis expired, or of one past its
|
||||
// TTL, takes the name out of the directory's list.
|
||||
func TestListingRemovesExpiredNames(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
|
||||
insertTestEntry(t, store, dir.Child("evicted"), now, 3600)
|
||||
insertTestEntry(t, store, dir.Child("expired"), now.Add(-2*time.Hour), 3600)
|
||||
insertTestEntry(t, store, dir.Child("live"), now, 0)
|
||||
// what redis does once the TTL passes
|
||||
if err := store.Client.Del(ctx, store.getKey(string(dir.Child("evicted")))).Err(); err != nil {
|
||||
t.Fatalf("del: %v", err)
|
||||
}
|
||||
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "live" {
|
||||
t.Fatalf("listed %v, want [live]", names)
|
||||
}
|
||||
if n, err := store.Client.Exists(ctx, store.getKey(string(dir.Child("expired")))).Result(); err != nil || n != 0 {
|
||||
t.Fatalf("expired value still stored: n=%d err=%v", n, err)
|
||||
}
|
||||
|
||||
if err := store.DeleteEntry(ctx, dir.Child("live")); err != nil {
|
||||
t.Fatalf("DeleteEntry: %v", err)
|
||||
}
|
||||
if listingKeyExists(t, store, dir) {
|
||||
t.Fatalf("listing key left behind by the expired names")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveExpiredLeftover(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
|
||||
if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("never")); err != nil || removed {
|
||||
t.Fatalf("never written: removed=%v err=%v", removed, err)
|
||||
}
|
||||
|
||||
insertTestEntry(t, store, dir.Child("live"), now, 0)
|
||||
if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("live")); err != nil || removed {
|
||||
t.Fatalf("live: removed=%v err=%v", removed, err)
|
||||
}
|
||||
|
||||
// an expired directory whose children are still listed keeps its name
|
||||
insertTestEntry(t, store, dir.Child("subdir"), now, 3600)
|
||||
insertTestEntry(t, store, dir.Child("subdir").Child("child"), now, 0)
|
||||
insertTestEntry(t, store, dir.Child("evicted"), now, 3600)
|
||||
for _, p := range []util.FullPath{dir.Child("subdir"), dir.Child("evicted")} {
|
||||
if err := store.Client.Del(ctx, store.getKey(string(p))).Err(); err != nil {
|
||||
t.Fatalf("del: %v", err)
|
||||
}
|
||||
}
|
||||
if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("subdir")); err != nil || removed {
|
||||
t.Fatalf("subdir with children: removed=%v err=%v", removed, err)
|
||||
}
|
||||
if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("evicted")); err != nil || !removed {
|
||||
t.Fatalf("evicted: removed=%v err=%v", removed, err)
|
||||
}
|
||||
|
||||
var names []string
|
||||
if err := listChildren(ctx, store, store.getKey(genDirectoryListKey(string(dir))), "", func(name string) bool {
|
||||
names = append(names, name)
|
||||
return true
|
||||
}); err != nil {
|
||||
t.Fatalf("listChildren: %v", err)
|
||||
}
|
||||
if fmt.Sprint(names) != "[live subdir]" {
|
||||
t.Fatalf("directory list holds %v, want [live subdir]", names)
|
||||
}
|
||||
|
||||
if err := store.DeleteFolderChildren(ctx, dir.Child("subdir")); err != nil {
|
||||
t.Fatalf("DeleteFolderChildren: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// An update that finds the value expired writes it again, and has to list the
|
||||
// name again too: the cleanup of the expired value may have taken it out.
|
||||
func TestUpdateEntryOfAnExpiredValueListsItAgain(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
path := dir.Child("updated")
|
||||
insertTestEntry(t, store, path, now, 3600)
|
||||
if err := store.Client.Del(ctx, store.getKey(string(path))).Err(); err != nil {
|
||||
t.Fatalf("del: %v", err)
|
||||
}
|
||||
if removed, err := store.RemoveExpiredLeftover(ctx, path); err != nil || !removed {
|
||||
t.Fatalf("RemoveExpiredLeftover = %v, %v", removed, err)
|
||||
}
|
||||
|
||||
if err := store.UpdateEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644, TtlSec: 7200},
|
||||
}); err != nil {
|
||||
t.Fatalf("UpdateEntry: %v", err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "updated" {
|
||||
t.Fatalf("listed %v, want [updated]", names)
|
||||
}
|
||||
if ttl, err := store.Client.TTL(ctx, store.getKey(string(path))).Result(); err != nil || ttl <= time.Hour || ttl > 2*time.Hour {
|
||||
t.Fatalf("TTL = %v, %v; want the update's 2h", ttl, err)
|
||||
}
|
||||
}
|
||||
|
||||
// An update that finds the value expired lists the name before it writes the
|
||||
// value back. Failing to list it leaves the value missing, so a retry lists it.
|
||||
func TestUpdateEntryFailingToListTheNameRetries(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
path := dir.Child("updated")
|
||||
insertTestEntry(t, store, path, now, 3600)
|
||||
if err := store.Client.Del(ctx, store.getKey(string(path))).Err(); err != nil {
|
||||
t.Fatalf("del: %v", err)
|
||||
}
|
||||
if removed, err := store.RemoveExpiredLeftover(ctx, path); err != nil || !removed {
|
||||
t.Fatalf("RemoveExpiredLeftover = %v, %v", removed, err)
|
||||
}
|
||||
|
||||
update := &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644, TtlSec: 7200},
|
||||
}
|
||||
// let the update's SET XX through, then fail the SET NX that takes the list lock
|
||||
failing := &failingCommands{name: "set"}
|
||||
store.Client.AddHook(failing)
|
||||
failing.skip.Store(1)
|
||||
failing.left.Store(1 << 20)
|
||||
if err := store.UpdateEntry(ctx, update); err == nil {
|
||||
t.Fatalf("UpdateEntry succeeded although the list lock failed")
|
||||
}
|
||||
failing.left.Store(0)
|
||||
if n, err := store.Client.Exists(ctx, store.getKey(string(path))).Result(); err != nil || n != 0 {
|
||||
t.Fatalf("value exists = %d, %v; want it left missing", n, err)
|
||||
}
|
||||
|
||||
if err := store.UpdateEntry(ctx, update); err != nil {
|
||||
t.Fatalf("UpdateEntry retry: %v", err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "updated" {
|
||||
t.Fatalf("listed %v, want [updated]", names)
|
||||
}
|
||||
}
|
||||
|
||||
// A write under the list lock can outlast the lock's lease, so another filer's
|
||||
// cleanup can remove the name before the value lands. The lost lease shows at
|
||||
// unlock, and the name is listed again.
|
||||
func TestInsertChildListsTheNameAgainAfterTheLeaseRanOut(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
path := dir.Child("updated")
|
||||
|
||||
if err := insertChild(ctx, store, key, "updated", func() error {
|
||||
if err := store.Client.Del(ctx, key+"lock").Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if removed, err := store.removeOrphanedDirectoryListMember(ctx, dir, "updated"); err != nil || !removed {
|
||||
return fmt.Errorf("cleanup removed = %v, %v", removed, err)
|
||||
}
|
||||
return store.doInsertEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644},
|
||||
})
|
||||
}); err != nil {
|
||||
t.Fatalf("insertChild: %v", err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "updated" {
|
||||
t.Fatalf("listed %v, want [updated]", names)
|
||||
}
|
||||
}
|
||||
|
||||
// A cleanup that found no value can outlast the list lock's lease, so another
|
||||
// filer can list the name and write its value before the cleanup removes the
|
||||
// name. The lost lease shows at unlock, and the name is listed again.
|
||||
func TestCleanupListsTheNameAgainAfterTheLeaseRanOut(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
path := dir.Child("updated")
|
||||
if err := insertChild(ctx, store, key, "updated", nil); err != nil {
|
||||
t.Fatalf("insertChild: %v", err)
|
||||
}
|
||||
|
||||
if err := removeChild(ctx, store, key, "updated", func() (bool, error) {
|
||||
if err := store.Client.Del(ctx, key+"lock").Err(); err != nil {
|
||||
return true, err
|
||||
}
|
||||
return false, store.UpdateEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644},
|
||||
})
|
||||
}); err != nil {
|
||||
t.Fatalf("removeChild: %v", err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "updated" {
|
||||
t.Fatalf("listed %v, want [updated]", names)
|
||||
}
|
||||
}
|
||||
|
||||
// A cleanup can lose its lease and then fail partway through removing the
|
||||
// name, after the name is already gone. The name is listed again all the same.
|
||||
func TestCleanupFailingAfterTheLeaseRanOutListsTheNameAgain(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
insertTestEntry(t, store, dir.Child("a"), now, 0)
|
||||
if err := insertChild(ctx, store, key, "b", nil); err != nil {
|
||||
t.Fatalf("insertChild: %v", err)
|
||||
}
|
||||
|
||||
// fail the node size read that follows the removal of b from its node
|
||||
failing := &failingCommands{name: "zlexcount"}
|
||||
store.Client.AddHook(failing)
|
||||
if err := removeChild(ctx, store, key, "b", func() (bool, error) {
|
||||
if err := store.Client.Del(ctx, key+"lock").Err(); err != nil {
|
||||
return true, err
|
||||
}
|
||||
if err := store.UpdateEntry(ctx, &filer.Entry{
|
||||
FullPath: dir.Child("b"),
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644},
|
||||
}); err != nil {
|
||||
return true, err
|
||||
}
|
||||
failing.left.Store(1)
|
||||
return false, nil
|
||||
}); err == nil {
|
||||
t.Fatalf("removeChild succeeded although reading the node failed")
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 2 || names[0] != "a" || names[1] != "b" {
|
||||
t.Fatalf("listed %v, want [a b]", names)
|
||||
}
|
||||
}
|
||||
|
||||
// Listing the name again after a lost lease is the only thing that lists a
|
||||
// value written in between, so a failed attempt is retried.
|
||||
func TestRelistingAfterTheLeaseRanOutRetries(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
path := dir.Child("updated")
|
||||
|
||||
// fail the list read of the first attempt to list the name again
|
||||
failing := &failingCommands{name: "get"}
|
||||
store.Client.AddHook(failing)
|
||||
if err := insertChild(ctx, store, key, "updated", func() error {
|
||||
if err := store.Client.Del(ctx, key+"lock").Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if removed, err := store.removeOrphanedDirectoryListMember(ctx, dir, "updated"); err != nil || !removed {
|
||||
return fmt.Errorf("cleanup removed = %v, %v", removed, err)
|
||||
}
|
||||
if err := store.doInsertEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
failing.left.Store(1)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("insertChild: %v", err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "updated" {
|
||||
t.Fatalf("listed %v, want [updated]", names)
|
||||
}
|
||||
}
|
||||
|
||||
// A list change can outlast the list lock's lease, and another filer's change
|
||||
// based on an earlier read of the list can then drop the name. The lost lease
|
||||
// shows at unlock, and the name is listed again.
|
||||
func TestInsertEntryListsTheNameAgainAfterItsListChangeWasLost(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
|
||||
// after the list write, the lock is gone and another filer, which read the
|
||||
// list before that write, removes the list's last name and with it the list
|
||||
store.Client.AddHook(&afterCommand{name: "set", key: key, fn: func() {
|
||||
if err := store.Client.Del(ctx, key+"lock", key).Err(); err != nil {
|
||||
t.Errorf("del: %v", err)
|
||||
}
|
||||
}})
|
||||
insertTestEntry(t, store, dir.Child("a"), time.Now(), 0)
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "a" {
|
||||
t.Fatalf("listed %v, want [a]", names)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user