diff --git a/weed/filer/filer.go b/weed/filer/filer.go index cfb7cad4a5..0ae59ba0b2 100644 --- a/weed/filer/filer.go +++ b/weed/filer/filer.go @@ -485,6 +485,15 @@ func (f *Filer) TransactionCovers(ctx context.Context, paths ...util.FullPath) b return ok && fsw.transactionCovers(paths...) } +// RefusesConflictingCommits reports whether a store transaction that reads the +// entry at path and writes it is refused when another writer commits that +// entry meanwhile: the default store says that its commits are, and it holds +// the entry. +func (f *Filer) RefusesConflictingCommits(path util.FullPath) bool { + fsw, ok := f.Store.(*FilerStoreWrapper) + return ok && fsw.refusesConflictingCommits(path) +} + // OverwritesAtOnce reports whether an entry inserted at path replaces what is // stored there at once and whole: the default store says that its inserts do, // and it holds the entry. diff --git a/weed/filer/filerstore.go b/weed/filer/filerstore.go index 5fea65e3c1..9db1e31484 100644 --- a/weed/filer/filerstore.go +++ b/weed/filer/filerstore.go @@ -92,6 +92,17 @@ type IsolatingTransactionStore interface { IsolatesTransactions() bool } +// ConflictRefusingStore is implemented by a store whose transactions are +// optimistic: CommitTransaction refuses, with ErrTransactionConflict, a +// transaction that wrote a key another writer committed after it began. A read +// of an entry and the write it decides, made in one such transaction, cannot +// have a rename or a delete of the entry commit between them unnoticed, from +// whichever filer. A store says so itself: TiKV does. The SQL stores do not: +// at their default isolation the later write goes through. +type ConflictRefusingStore interface { + RefusesConflictingCommits() bool +} + // 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 ac9a5a941c..584768a386 100644 --- a/weed/filer/filerstore_wrapper.go +++ b/weed/filer/filerstore_wrapper.go @@ -465,6 +465,15 @@ func (fsw *FilerStoreWrapper) transactionCovers(paths ...util.FullPath) bool { return true } +// refusesConflictingCommits reports whether a transaction of the default store +// that read and wrote the entry at path is refused when another writer +// committed that entry meanwhile: the store's commits are (ConflictRefusingStore) +// and it holds the entry. +func (fsw *FilerStoreWrapper) refusesConflictingCommits(path util.FullPath) bool { + refusing, ok := fsw.defaultStore.(ConflictRefusingStore) + return ok && refusing.RefusesConflictingCommits() && fsw.getActualStore(path) == fsw.defaultStore +} + // overwritesAtOnce reports whether an entry inserted at path replaces what is // stored there at once and whole: the default store says that its inserts do // (OverwritingStore), and it holds the entry. diff --git a/weed/filer/tikv/tikv_store.go b/weed/filer/tikv/tikv_store.go index 8d8877113d..e4cfd59dff 100644 --- a/weed/filer/tikv/tikv_store.go +++ b/weed/filer/tikv/tikv_store.go @@ -385,6 +385,15 @@ func (store *TikvStore) IsolatesTransactions() bool { var _ filer.IsolatingTransactionStore = (*TikvStore)(nil) +// RefusesConflictingCommits: the transactions are optimistic, and a commit +// meets a write conflict (commitError) on a key another writer committed +// after the transaction began. +func (store *TikvStore) RefusesConflictingCommits() bool { + return true +} + +var _ filer.ConflictRefusingStore = (*TikvStore)(nil) + // commitError marks a write conflict as a transaction conflict: another writer // committed a key this optimistic transaction wrote after it began, so the // transaction can succeed when run again. diff --git a/weed/server/filer_grpc_server.go b/weed/server/filer_grpc_server.go index 9215fe0774..fea2305e4f 100644 --- a/weed/server/filer_grpc_server.go +++ b/weed/server/filer_grpc_server.go @@ -973,56 +973,128 @@ func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntr // but the acknowledged state still reflects everything at or below this. logTsNs := time.Now().UnixNano() - entry, err := fs.filer.FindEntry(ctx, lockPath) - if err != nil { - if errors.Is(err, filer_pb.ErrNotFound) { - return &filer_pb.UpdateEntryResponse{}, status.Errorf(codes.NotFound, "not found %s: %v", fullpath, err) + // The read (preconditions, garbage diff) and the write it decides: in one + // store transaction where the store refuses a conflicting commit, since + // the lock above does not cover a rename or a delete of the entry. + var ( + entry, newEntry *filer.Entry + garbage []*filer_pb.FileChunk + unchanged bool + stamp int64 + ) + err := fs.runEntryTransaction(ctx, lockPath, func(ctx context.Context) error { + var err error + entry, newEntry, garbage, unchanged = nil, nil, nil, false + entry, err = fs.filer.FindEntry(ctx, lockPath) + if err != nil { + if errors.Is(err, filer_pb.ErrNotFound) { + return status.Errorf(codes.NotFound, "not found %s: %v", fullpath, err) + } + return fmt.Errorf("not found %s: %v", fullpath, err) } - return &filer_pb.UpdateEntryResponse{}, fmt.Errorf("not found %s: %v", fullpath, err) - } - if err := validateUpdateEntryPreconditions(entry, req.ExpectedExtended); err != nil { + if err := validateUpdateEntryPreconditions(entry, req.ExpectedExtended); err != nil { + return err + } + if conditionIsSet(req.Condition) && !writeConditionSatisfied(req.Condition, entry) { + glog.V(3).InfofCtx(ctx, "UpdateEntry %s: precondition failed: %v", fullpath, req.Condition) + return status.Errorf(codes.FailedPrecondition, "precondition failed: %s", fullpath) + } + + chunks, replaced, err := fs.cleanupChunks(ctx, fullpath, entry, req.Entry) + if err != nil { + return fmt.Errorf("UpdateEntry cleanupChunks %s: %v", fullpath, err) + } + + newEntry = filer.FromPbEntry(req.Directory, req.Entry) + newEntry.Chunks = chunks + + // Don't apply TTL to remote entries - they're managed by remote storage + if newEntry.Remote != nil { + newEntry.TtlSec = 0 + } + + if unchanged = filer.EqualEntry(entry, newEntry); unchanged { + return nil + } + garbage = replaced + stamp = fs.filer.StampEntryCommitTsNs(newEntry) + return fs.filer.UpdateEntry(ctx, entry, newEntry, req.IsFromOtherCluster) + }, func() { + // Nothing of the run is stored: its stamp names no event, and nothing + // refers to the manifest chunks it folded the request's chunks into. + fs.filer.ReleaseEntryCommitTsNs(stamp) + stamp = 0 + fs.filer.DeleteChunksNotRecursive(filer.DoMinusChunks(newEntry.GetChunks(), req.Entry.GetChunks())) + }) + if err != nil { + fs.filer.ReleaseEntryCommitTsNs(stamp) + glog.V(3).InfofCtx(ctx, "UpdateEntry %s: %v", fullpath, err) return &filer_pb.UpdateEntryResponse{}, err } - if conditionIsSet(req.Condition) && !writeConditionSatisfied(req.Condition, entry) { - glog.V(3).InfofCtx(ctx, "UpdateEntry %s: precondition failed: %v", fullpath, req.Condition) - return &filer_pb.UpdateEntryResponse{}, status.Errorf(codes.FailedPrecondition, "precondition failed: %s", fullpath) + + resp := &filer_pb.UpdateEntryResponse{LogTsNs: logTsNs, LogSignature: fs.filer.Signature} + if unchanged { + return resp, nil } - chunks, garbage, err2 := fs.cleanupChunks(ctx, fullpath, entry, req.Entry) - if err2 != nil { - return &filer_pb.UpdateEntryResponse{}, fmt.Errorf("UpdateEntry cleanupChunks %s: %v", fullpath, err2) - } - - newEntry := filer.FromPbEntry(req.Directory, req.Entry) - newEntry.Chunks = chunks - - // Don't apply TTL to remote entries - they're managed by remote storage - if newEntry.Remote != nil { - newEntry.TtlSec = 0 - } - - if filer.EqualEntry(entry, newEntry) { - return &filer_pb.UpdateEntryResponse{LogTsNs: logTsNs, LogSignature: fs.filer.Signature}, err - } + // an update that is not the same hard link as entry dropped entry's + // link; the file's other names still read entry's chunks + garbage = fs.filer.KeepHardLinkedChunks(ctx, entry, newEntry, garbage) + fs.filer.DeleteChunksNotRecursive(garbage) ctx, eventSink := filer.WithMetadataEventSink(ctx) - resp := &filer_pb.UpdateEntryResponse{LogTsNs: logTsNs, LogSignature: fs.filer.Signature} - fs.filer.StampEntryCommitTsNs(newEntry) - if err = fs.filer.UpdateEntry(ctx, entry, newEntry, req.IsFromOtherCluster); err == nil { - // an update that is not the same hard link as entry dropped entry's - // link; the file's other names still read entry's chunks - garbage = fs.filer.KeepHardLinkedChunks(ctx, entry, newEntry, garbage) - fs.filer.DeleteChunksNotRecursive(garbage) + fs.filer.NotifyUpdateEvent(ctx, entry, newEntry, true, req.IsFromOtherCluster, req.Signatures) + resp.MetadataEvent = eventSink.Last() - fs.filer.NotifyUpdateEvent(ctx, entry, newEntry, true, req.IsFromOtherCluster, req.Signatures) - resp.MetadataEvent = eventSink.Last() + return resp, nil +} - } else { - fs.filer.ReleaseEntryCommitTsNs(newEntry.CommitTsNs) - glog.V(3).InfofCtx(ctx, "UpdateEntry %s: %v", filepath.Join(req.Directory, req.Entry.Name), err) +// entryUpdateAttempts bounds how often an entry update runs its transaction +// while the store refuses the commit for a concurrent write to the entry. +const entryUpdateAttempts = 5 + +// runEntryTransaction runs attempt: the read of the entry at path and the +// write that read decides. The caller holds the path's lock, which keeps the +// two together against the writers that take it on this filer. A rename or a +// delete sent to another filer does not take it, and on any filer a rename +// moves, and a recursive delete removes, what is below its paths unlocked. One +// that committed between the read and the write had the write store the entry +// again at the path it had left. +// +// Where the store refuses a conflicting commit (filer.ConflictRefusingStore: +// TiKV), attempt runs in a store transaction of its own. Such a rename or +// delete wrote the entry's key, so the store refuses the commit; refused then +// gives up what the run made outside the store, and attempt runs again and +// reads what is there now. Other stores run attempt once, without a +// transaction, as before. +func (fs *FilerServer) runEntryTransaction(ctx context.Context, path util.FullPath, attempt func(ctx context.Context) error, refused func()) error { + if !fs.filer.RefusesConflictingCommits(path) { + return attempt(ctx) + } + for n := 1; ; n++ { + txCtx, err := fs.filer.BeginTransaction(ctx) + if err != nil { + return err + } + if err := attempt(txCtx); err != nil { + fs.filer.RollbackTransaction(txCtx) + return err + } + commitErr := fs.filer.CommitTransaction(txCtx) + if commitErr == nil { + return nil + } + fs.filer.RollbackTransaction(txCtx) + if !errors.Is(commitErr, filer.ErrTransactionConflict) { + return fmt.Errorf("%s commit error: %w", path, commitErr) + } + refused() + if n == entryUpdateAttempts { + return fmt.Errorf("%s commit error: %w", path, commitErr) + } + glog.V(0).InfofCtx(ctx, "update %s: running it again (%d of %d) after a concurrent write: %v", path, n+1, entryUpdateAttempts, commitErr) + time.Sleep(time.Duration(n) * 10 * time.Millisecond) } - - return resp, err } func validateUpdateEntryPreconditions(entry *filer.Entry, expectedExtended map[string][]byte) error { diff --git a/weed/server/filer_grpc_server_update_conflict_test.go b/weed/server/filer_grpc_server_update_conflict_test.go new file mode 100644 index 0000000000..085fc96fed --- /dev/null +++ b/weed/server/filer_grpc_server_update_conflict_test.go @@ -0,0 +1,235 @@ +package weed_server + +import ( + "context" + "errors" + "testing" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// An update reads the entry, then writes it. Its path lock is this filer's and +// covers that one path: a rename or a delete on another filer, or of a +// directory above the entry, can commit between the two. These tests have one +// commit just then, on a store that refuses the update's commit for it as TiKV +// does, and check that the update answers from what the other writer left +// instead of storing the entry again where it no longer is. + +// conflictRefusingStore is txnRenameStore declaring, as the TiKV store does, +// that its commits are refused for a concurrent write. +type conflictRefusingStore struct{ *txnRenameStore } + +func (conflictRefusingStore) RefusesConflictingCommits() bool { return true } + +const updatedChunk, storedChunk, otherChunk = "2,0b02", "1,0a01", "3,0c03" + +// updateConflictServer has /ckpt/run/f in the store with the chunk 1,0a01. +// meanwhile runs against the store as another writer's committed transaction, +// after the update read the entry and before its first commit, which the store +// then refuses. +func updateConflictServer(t *testing.T, meanwhile func(entries map[string]*filer.Entry)) (*FilerServer, *filer.Filer, *txnRenameStore, *captureQueue) { + t.Helper() + store := newTxnRenameStore() + store.entries["/ckpt/run"] = newDirectoryEntry("/ckpt/run", 110) + store.entries["/ckpt/run/f"] = fileEntryWithChunk("/ckpt/run/f", 101, storedChunk) + store.refuse = func(commit int) error { + if commit > 1 { + return nil + } + store.mu.Lock() + meanwhile(store.entries) + store.mu.Unlock() + return writeConflict(commit) + } + queue := &captureQueue{} + swapNotificationQueue(t, queue) + f := newRenameTestFiler(t, conflictRefusingStore{store}) + return &FilerServer{filer: f, option: &FilerOption{}, entryLockTable: util.NewLockTable[util.FullPath]()}, f, store, queue +} + +func updateOfF(chunk string) *filer_pb.UpdateEntryRequest { + return &filer_pb.UpdateEntryRequest{ + Directory: "/ckpt/run", + Entry: &filer_pb.Entry{ + Name: "f", + Attributes: &filer_pb.FuseAttributes{Mtime: 1700000100, FileMode: 0644, Inode: 101, FileSize: 4}, + Chunks: []*filer_pb.FileChunk{written(chunk, 2)}, + }, + } +} + +func moveInStore(entries map[string]*filer.Entry, from, to string) { + entry := entries[from].ShallowClone() + entry.FullPath = util.FullPath(to) + entries[to] = entry + delete(entries, from) +} + +// checkGone: the entry the update was for left its path, so the update finds +// nothing, stores nothing there, tells no subscriber, and deletes no chunk: +// the one it would have replaced is still read under the entry's new name. +func checkGone(t *testing.T, err error, f *filer.Filer, store *txnRenameStore, queue *captureQueue, gone ...string) { + t.Helper() + if status.Code(err) != codes.NotFound { + t.Fatalf("UpdateEntry: %v, want NotFound", err) + } + for _, p := range gone { + if _, err := store.renameTestStore.FindEntry(context.Background(), util.FullPath(p)); !errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("%s after the update: %v, want it to stay gone", p, err) + } + } + if events := queue.snapshot(); len(events) != 0 { + t.Fatalf("metadata events = %+v, want none", events) + } + checkDeletions(t, f) +} + +func checkChunk(t *testing.T, store *txnRenameStore, p string, want string) { + t.Helper() + entry, err := store.renameTestStore.FindEntry(context.Background(), util.FullPath(p)) + if err != nil { + t.Fatalf("%s: %v", p, err) + } + if ids := chunkIds(entry); len(ids) != 1 || ids[0] != want { + t.Fatalf("%s chunks = %v, want [%s]", p, ids, want) + } +} + +// mv run run2 while a file under run is flushed: the update must not leave +// run/f under a directory that no longer exists, where no listing reaches it, +// nor delete the chunk run2/f reads. +func TestUpdateEntryFindsNothingAfterItsDirectoryIsRenamed(t *testing.T) { + server, f, store, queue := updateConflictServer(t, func(entries map[string]*filer.Entry) { + moveInStore(entries, "/ckpt/run", "/ckpt/run2") + moveInStore(entries, "/ckpt/run/f", "/ckpt/run2/f") + }) + + _, err := server.UpdateEntry(context.Background(), updateOfF(updatedChunk)) + + checkGone(t, err, f, store, queue, "/ckpt/run", "/ckpt/run/f") + checkChunk(t, store, "/ckpt/run2/f", storedChunk) +} + +// mv f g on another filer while f is flushed: the update must not bring f back +// as a second name for the file, sharing a chunk that deleting either name +// deletes for both. +func TestUpdateEntryFindsNothingAfterTheEntryIsRenamed(t *testing.T) { + server, f, store, queue := updateConflictServer(t, func(entries map[string]*filer.Entry) { + moveInStore(entries, "/ckpt/run/f", "/ckpt/run/g") + }) + + _, err := server.UpdateEntry(context.Background(), updateOfF(updatedChunk)) + + checkGone(t, err, f, store, queue, "/ckpt/run/f") + checkChunk(t, store, "/ckpt/run/g", storedChunk) +} + +// rm f on another filer while f is flushed: the update must not bring the +// removed file back. +func TestUpdateEntryFindsNothingAfterTheEntryIsDeleted(t *testing.T) { + server, f, store, queue := updateConflictServer(t, func(entries map[string]*filer.Entry) { + delete(entries, "/ckpt/run/f") + }) + + _, err := server.UpdateEntry(context.Background(), updateOfF(updatedChunk)) + + checkGone(t, err, f, store, queue, "/ckpt/run/f") +} + +// Another file renamed over f while f is flushed. An update without a +// condition still writes over whatever is at the path, but it replaces the +// file that is there now: that file's chunk is the one to delete, and the one +// subscribers are told went. +func TestUpdateEntryReplacesWhatWasRenamedOverTheEntry(t *testing.T) { + server, f, store, queue := updateConflictServer(t, func(entries map[string]*filer.Entry) { + entries["/ckpt/run/f"] = fileEntryWithChunk("/ckpt/run/f", 202, otherChunk) + }) + + if _, err := server.UpdateEntry(context.Background(), updateOfF(updatedChunk)); err != nil { + t.Fatalf("UpdateEntry: %v, want it to run again after the conflict", err) + } + + if got := store.commitCount(); got != 2 { + t.Fatalf("commits = %d, want 2", got) + } + checkChunk(t, store, "/ckpt/run/f", updatedChunk) + checkDeletions(t, f, otherChunk) + events := queue.snapshot() + if len(events) != 1 { + t.Fatalf("metadata events = %+v, want the one committed update", events) + } + if old := events[0].notification.GetOldEntry().GetChunks(); len(old) != 1 || old[0].GetFileIdString() != otherChunk { + t.Fatalf("event's old entry chunks = %v, want [%s]", old, otherChunk) + } +} + +// The same, for an update that names the entry it means to change: the file +// renamed over it is not that entry, and stays as it is. +func TestUpdateEntryChecksItsPreconditionAgainAfterAConflict(t *testing.T) { + server, f, store, queue := updateConflictServer(t, func(entries map[string]*filer.Entry) { + other := fileEntryWithChunk("/ckpt/run/f", 202, otherChunk) + other.Extended = map[string][]byte{"owner": []byte("b")} + entries["/ckpt/run/f"] = other + }) + store.entries["/ckpt/run/f"].Extended = map[string][]byte{"owner": []byte("a")} + req := updateOfF(updatedChunk) + req.ExpectedExtended = map[string][]byte{"owner": []byte("a")} + + _, err := server.UpdateEntry(context.Background(), req) + + if status.Code(err) != codes.FailedPrecondition { + t.Fatalf("UpdateEntry: %v, want FailedPrecondition", err) + } + checkChunk(t, store, "/ckpt/run/f", otherChunk) + if events := queue.snapshot(); len(events) != 0 { + t.Fatalf("metadata events = %+v, want none", events) + } + checkDeletions(t, f) +} + +// A store that keeps refusing: the update gives up with the store's error and +// leaves the entry as the other writers have it. +func TestUpdateEntryGivesUpWhileTheStoreKeepsRefusing(t *testing.T) { + server, f, store, queue := updateConflictServer(t, func(map[string]*filer.Entry) {}) + store.refuse = writeConflict + + _, err := server.UpdateEntry(context.Background(), updateOfF(updatedChunk)) + + if !errors.Is(err, filer.ErrTransactionConflict) { + t.Fatalf("UpdateEntry: %v, want the store's conflict", err) + } + if got := store.commitCount(); got != entryUpdateAttempts { + t.Fatalf("commits = %d, want %d", got, entryUpdateAttempts) + } + checkChunk(t, store, "/ckpt/run/f", storedChunk) + if events := queue.snapshot(); len(events) != 0 { + t.Fatalf("metadata events = %+v, want none", events) + } + checkDeletions(t, f) +} + +// A store that does not refuse conflicting commits gains nothing from a +// transaction around the update, and gets none. +func TestUpdateEntryUsesNoTransactionWhereTheStoreRefusesNone(t *testing.T) { + store := newTxnRenameStore() + store.entries["/ckpt/run"] = newDirectoryEntry("/ckpt/run", 110) + store.entries["/ckpt/run/f"] = fileEntryWithChunk("/ckpt/run/f", 101, storedChunk) + swapNotificationQueue(t, &captureQueue{}) + f := newRenameTestFiler(t, store) + server := &FilerServer{filer: f, option: &FilerOption{}, entryLockTable: util.NewLockTable[util.FullPath]()} + + if _, err := server.UpdateEntry(context.Background(), updateOfF(updatedChunk)); err != nil { + t.Fatalf("UpdateEntry: %v", err) + } + + if got := store.commitCount(); got != 0 { + t.Fatalf("commits = %d, want none", got) + } + checkChunk(t, store, "/ckpt/run/f", updatedChunk) + checkDeletions(t, f, storedChunk) +}