diff --git a/weed/filer/abstract_sql/abstract_sql_store.go b/weed/filer/abstract_sql/abstract_sql_store.go index fdbb7a8adb..f51e0edf69 100644 --- a/weed/filer/abstract_sql/abstract_sql_store.go +++ b/weed/filer/abstract_sql/abstract_sql_store.go @@ -88,6 +88,15 @@ type TxOrDB interface { QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) } +// IsolatesTransactions: entry and KV calls take the sql.Tx their context +// carries (getTxOrDB, kvDB), and the database keeps a transaction's writes to +// itself until its commit. Bucket tables are created and dropped outside it. +func (store *AbstractSqlStore) IsolatesTransactions() bool { + return true +} + +var _ filer.IsolatingTransactionStore = (*AbstractSqlStore)(nil) + func (store *AbstractSqlStore) BeginTransaction(ctx context.Context) (context.Context, error) { tx, err := store.DB.BeginTx(ctx, &sql.TxOptions{ Isolation: sql.LevelReadCommitted, diff --git a/weed/filer/abstract_sql/abstract_sql_store_test.go b/weed/filer/abstract_sql/abstract_sql_store_test.go index 7c2f1ad3d3..5d72e9d251 100644 --- a/weed/filer/abstract_sql/abstract_sql_store_test.go +++ b/weed/filer/abstract_sql/abstract_sql_store_test.go @@ -2,6 +2,7 @@ package abstract_sql import ( "context" + "database/sql" "errors" "reflect" "testing" @@ -214,3 +215,70 @@ func TestListDirectoryEntriesStoppedByCallbackWithCanceledContext(t *testing.T) t.Fatalf("ListDirectoryEntries error = %v, want nil", err) } } + +type writeGen struct{ SqlGenerator } + +func (writeGen) GetSqlInsert(string) string { return "INSERT entry" } +func (writeGen) GetSqlDelete(string) string { return "DELETE entry" } + +// What IsolatesTransactions declares: an entry write, an entry delete and a KV +// write under a transaction's context all go through that transaction, the KV +// write too when KV has a pool of its own, and a rollback ends it. +func TestWritesUnderATransactionGoThroughIt(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatal(err) + } + defer db.Close() + // nothing is expected of the KV pool: a call to it fails the write + kvDB, kvMock, err := sqlmock.New() + if err != nil { + t.Fatal(err) + } + defer kvDB.Close() + + mock.ExpectBegin() + mock.ExpectExec("INSERT entry").WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec("DELETE entry").WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec("INSERT entry").WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectRollback() + + store := &AbstractSqlStore{SqlGenerator: writeGen{}, DB: db, KvDB: kvDB} + if !store.IsolatesTransactions() { + t.Fatal("IsolatesTransactions = false") + } + txCtx, err := store.BeginTransaction(context.Background()) + if err != nil { + t.Fatalf("BeginTransaction: %v", err) + } + // one mock serves the pool and its transactions alike, so the expectations + // alone would also pass for writes through store.DB + tx, _ := txCtx.Value("tx").(*sql.Tx) + if tx == nil { + t.Fatal("BeginTransaction context carries no *sql.Tx") + } + if db, _, _, _ := store.getTxOrDB(txCtx, "/dir/new.txt", false); db != TxOrDB(tx) { + t.Fatalf("getTxOrDB under the transaction = %T, want its *sql.Tx", db) + } + if db := store.kvDB(txCtx); db != TxOrDB(tx) { + t.Fatalf("kvDB under the transaction = %T, want its *sql.Tx", db) + } + if err := store.InsertEntry(txCtx, &filer.Entry{FullPath: "/dir/new.txt"}); err != nil { + t.Fatalf("InsertEntry: %v", err) + } + if err := store.DeleteEntry(txCtx, "/dir/old.txt"); err != nil { + t.Fatalf("DeleteEntry: %v", err) + } + if err := store.KvPut(txCtx, []byte("hard-link-id"), []byte("record")); err != nil { + t.Fatalf("KvPut: %v", err) + } + if err := store.RollbackTransaction(txCtx); err != nil { + t.Fatalf("RollbackTransaction: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Error(err) + } + if err := kvMock.ExpectationsWereMet(); err != nil { + t.Error(err) + } +} diff --git a/weed/filer/filer.go b/weed/filer/filer.go index a37a689ab8..4da3e17984 100644 --- a/weed/filer/filer.go +++ b/weed/filer/filer.go @@ -473,6 +473,18 @@ func (f *Filer) BeginTransaction(ctx context.Context) (context.Context, error) { return context.WithValue(txCtx, storeTransactionKey{}, true), nil } +// TransactionCovers reports whether ctx is inside a store transaction that +// covers the writes to the entries at paths: the default store isolates its +// transactions and holds those entries. Such writes show to no other reader +// before the commit, and a refused commit leaves none of them behind. +func (f *Filer) TransactionCovers(ctx context.Context, paths ...util.FullPath) bool { + if ctx.Value(storeTransactionKey{}) == nil { + return false + } + fsw, ok := f.Store.(*FilerStoreWrapper) + return ok && fsw.transactionCovers(paths...) +} + func (f *Filer) CommitTransaction(ctx context.Context) error { return f.Store.CommitTransaction(ctx) } diff --git a/weed/filer/filerstore.go b/weed/filer/filerstore.go index 3a3a7c0413..b618c842eb 100644 --- a/weed/filer/filerstore.go +++ b/weed/filer/filerstore.go @@ -15,6 +15,10 @@ var ( ErrUnsupportedSuperLargeDirectoryListing = errors.New("unsupported super large directory listing") ErrKvNotImplemented = errors.New("kv not implemented yet") ErrKvNotFound = errors.New("kv: not found") + // ErrTransactionConflict marks a commit the store refused because another + // writer changed a key the transaction wrote after it began. Running the + // transaction again reads that write. + ErrTransactionConflict = errors.New("transaction conflict") ) type ListEachEntryFunc func(entry *Entry) (bool, error) @@ -76,3 +80,14 @@ type BucketAware interface { type Debuggable interface { Debug(writer io.Writer) } + +// IsolatingTransactionStore is implemented by a store whose transactions are +// real: the entry and KV writes made under the context BeginTransaction +// returns go through that transaction, stay invisible to other readers until +// CommitTransaction, and are undone by RollbackTransaction. A store says so +// itself, once that has been checked for it: the SQL stores and TiKV do. It +// cannot be told from the context a store hands back, which may carry a +// transaction that its writes do not use. +type IsolatingTransactionStore interface { + IsolatesTransactions() bool +} diff --git a/weed/filer/filerstore_wrapper.go b/weed/filer/filerstore_wrapper.go index fe1ef136f1..de343b9c95 100644 --- a/weed/filer/filerstore_wrapper.go +++ b/weed/filer/filerstore_wrapper.go @@ -447,6 +447,24 @@ func (fsw *FilerStoreWrapper) prefixFilterEntries(ctx context.Context, dirPath u return } +// transactionCovers reports whether a transaction of the default store covers +// the writes to the entries at paths: the store's transactions are real +// (IsolatingTransactionStore) and it holds those entries. The writes of a +// path-specific store bypass the default store's transaction. An entry in the +// default store has its parents there too. +func (fsw *FilerStoreWrapper) transactionCovers(paths ...util.FullPath) bool { + isolating, ok := fsw.defaultStore.(IsolatingTransactionStore) + if !ok || !isolating.IsolatesTransactions() { + return false + } + for _, p := range paths { + if fsw.getActualStore(p) != fsw.defaultStore { + return false + } + } + return true +} + func (fsw *FilerStoreWrapper) BeginTransaction(ctx context.Context) (context.Context, error) { if err := ctx.Err(); err != nil { return nil, err diff --git a/weed/filer/tikv/tikv_store.go b/weed/filer/tikv/tikv_store.go index 0cff2d1867..8d8877113d 100644 --- a/weed/filer/tikv/tikv_store.go +++ b/weed/filer/tikv/tikv_store.go @@ -371,11 +371,30 @@ func (store *TikvStore) BeginTransaction(ctx context.Context) (context.Context, func (store *TikvStore) CommitTransaction(ctx context.Context) error { if tx, ok := ctx.Value("tx").(*txnkv.KVTxn); ok { - return tx.Commit(context.Background()) + return commitError(tx.Commit(context.Background())) } return nil } +// IsolatesTransactions: every entry and KV call takes the transaction its +// context carries (getTxn), and TiKV keeps a transaction's writes to itself +// until its commit. +func (store *TikvStore) IsolatesTransactions() bool { + return true +} + +var _ filer.IsolatingTransactionStore = (*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. +func commitError(err error) error { + if tikverr.IsErrWriteConflict(err) { + return fmt.Errorf("%w: %w", filer.ErrTransactionConflict, err) + } + return err +} + func (store *TikvStore) RollbackTransaction(ctx context.Context) error { if tx, ok := ctx.Value("tx").(*txnkv.KVTxn); ok { return tx.Rollback() diff --git a/weed/filer/tikv/tikv_store_commit_test.go b/weed/filer/tikv/tikv_store_commit_test.go new file mode 100644 index 0000000000..f69cf5334e --- /dev/null +++ b/weed/filer/tikv/tikv_store_commit_test.go @@ -0,0 +1,38 @@ +//go:build tikv + +package tikv + +import ( + "errors" + "fmt" + "strings" + "testing" + + tikverr "github.com/tikv/client-go/v2/error" + + "github.com/seaweedfs/seaweedfs/weed/filer" +) + +// A commit TiKV refuses because another writer committed one of the +// transaction's keys after it began is a transaction conflict, however the +// client wrapped it; the message keeps TiKV's details. +func TestCommitErrorMarksWriteConflicts(t *testing.T) { + conflict := tikverr.NewErrWriteConflictWithArgs(470569654678716421, 470569654678716448, 0, []byte("k"), 0) + for _, err := range []error{conflict, fmt.Errorf("commit: %w", conflict)} { + got := commitError(err) + if !errors.Is(got, filer.ErrTransactionConflict) { + t.Errorf("commitError(%v) = %v, want a transaction conflict", err, got) + } + if !strings.Contains(got.Error(), "write conflict") || !strings.Contains(got.Error(), "470569654678716448") { + t.Errorf("commitError(%v) = %q, want TiKV's details kept", err, got) + } + } + + other := errors.New("region is unavailable") + if got := commitError(other); got != other { + t.Errorf("commitError(%v) = %v, want it unchanged", other, got) + } + if got := commitError(nil); got != nil { + t.Errorf("commitError(nil) = %v, want nil", got) + } +} diff --git a/weed/server/filer_grpc_server_rename.go b/weed/server/filer_grpc_server_rename.go index 9992391172..df6ad1581d 100644 --- a/weed/server/filer_grpc_server_rename.go +++ b/weed/server/filer_grpc_server_rename.go @@ -50,56 +50,31 @@ func (fs *FilerServer) AtomicRenameEntry(ctx context.Context, req *filer_pb.Atom // a SQL store keeps the transaction in the context and refuses calls // through it once committed; the work after the commit uses this one afterCommitCtx := ctx - ctx, err := fs.filer.BeginTransaction(ctx) + effects, err := fs.runRenameTransaction(ctx, fmt.Sprintf("%s/%s", req.OldDirectory, req.OldName), func(ctx context.Context, effects *renameEffects) (bool, error) { + oldEntry, err := fs.filer.FindEntry(ctx, oldParent.Child(req.OldName)) + if err != nil { + return false, fmt.Errorf("%s/%s not found: %v", req.OldDirectory, req.OldName, err) + } + + // The check runs under the rename path locks, which CreateEntry on the same + // filer also takes, so a target created concurrently cannot slip through. + if req.FailIfTargetExists && newParent.Child(req.NewName) != oldParent.Child(req.OldName) { + if _, findErr := fs.filer.FindEntry(ctx, newParent.Child(req.NewName)); findErr == nil { + return false, fmt.Errorf("%s/%s: %w", req.NewDirectory, req.NewName, filer_pb.ErrEntryAlreadyExists) + } else if findErr != filer_pb.ErrNotFound { + return false, findErr + } + } + + if moveErr := fs.moveEntry(ctx, nil, oldParent, oldEntry, newParent, req.NewName, req.Signatures, false, &effects.metadataEvents, &effects.pendingChunkDeletes, &effects.pendingRemoteCopies); moveErr != nil { + return false, fmt.Errorf("%s/%s move error: %v", req.OldDirectory, req.OldName, moveErr) + } + return fs.filer.TransactionCovers(ctx, oldParent.Child(req.OldName), newParent.Child(req.NewName)) && retryableRename(oldEntry, effects), nil + }) if err != nil { return nil, err } - - oldEntry, err := fs.filer.FindEntry(ctx, oldParent.Child(req.OldName)) - if err != nil { - fs.filer.RollbackTransaction(ctx) - return nil, fmt.Errorf("%s/%s not found: %v", req.OldDirectory, req.OldName, err) - } - - // The check runs under the rename path locks, which CreateEntry on the same - // filer also takes, so a target created concurrently cannot slip through. - if req.FailIfTargetExists && newParent.Child(req.NewName) != oldParent.Child(req.OldName) { - if _, findErr := fs.filer.FindEntry(ctx, newParent.Child(req.NewName)); findErr == nil { - fs.filer.RollbackTransaction(ctx) - return nil, fmt.Errorf("%s/%s: %w", req.NewDirectory, req.NewName, filer_pb.ErrEntryAlreadyExists) - } else if findErr != filer_pb.ErrNotFound { - fs.filer.RollbackTransaction(ctx) - return nil, findErr - } - } - - var metadataEvents []metadataEvent - var pendingChunkDeletes []*filer_pb.FileChunk - var pendingRemoteCopies []*pendingRemoteCopy - moveErr := fs.moveEntry(ctx, nil, oldParent, oldEntry, newParent, req.NewName, req.Signatures, false, &metadataEvents, &pendingChunkDeletes, &pendingRemoteCopies) - if moveErr != nil { - releaseMetadataEventStamps(fs.filer, metadataEvents) - fs.filer.RollbackTransaction(ctx) - return nil, fmt.Errorf("%s/%s move error: %v", req.OldDirectory, req.OldName, moveErr) - } else { - if commitError := fs.filer.CommitTransaction(ctx); commitError != nil { - releaseMetadataEventStamps(fs.filer, metadataEvents) - fs.filer.RollbackTransaction(ctx) - return nil, fmt.Errorf("%s/%s move commit error: %v", req.OldDirectory, req.OldName, commitError) - } - } - // Chunks from an overwritten rename target are only deletable after the - // rename transaction has committed: anything that fails mid-rename (move, - // child moves, oldPath delete, CommitTransaction) would otherwise leave - // live metadata pointing at freshly-deleted chunks. - if len(pendingChunkDeletes) > 0 { - fs.filer.DeleteChunksNotRecursive(pendingChunkDeletes) - } - fs.finishRemoteCopies(afterCommitCtx, pendingRemoteCopies) - applyRemoteCopies(metadataEvents, pendingRemoteCopies) - for _, event := range metadataEvents { - event.notify(fs.filer, afterCommitCtx, req.Signatures) - } + fs.finishRename(afterCommitCtx, effects, req.Signatures) return &filer_pb.AtomicRenameEntryResponse{}, nil } @@ -117,60 +92,170 @@ func (fs *FilerServer) StreamRenameEntry(req *filer_pb.StreamRenameEntryRequest, defer fs.acquireRenamePathLocks("StreamRenameEntry", oldParent.Child(req.OldName), newParent.Child(req.NewName))() - ctx := context.Background() + afterCommitCtx := context.Background() + var held *renameResponseBuffer + effects, err := fs.runRenameTransaction(afterCommitCtx, fmt.Sprintf("%s/%s", req.OldDirectory, req.OldName), func(ctx context.Context, effects *renameEffects) (bool, error) { + held = nil + oldEntry, err := fs.filer.FindEntry(ctx, oldParent.Child(req.OldName)) + if err != nil { + return false, fmt.Errorf("%s/%s not found: %v", req.OldDirectory, req.OldName, err) + } - afterCommitCtx := ctx - ctx, err = fs.filer.BeginTransaction(ctx) + if oldEntry.IsDirectory() { + // follow https://pubs.opengroup.org/onlinepubs/000095399/functions/rename.html + targetDir := newParent.Child(req.NewName) + newEntry, err := fs.filer.FindEntry(ctx, targetDir) + if err == nil { + if !newEntry.IsDirectory() { + return false, fmt.Errorf("%s is not directory", targetDir) + } + if entries, _, _ := fs.filer.ListDirectoryEntries(ctx, targetDir, "", false, 1, "", "", ""); len(entries) > 0 { + return false, fmt.Errorf("%s is not empty", targetDir) + } + } + } + + // The client applies each response as it arrives. When the store's + // transaction covers the rename's writes, a file's responses wait for + // the commit: a rename the store refuses never reaches the client, and + // one that runs again sends them once. A directory sends its + // children's as it moves them, which keeps the client of a long rename + // from timing out; having sent them, it does not run again. Without + // such a transaction the writes show as they are made, and so do the + // responses. + responses := stream + if !oldEntry.IsDirectory() && fs.filer.TransactionCovers(ctx, oldParent.Child(req.OldName), newParent.Child(req.NewName)) { + held = &renameResponseBuffer{SeaweedFiler_StreamRenameEntryServer: stream} + responses = held + } + if moveErr := fs.moveEntry(ctx, responses, oldParent, oldEntry, newParent, req.NewName, req.Signatures, false, &effects.metadataEvents, &effects.pendingChunkDeletes, &effects.pendingRemoteCopies); moveErr != nil { + return false, fmt.Errorf("%s/%s move error: %v", req.OldDirectory, req.OldName, moveErr) + } + return held != nil && retryableRename(oldEntry, effects), nil + }) if err != nil { return err } - - oldEntry, err := fs.filer.FindEntry(ctx, oldParent.Child(req.OldName)) - if err != nil { - fs.filer.RollbackTransaction(ctx) - return fmt.Errorf("%s/%s not found: %v", req.OldDirectory, req.OldName, err) + if held == nil { + fs.finishRename(afterCommitCtx, effects, req.Signatures) + return nil } + // Committed. The held responses go out while the rename finishes what the + // commit leaves (events, chunk deletions, remote copies): a client that + // stopped reading cannot hold that work up, and a slow remote copy does + // not keep the client waiting for its responses. The call returns, and + // gives up the rename's path locks, once both are done. + finished := make(chan struct{}) + go func() { + defer close(finished) + fs.finishRename(afterCommitCtx, effects, req.Signatures) + }() + err = held.release() + <-finished + return err +} - if oldEntry.IsDirectory() { - // follow https://pubs.opengroup.org/onlinepubs/000095399/functions/rename.html - targetDir := newParent.Child(req.NewName) - newEntry, err := fs.filer.FindEntry(ctx, targetDir) - if err == nil { - if !newEntry.IsDirectory() { - fs.filer.RollbackTransaction(ctx) - return fmt.Errorf("%s is not directory", targetDir) - } - if entries, _, _ := fs.filer.ListDirectoryEntries(ctx, targetDir, "", false, 1, "", "", ""); len(entries) > 0 { - fs.filer.RollbackTransaction(ctx) - return fmt.Errorf("%s is not empty", targetDir) - } +// renameAttempts bounds how often a rename runs its transaction while the +// store refuses the commit for a concurrent write to one of its keys. +const renameAttempts = 5 + +// renameEffects is what a rename's transaction leaves for after its commit. +type renameEffects struct { + metadataEvents []metadataEvent + pendingChunkDeletes []*filer_pb.FileChunk + pendingRemoteCopies []*pendingRemoteCopy +} + +// runRenameTransaction runs attempt in a new store transaction and commits it. +// A store with optimistic transactions (TiKV) refuses the commit when another +// writer changed one of the transaction's keys after it began: a flush of the +// file being renamed, say. While attempt reports that nothing it did has left +// the transaction, it runs again in a new one, which reads that write and +// moves it along instead of failing the rename. +func (fs *FilerServer) runRenameTransaction(ctx context.Context, oldPath string, attempt func(ctx context.Context, effects *renameEffects) (retryable bool, err error)) (*renameEffects, error) { + for n := 1; ; n++ { + txCtx, err := fs.filer.BeginTransaction(ctx) + if err != nil { + return nil, err + } + effects := &renameEffects{} + retryable, err := attempt(txCtx, effects) + if err != nil { + releaseMetadataEventStamps(fs.filer, effects.metadataEvents) + fs.filer.RollbackTransaction(txCtx) + return nil, err + } + commitErr := fs.filer.CommitTransaction(txCtx) + if commitErr == nil { + return effects, nil + } + releaseMetadataEventStamps(fs.filer, effects.metadataEvents) + fs.filer.RollbackTransaction(txCtx) + if !retryable || n == renameAttempts || !errors.Is(commitErr, filer.ErrTransactionConflict) { + return nil, fmt.Errorf("%s move commit error: %v", oldPath, commitErr) + } + glog.V(0).Infof("rename %s: running it again (%d of %d) after a concurrent write: %v", oldPath, n+1, renameAttempts, commitErr) + time.Sleep(time.Duration(n) * 10 * time.Millisecond) + } +} + +// retryableRename reports whether a rename's transaction may run again after +// the store refused its commit: a file move that did nothing outside the +// transaction. A remote object copied or deleted on the way, for the file or +// for the target it replaced, would stay copied or deleted. The caller also +// checks that the transaction covers the rename's writes (TransactionCovers). +func retryableRename(oldEntry *filer.Entry, effects *renameEffects) bool { + if oldEntry.IsDirectory() || oldEntry.Remote != nil || len(effects.pendingRemoteCopies) > 0 { + return false + } + for _, event := range effects.metadataEvents { + if event.oldEntry != nil && event.oldEntry.Remote != nil { + return false } } + return true +} - var metadataEvents []metadataEvent - var pendingChunkDeletes []*filer_pb.FileChunk - var pendingRemoteCopies []*pendingRemoteCopy - moveErr := fs.moveEntry(ctx, stream, oldParent, oldEntry, newParent, req.NewName, req.Signatures, false, &metadataEvents, &pendingChunkDeletes, &pendingRemoteCopies) - if moveErr != nil { - releaseMetadataEventStamps(fs.filer, metadataEvents) - fs.filer.RollbackTransaction(ctx) - return fmt.Errorf("%s/%s move error: %v", req.OldDirectory, req.OldName, moveErr) - } else { - if commitError := fs.filer.CommitTransaction(ctx); commitError != nil { - releaseMetadataEventStamps(fs.filer, metadataEvents) - fs.filer.RollbackTransaction(ctx) - return fmt.Errorf("%s/%s move commit error: %v", req.OldDirectory, req.OldName, commitError) +// finishRename does what a committed rename leaves for after its commit. +func (fs *FilerServer) finishRename(ctx context.Context, effects *renameEffects, signatures []int32) { + // Chunks from an overwritten rename target are only deletable after the + // rename transaction has committed: anything that fails mid-rename (move, + // child moves, oldPath delete, CommitTransaction) would otherwise leave + // live metadata pointing at freshly-deleted chunks. + if len(effects.pendingChunkDeletes) > 0 { + fs.filer.DeleteChunksNotRecursive(effects.pendingChunkDeletes) + } + fs.finishRemoteCopies(ctx, effects.pendingRemoteCopies) + applyRemoteCopies(effects.metadataEvents, effects.pendingRemoteCopies) + for _, event := range effects.metadataEvents { + event.notify(fs.filer, ctx, signatures) + } +} + +// renameResponseBuffer holds a rename's responses for its client until the +// transaction that produced them has committed. +type renameResponseBuffer struct { + filer_pb.SeaweedFiler_StreamRenameEntryServer + held []*filer_pb.StreamRenameEntryResponse +} + +// Send keeps resp for after the commit. It fails as the stream would once the +// client has gone away, so a rename whose client canceled is rolled back, as +// it is when the responses go out at once, instead of committed unseen. +func (b *renameResponseBuffer) Send(resp *filer_pb.StreamRenameEntryResponse) error { + if err := b.Context().Err(); err != nil { + return err + } + b.held = append(b.held, resp) + return nil +} + +func (b *renameResponseBuffer) release() error { + for _, resp := range b.held { + if err := b.SeaweedFiler_StreamRenameEntryServer.Send(resp); err != nil { + return err } } - if len(pendingChunkDeletes) > 0 { - fs.filer.DeleteChunksNotRecursive(pendingChunkDeletes) - } - fs.finishRemoteCopies(afterCommitCtx, pendingRemoteCopies) - applyRemoteCopies(metadataEvents, pendingRemoteCopies) - for _, event := range metadataEvents { - event.notify(fs.filer, afterCommitCtx, req.Signatures) - } - return nil } diff --git a/weed/server/filer_grpc_server_rename_conflict_test.go b/weed/server/filer_grpc_server_rename_conflict_test.go new file mode 100644 index 0000000000..e645b04609 --- /dev/null +++ b/weed/server/filer_grpc_server_rename_conflict_test.go @@ -0,0 +1,568 @@ +package weed_server + +import ( + "context" + "errors" + "fmt" + "sort" + "strings" + "testing" + "time" + + "google.golang.org/grpc" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// txnRenameStore keeps a transaction's writes to itself until the commit, the +// way TiKV does: no reader sees them before, a rolled back transaction leaves +// nothing behind, and refuse can turn a commit down the way an optimistic +// store does when another writer committed one of its keys meanwhile. +type txnRenameStore struct { + *renameTestStore + refuse func(commit int) error // commit counts from 1; nil lets every commit through + commits int +} + +type txnRenameWrites map[util.FullPath]*filer.Entry // nil: deleted + +type txnRenameKey struct{} + +// newTxnRenameStore starts with the directory /ckpt. +func newTxnRenameStore() *txnRenameStore { + store := &txnRenameStore{renameTestStore: newRenameTestStore()} + store.entries["/ckpt"] = newDirectoryEntry("/ckpt", 100) + return store +} + +// IsolatesTransactions declares what the store does, as the TiKV store does. +func (s *txnRenameStore) IsolatesTransactions() bool { return true } + +func txnWrites(ctx context.Context) txnRenameWrites { + writes, _ := ctx.Value(txnRenameKey{}).(txnRenameWrites) + return writes +} + +func (s *txnRenameStore) BeginTransaction(ctx context.Context) (context.Context, error) { + return context.WithValue(ctx, txnRenameKey{}, txnRenameWrites{}), nil +} + +func (s *txnRenameStore) CommitTransaction(ctx context.Context) error { + writes := txnWrites(ctx) + if writes == nil { + return nil + } + s.mu.Lock() + s.commits++ + commit := s.commits + s.mu.Unlock() + if s.refuse != nil { + if err := s.refuse(commit); err != nil { + return err + } + } + s.mu.Lock() + defer s.mu.Unlock() + for p, entry := range writes { + if entry == nil { + delete(s.entries, string(p)) + } else { + s.entries[string(p)] = entry + } + } + clear(writes) + return nil +} + +func (s *txnRenameStore) RollbackTransaction(ctx context.Context) error { + clear(txnWrites(ctx)) + return nil +} + +func (s *txnRenameStore) commitCount() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.commits +} + +func (s *txnRenameStore) InsertEntry(ctx context.Context, entry *filer.Entry) error { + if writes := txnWrites(ctx); writes != nil { + writes[entry.FullPath] = entry.ShallowClone() + return nil + } + return s.renameTestStore.InsertEntry(ctx, entry) +} + +func (s *txnRenameStore) UpdateEntry(ctx context.Context, entry *filer.Entry) error { + return s.InsertEntry(ctx, entry) +} + +func (s *txnRenameStore) DeleteEntry(ctx context.Context, p util.FullPath) error { + if writes := txnWrites(ctx); writes != nil { + writes[p] = nil + return nil + } + return s.renameTestStore.DeleteEntry(ctx, p) +} + +func (s *txnRenameStore) FindEntry(ctx context.Context, p util.FullPath) (*filer.Entry, error) { + if entry, found := txnWrites(ctx)[p]; found { + if entry == nil { + return nil, filer_pb.ErrNotFound + } + return entry.ShallowClone(), nil + } + return s.renameTestStore.FindEntry(ctx, p) +} + +func (s *txnRenameStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (string, error) { + return s.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, "", eachEntryFunc) +} + +// ListDirectoryPrefixedEntries lists what the transaction sees: the store as +// committed, with the transaction's own writes over it. +func (s *txnRenameStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (string, error) { + visible := map[util.FullPath]*filer.Entry{} + s.mu.Lock() + for p, entry := range s.entries { + visible[util.FullPath(p)] = entry + } + s.mu.Unlock() + for p, entry := range txnWrites(ctx) { + if entry == nil { + delete(visible, p) + } else { + visible[p] = entry + } + } + var names []string + children := map[string]*filer.Entry{} + for p, entry := range visible { + if parent, name := p.DirAndName(); parent == string(dirPath) && p != dirPath && strings.HasPrefix(name, prefix) { + names = append(names, name) + children[name] = entry + } + } + sort.Strings(names) + lastFileName, count := "", int64(0) + for _, name := range names { + if startFileName != "" && (name < startFileName || name == startFileName && !includeStartFile) { + continue + } + lastFileName = name + more, err := eachEntryFunc(children[name].ShallowClone()) + if err != nil || !more { + return lastFileName, err + } + if count++; limit > 0 && count >= limit { + break + } + } + return lastFileName, nil +} + +// commitStampedStream records each response with the number of commits the +// store had made when it was sent. +type commitStampedStream struct { + grpc.ServerStream + store *txnRenameStore + sent []*filer_pb.StreamRenameEntryResponse + at []int +} + +func (s *commitStampedStream) Context() context.Context { return context.Background() } +func (s *commitStampedStream) Send(resp *filer_pb.StreamRenameEntryResponse) error { + s.sent = append(s.sent, resp) + s.at = append(s.at, s.store.commitCount()) + return nil +} + +func writeConflict(commit int) error { + return fmt.Errorf("%w: write conflict { start_ts:%d conflict_ts:%d reason:Optimistic }", filer.ErrTransactionConflict, commit, commit+27) +} + +// flushedWhileRenaming refuses the first commit the way TiKV does when a +// writer commits the file being renamed after the rename's transaction began, +// and stores what that writer wrote: weed mount publishing the file the +// application is renaming over its target (safetensors, torch.save). +func flushedWhileRenaming(store *txnRenameStore, p string, flushed *filer.Entry) { + store.refuse = func(commit int) error { + if commit > 1 { + return nil + } + store.mu.Lock() + store.entries[p] = flushed + store.mu.Unlock() + return writeConflict(commit) + } +} + +func chunkIds(entry *filer.Entry) []string { + var ids []string + for _, chunk := range entry.GetChunks() { + ids = append(ids, chunk.GetFileIdString()) + } + return ids +} + +func checkRenamedFile(t *testing.T, store *txnRenameStore, src, dst string, wantChunk string) { + t.Helper() + if _, err := store.renameTestStore.FindEntry(context.Background(), util.FullPath(src)); !errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("%s after the rename: %v, want gone", src, err) + } + moved, err := store.renameTestStore.FindEntry(context.Background(), util.FullPath(dst)) + if err != nil { + t.Fatalf("%s after the rename: %v", dst, err) + } + if ids := chunkIds(moved); len(ids) != 1 || ids[0] != wantChunk { + t.Fatalf("%s chunks = %v, want [%s]: the rename must move what the concurrent writer stored", dst, ids, wantChunk) + } +} + +// A writer that commits the file while the rename's transaction runs makes +// TiKV refuse the rename's commit. The rename runs again, moves what the +// writer stored, and its client hears of it once, after the commit. +func TestStreamRenameRunsAgainAfterConcurrentWrite(t *testing.T) { + store := newTxnRenameStore() + store.entries["/ckpt/.tmpTdjXVI"] = fileEntryWithChunk("/ckpt/.tmpTdjXVI", 101, "1,0a01") + flushedWhileRenaming(store, "/ckpt/.tmpTdjXVI", fileEntryWithChunk("/ckpt/.tmpTdjXVI", 101, "2,0b02")) + queue := &captureQueue{} + swapNotificationQueue(t, queue) + server := &FilerServer{filer: newRenameTestFiler(t, store), entryLockTable: util.NewLockTable[util.FullPath]()} + stream := &commitStampedStream{store: store} + + if err := server.StreamRenameEntry(&filer_pb.StreamRenameEntryRequest{ + OldDirectory: "/ckpt", OldName: ".tmpTdjXVI", NewDirectory: "/ckpt", NewName: "ema.safetensors.tmp", + }, stream); err != nil { + t.Fatalf("StreamRenameEntry: %v, want the rename to run again after the conflict", err) + } + + if got := store.commitCount(); got != 2 { + t.Fatalf("commits = %d, want 2", got) + } + checkRenamedFile(t, store, "/ckpt/.tmpTdjXVI", "/ckpt/ema.safetensors.tmp", "2,0b02") + if len(stream.sent) != 2 { + t.Fatalf("client got %d responses, want the committed run's 2", len(stream.sent)) + } + for i, commits := range stream.at { + if commits != 2 { + t.Fatalf("response %d went out after %d commits, want only after the rename committed", i, commits) + } + } + if ids := stream.sent[0].EventNotification.GetNewEntry().GetChunks(); len(ids) != 1 || ids[0].GetFileIdString() != "2,0b02" { + t.Fatalf("client's new entry chunks = %v, want the concurrent writer's", ids) + } + if events := queue.snapshot(); len(events) != 1 || events[0].notification.GetNewEntry().GetName() != "ema.safetensors.tmp" { + t.Fatalf("metadata events = %+v, want the one committed rename", events) + } +} + +func TestAtomicRenameRunsAgainAfterConcurrentWrite(t *testing.T) { + store := newTxnRenameStore() + store.entries["/ckpt/.tmpTdjXVI"] = fileEntryWithChunk("/ckpt/.tmpTdjXVI", 101, "1,0a01") + flushedWhileRenaming(store, "/ckpt/.tmpTdjXVI", fileEntryWithChunk("/ckpt/.tmpTdjXVI", 101, "2,0b02")) + queue := &captureQueue{} + swapNotificationQueue(t, queue) + server := &FilerServer{filer: newRenameTestFiler(t, store), entryLockTable: util.NewLockTable[util.FullPath]()} + + if _, err := server.AtomicRenameEntry(context.Background(), &filer_pb.AtomicRenameEntryRequest{ + OldDirectory: "/ckpt", OldName: ".tmpTdjXVI", NewDirectory: "/ckpt", NewName: "ema.safetensors.tmp", + }); err != nil { + t.Fatalf("AtomicRenameEntry: %v, want the rename to run again after the conflict", err) + } + if got := store.commitCount(); got != 2 { + t.Fatalf("commits = %d, want 2", got) + } + checkRenamedFile(t, store, "/ckpt/.tmpTdjXVI", "/ckpt/ema.safetensors.tmp", "2,0b02") + if events := queue.snapshot(); len(events) != 1 { + t.Fatalf("metadata events = %d, want the one committed rename", len(events)) + } +} + +// A rename the store refuses for good must not reach the client: weed mount +// applies each response as it arrives, and would hold the file under a name +// the filer never gave it. +func TestStreamRenameRefusedCommitSendsNothing(t *testing.T) { + for _, tc := range []struct { + name string + refuse func(commit int) error + wantCommits int + }{ + {"other error", func(int) error { return errors.New("region is unavailable") }, 1}, + {"conflicts every time", writeConflict, renameAttempts}, + } { + t.Run(tc.name, func(t *testing.T) { + store := newTxnRenameStore() + store.entries["/ckpt/.tmpA"] = fileEntryWithChunk("/ckpt/.tmpA", 101, "1,0a01") + store.refuse = tc.refuse + queue := &captureQueue{} + swapNotificationQueue(t, queue) + server := &FilerServer{filer: newRenameTestFiler(t, store), entryLockTable: util.NewLockTable[util.FullPath]()} + stream := &commitStampedStream{store: store} + + err := server.StreamRenameEntry(&filer_pb.StreamRenameEntryRequest{ + OldDirectory: "/ckpt", OldName: ".tmpA", NewDirectory: "/ckpt", NewName: "ema.safetensors", + }, stream) + if err == nil || !strings.Contains(err.Error(), "move commit error") { + t.Fatalf("StreamRenameEntry = %v, want the commit error", err) + } + if got := store.commitCount(); got != tc.wantCommits { + t.Fatalf("commits = %d, want %d", got, tc.wantCommits) + } + if len(stream.sent) != 0 { + t.Fatalf("client got %d responses for a rename that did not happen", len(stream.sent)) + } + if events := queue.snapshot(); len(events) != 0 { + t.Fatalf("metadata events = %d for a rename that did not happen", len(events)) + } + if _, err := store.renameTestStore.FindEntry(context.Background(), "/ckpt/.tmpA"); err != nil { + t.Fatalf("source after the refused rename: %v", err) + } + if _, err := store.renameTestStore.FindEntry(context.Background(), "/ckpt/ema.safetensors"); !errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("target after the refused rename: %v, want absent", err) + } + }) + } +} + +// A directory's rename sends its children's events as it moves them, which +// keeps its client from timing out on a long one; having sent them, it is +// not run again. +func TestStreamRenameOfDirectoryIsNotRunAgain(t *testing.T) { + store := newTxnRenameStore() + store.entries["/a"] = newDirectoryEntry("/a", 1) + store.entries["/a/f"] = fileEntryWithChunk("/a/f", 2, "1,0a01") + store.refuse = writeConflict + swapNotificationQueue(t, &captureQueue{}) + server := &FilerServer{filer: newRenameTestFiler(t, store), entryLockTable: util.NewLockTable[util.FullPath]()} + stream := &commitStampedStream{store: store} + + err := server.StreamRenameEntry(&filer_pb.StreamRenameEntryRequest{ + OldDirectory: "/", OldName: "a", NewDirectory: "/", NewName: "b", + }, stream) + if err == nil || !strings.Contains(err.Error(), "move commit error") { + t.Fatalf("StreamRenameEntry = %v, want the commit error", err) + } + if got := store.commitCount(); got != 1 { + t.Fatalf("commits = %d, want 1: a directory rename is not run again", got) + } + if len(stream.sent) == 0 { + t.Fatal("a directory rename streams its events as it moves the entries") + } +} + +// A file with a remote object is not run again: the move may have copied or +// deleted that object, outside the store's transaction. +func TestStreamRenameOfRemoteFileIsNotRunAgain(t *testing.T) { + store := newTxnRenameStore() + remote := fileEntryWithChunk("/ckpt/r.bin", 101, "1,0a01") + remote.Remote = &filer_pb.RemoteEntry{StorageName: "s3", RemoteSize: 10, RemoteMtime: 1} + store.entries["/ckpt/r.bin"] = remote + store.refuse = writeConflict + swapNotificationQueue(t, &captureQueue{}) + server := &FilerServer{filer: newRenameTestFiler(t, store), entryLockTable: util.NewLockTable[util.FullPath]()} + stream := &commitStampedStream{store: store} + + err := server.StreamRenameEntry(&filer_pb.StreamRenameEntryRequest{ + OldDirectory: "/ckpt", OldName: "r.bin", NewDirectory: "/ckpt", NewName: "s.bin", + }, stream) + if err == nil || !strings.Contains(err.Error(), "move commit error") { + t.Fatalf("StreamRenameEntry = %v, want the commit error", err) + } + if got := store.commitCount(); got != 1 { + t.Fatalf("commits = %d, want 1: a remote file's rename is not run again", got) + } + if len(stream.sent) != 0 { + t.Fatalf("client got %d responses for a rename that did not happen", len(stream.sent)) + } +} + +// A store that does not declare isolating transactions keeps the responses +// going out as the entry moves, as before: one without transactions, where +// each write shows at once, and one that hands back a transaction context but +// does not say that its writes go through it. +func TestStreamRenameWithoutIsolatingTransactionsStreamsLive(t *testing.T) { + for _, tc := range []struct { + name string + strictTx bool + }{ + {"no transactions", false}, + {"transactions not declared isolating", true}, + } { + t.Run(tc.name, func(t *testing.T) { + store := newRenameTestStore() + store.strictTx = tc.strictTx + store.entries["/ckpt"] = newDirectoryEntry("/ckpt", 100) + store.entries["/ckpt/.tmpL"] = fileEntryWithChunk("/ckpt/.tmpL", 101, "1,0a01") + swapNotificationQueue(t, &captureQueue{}) + server := &FilerServer{filer: newRenameTestFiler(t, store), entryLockTable: util.NewLockTable[util.FullPath]()} + stream := &renameLiveStream{store: store} + + if err := server.StreamRenameEntry(&filer_pb.StreamRenameEntryRequest{ + OldDirectory: "/ckpt", OldName: ".tmpL", NewDirectory: "/ckpt", NewName: "l.bin", + }, stream); err != nil { + t.Fatalf("StreamRenameEntry: %v", err) + } + if len(stream.sourceAt) != 2 || !stream.sourceAt[0] { + t.Fatalf("responses saw the source as %v, want the first sent while the move was still under way", stream.sourceAt) + } + }) + } +} + +// renameLiveStream records, for each response, whether the source entry was +// still in the store when it was sent. +type renameLiveStream struct { + grpc.ServerStream + store *renameTestStore + sourceAt []bool +} + +func (s *renameLiveStream) Context() context.Context { return context.Background() } +func (s *renameLiveStream) Send(resp *filer_pb.StreamRenameEntryResponse) error { + _, err := s.store.FindEntry(context.Background(), "/ckpt/.tmpL") + s.sourceAt = append(s.sourceAt, err == nil) + return nil +} + +// A path-specific store's writes bypass the default store's transaction. A +// rename that writes there is not run again; one that stays in the default +// store is, as without the path-specific store. +func TestRenameWithPathSpecificStore(t *testing.T) { + for _, tc := range []struct { + name, newDir string + wantCommits int + }{ + {"into it", "/ckpt/archive", 1}, + {"elsewhere", "/ckpt", 2}, + } { + for _, stream := range []bool{true, false} { + t.Run(tc.name+map[bool]string{true: "/stream", false: "/atomic"}[stream], func(t *testing.T) { + store := newTxnRenameStore() + store.entries["/ckpt/.tmpP"] = fileEntryWithChunk("/ckpt/.tmpP", 101, "1,0a01") + if tc.wantCommits == 1 { + store.refuse = writeConflict + } else { + flushedWhileRenaming(store, "/ckpt/.tmpP", fileEntryWithChunk("/ckpt/.tmpP", 101, "2,0b02")) + } + swapNotificationQueue(t, &captureQueue{}) + f := newRenameTestFiler(t, store) + f.Store.(*filer.FilerStoreWrapper).AddPathSpecificStore("/ckpt/archive/", "archive", newRenameTestStore()) + server := &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()} + + responses := &commitStampedStream{store: store} + var err error + if stream { + err = server.StreamRenameEntry(&filer_pb.StreamRenameEntryRequest{ + OldDirectory: "/ckpt", OldName: ".tmpP", NewDirectory: tc.newDir, NewName: "p.bin", + }, responses) + } else { + _, err = server.AtomicRenameEntry(context.Background(), &filer_pb.AtomicRenameEntryRequest{ + OldDirectory: "/ckpt", OldName: ".tmpP", NewDirectory: tc.newDir, NewName: "p.bin", + }) + } + if tc.wantCommits == 1 && (err == nil || !strings.Contains(err.Error(), "move commit error")) { + t.Fatalf("rename = %v, want the commit error", err) + } else if tc.wantCommits == 2 && err != nil { + t.Fatalf("rename = %v, want it run again after the conflict", err) + } + if got := store.commitCount(); got != tc.wantCommits { + t.Fatalf("commits = %d, want %d", got, tc.wantCommits) + } + if tc.wantCommits == 2 && stream { + for i, commits := range responses.at { + if commits != 2 { + t.Fatalf("response %d went out after %d commits, want only after the rename committed", i, commits) + } + } + } + }) + } + } +} + +// canceledRenameStream stands for a client that went away before the rename +// sent anything. +type canceledRenameStream struct { + grpc.ServerStream + ctx context.Context +} + +func (s *canceledRenameStream) Context() context.Context { return s.ctx } +func (s *canceledRenameStream) Send(*filer_pb.StreamRenameEntryResponse) error { + return s.ctx.Err() +} + +// A rename whose client canceled before its first response is rolled back, +// as it is when the responses go out at once, not committed unseen. +func TestStreamRenameWhoseClientCanceledIsRolledBack(t *testing.T) { + store := newTxnRenameStore() + store.entries["/ckpt/.tmpC"] = fileEntryWithChunk("/ckpt/.tmpC", 101, "1,0a01") + swapNotificationQueue(t, &captureQueue{}) + server := &FilerServer{filer: newRenameTestFiler(t, store), entryLockTable: util.NewLockTable[util.FullPath]()} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + err := server.StreamRenameEntry(&filer_pb.StreamRenameEntryRequest{ + OldDirectory: "/ckpt", OldName: ".tmpC", NewDirectory: "/ckpt", NewName: "c.bin", + }, &canceledRenameStream{ctx: ctx}) + if err == nil { + t.Fatal("StreamRenameEntry = nil, want the cancellation") + } + if got := store.commitCount(); got != 0 { + t.Fatalf("commits = %d, want the canceled rename rolled back", got) + } + if _, err := store.renameTestStore.FindEntry(context.Background(), "/ckpt/.tmpC"); err != nil { + t.Fatalf("source after the canceled rename: %v", err) + } +} + +// unreadRenameStream stands for a client that stopped reading: Send waits +// until the test lets it go. +type unreadRenameStream struct { + grpc.ServerStream + release chan struct{} +} + +func (s *unreadRenameStream) Context() context.Context { return context.Background() } +func (s *unreadRenameStream) Send(*filer_pb.StreamRenameEntryResponse) error { + <-s.release + return nil +} + +// A committed rename finishes (events, chunk deletions) before its held +// responses go out, so a client that stops reading cannot hold that up. +func TestStreamRenameFinishesBeforeTheClientReads(t *testing.T) { + store := newTxnRenameStore() + store.entries["/ckpt/.tmpB"] = fileEntryWithChunk("/ckpt/.tmpB", 101, "1,0a01") + store.entries["/ckpt/b.bin"] = fileEntryWithChunk("/ckpt/b.bin", 102, "2,0b02") + queue := &captureQueue{} + swapNotificationQueue(t, queue) + f := newRenameTestFiler(t, store) + server := &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()} + stream := &unreadRenameStream{release: make(chan struct{})} + done := make(chan error, 1) + go func() { + done <- server.StreamRenameEntry(&filer_pb.StreamRenameEntryRequest{ + OldDirectory: "/ckpt", OldName: ".tmpB", NewDirectory: "/ckpt", NewName: "b.bin", + }, stream) + }() + defer func() { + close(stream.release) + if err := <-done; err != nil { + t.Errorf("StreamRenameEntry: %v", err) + } + }() + + for deadline := time.Now().Add(10 * time.Second); len(queue.snapshot()) < 2 && time.Now().Before(deadline); { + time.Sleep(10 * time.Millisecond) + } + if events := queue.snapshot(); len(events) != 2 { + t.Fatalf("metadata events = %d while the client does not read, want the target's delete and the rename", len(events)) + } + if got := queuedDeletions(f); len(got) != 1 || got[0] != "2,0b02" { + t.Fatalf("queued chunk deletions = %v while the client does not read, want the replaced file's 2,0b02", got) + } +}