Compare commits

...
Author SHA1 Message Date
github-actions[bot] 93c6f8d64a docs: regenerate star history chart 2026-11-24 01:45:48 +00:00
89d5192831 filer: guard entry updates against rename/delete races (TiKV, FoundationDB) (#12918)
* filer: run an entry update again when a rename or delete of it commits meanwhile

UpdateEntry reads the entry, checks its preconditions against it, then
writes. The path lock keeps the two together only against writers of that
path on that filer. A rename or a delete sent to another filer does not
take it, and on any filer a rename or recursive delete of a directory above
the entry moves and removes what is below it unlocked. One that committed
between the read and the write had the write store the entry again at the
path it had left, and the update returned success: the entry back under a
directory that is gone, two names sharing chunks, or a file back after its
unlink returned.

Where the store refuses a conflicting commit, the read, the checks and the
write now run in one store transaction. The rename or delete wrote the
entry's key after it began, so the commit is refused with
ErrTransactionConflict and the update runs again, up to five times with
the rename's back-off, and answers from what is there now.

- filer.ConflictRefusingStore is how a store says so. TiKV does. Other
  stores, and entries in a path-specific store, run once without a
  transaction, as before.
- A refused run gives up its commit stamp and deletes the manifest chunks
  it folded the request's chunks into.
- Chunk deletion and the metadata event come after the commit, in the
  order they had.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: commit what an update's lookup removed, give up a failed run's manifests

From the review of 156a0078c.

FindEntry removes an expired entry and, for an expired S3 object, tells the
subscribers. Inside the update's transaction a NotFound rolled that removal
back while the event stayed, and the next lookup announced it again. What
the read answers the update with (the entry is not there, a precondition
does not hold) is now the run's result and not its failure: the run commits
whatever the lookup removed and UpdateEntry returns the answer. Only an
error of the write itself rolls back.

A run that fails after cleanupChunks folded the request's chunks into
manifests is rolled back, so nothing refers to them: it now gives them up
the way a run with a refused commit does. The cleanup tolerates a run that
got no further than its lookup.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: leave an expired S3 object to a lookup outside a transaction

FindEntry's removal of an expired S3 object deletes a remote copy and
publishes a delete event at once. Inside a store transaction a refused
commit restores the entry but not those, so subscribers could keep a
delete for a path that still holds an entry. A lookup in a transaction
now only answers NotFound and leaves the removal to one outside it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: guard update retries and retain expired rename targets

Reject retries when the originally observed entry changes, so stale requests cannot restore chunks already deleted by a concurrent writer. Keep expired S3 overwrite targets visible to rename cleanup, and defer overwritten remote-object deletion until commit succeeds. Add regression coverage for concurrent updates and renames, both rename RPCs, remote data, and rollback.

* filer: extend conflict-checked entry updates to FoundationDB

Specify the optional capability in terms of entry/KV read-modify-write conflicts, without promising atomic bulk operations or blind-write conflicts. Opt FoundationDB into the update transaction path and normalize only known uncommitted conflicts. Add routing, error-classification, and live FoundationDB entry/KV conflict tests, and document its transaction boundaries.

* filer: prepare update manifests outside metadata transactions

* filer: keep update rereads from restoring renamed remote entries

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-11-23 15:58:12 -08:00
14 changed files with 2027 additions and 1069 deletions

No files matched your search

+1013 -1019
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 53 KiB

+33 -2
View File
@@ -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.
@@ -1004,8 +1013,12 @@ func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, e
if entry != nil && entry.TtlSec > 0 && !entry.IsDirectory() {
if entry.IsExpireS3Enabled() {
if entry.GetS3ExpireTime().Before(time.Now()) && !entry.IsS3Versioning() {
if delErr := f.doDeleteEntryMetaAndData(ctx, entry, true, false, nil); delErr != nil {
glog.ErrorfCtx(ctx, "FindEntry doDeleteEntryMetaAndData %s failed: %v", entry.FullPath, delErr)
// Its remote delete and event would outlive a refused commit, so a
// lookup outside a transaction removes it.
if ctx.Value(storeTransactionKey{}) == nil {
if delErr := f.doDeleteEntryMetaAndData(ctx, entry, true, false, nil); delErr != nil {
glog.ErrorfCtx(ctx, "FindEntry doDeleteEntryMetaAndData %s failed: %v", entry.FullPath, delErr)
}
}
return nil, filer_pb.ErrNotFound
}
@@ -1026,6 +1039,24 @@ func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, e
return entry, err
}
// FindEntryWithoutRemoteFetch applies the usual expiry checks but leaves a
// missing filer entry absent, even when its remote object still exists.
func (f *Filer) FindEntryWithoutRemoteFetch(ctx context.Context, p util.FullPath) (*Entry, error) {
return f.FindEntry(context.WithValue(ctx, lazyFetchContextKey{}, true), p)
}
// FindEntryForOverwrite also returns an expired S3 entry retained inside a
// transaction. A replacement must account for its chunks and hard links and
// publish its deletion after commit: once overwritten, no later lookup can
// discover it for expiry cleanup. Ordinary lookups still see it as absent.
func (f *Filer) FindEntryForOverwrite(ctx context.Context, p util.FullPath) (*Entry, error) {
entry, err := f.FindEntry(ctx, p)
if errors.Is(err, filer_pb.ErrNotFound) && ctx.Value(storeTransactionKey{}) != nil {
return f.Store.FindEntry(ctx, p)
}
return entry, err
}
func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, startFileName string, inclusive bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (expiredCount int64, lastFileName string, err error) {
f.maybeLazyListFromRemote(ctx, p)
+1 -1
View File
@@ -123,7 +123,7 @@ func (f *Filer) DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isR
ctx = f.syncWriteContext(ctx, p)
entry, findErr := f.FindEntry(ctx, p)
entry, findErr := f.FindEntryForOverwrite(ctx, p)
if findErr != nil {
return findErr
}
+18 -2
View File
@@ -16,8 +16,9 @@ var (
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.
// writer changed a key the transaction read or wrote. No writes from the
// refused transaction were committed; an unknown commit result must not
// carry this sentinel. Running the transaction again reads the other write.
ErrTransactionConflict = errors.New("transaction conflict")
)
@@ -92,6 +93,21 @@ type IsolatingTransactionStore interface {
IsolatesTransactions() bool
}
// ConflictRefusingStore protects a read-modify-write of one entry and its
// shared KV records. Entry and KV operations must use the context's transaction,
// keep its writes invisible until commit, and leave none behind on rollback.
// If another writer changes a key this transaction both reads and writes after
// its read version, CommitTransaction must refuse with ErrTransactionConflict.
// Read/write conflicts suffice; blind writes need not conflict with each other.
//
// TiKV and FoundationDB implement this capability. It does not promise that
// bulk operations such as DeleteFolderChildren stay inside the transaction.
// Other stores must opt in only after their entry and KV paths, isolation and
// conflict errors have been checked; having BeginTransaction alone is not enough.
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
+37
View File
@@ -0,0 +1,37 @@
package filer
import (
"context"
"testing"
)
// An entry/KV transaction can be conflict checked even when bulk folder
// deletion escapes it, as on FoundationDB. Keep these capabilities distinct.
type entryConflictTestStore struct {
FilerStore
enabled bool
}
func (s *entryConflictTestStore) RefusesConflictingCommits() bool { return s.enabled }
func TestEntryConflictCapabilityFollowsStoreRouting(t *testing.T) {
for _, enabled := range []bool{false, true} {
store := &entryConflictTestStore{FilerStore: newStubFilerStore(), enabled: enabled}
wrapper := NewFilerStoreWrapper(store)
wrapper.AddPathSpecificStore("/other/", "other", &entryConflictTestStore{FilerStore: newStubFilerStore(), enabled: true})
f := &Filer{Store: wrapper}
if got := f.RefusesConflictingCommits("/default/file"); got != enabled {
t.Fatalf("default store capability = %v, want %v", got, enabled)
}
if f.RefusesConflictingCommits("/other/file") {
t.Fatal("a path-specific store is not covered by the default store's transaction")
}
ctx := context.WithValue(context.Background(), storeTransactionKey{}, true)
if f.TransactionCovers(ctx, "/default/file") {
t.Fatal("entry conflict detection must not imply isolation of bulk operations")
}
}
if NewFilerStoreWrapper(newStubFilerStore()).refusesConflictingCommits("/file") {
t.Fatal("a store without the optional capability must remain unwrapped")
}
}
+9
View File
@@ -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.
+14
View File
@@ -11,6 +11,20 @@ This package provides a FoundationDB-based filer store for SeaweedFS, offering A
- **Key-Value Support**: Full KV operations for metadata storage
- **Compression**: Automatic compression for large entry chunks
## Transaction conflicts
Single-entry updates read the entry and its hard-link KV records in the same
transaction as their writes. A concurrent rename, delete, or update that changes
the entry causes FoundationDB to refuse the commit. The filer retries against
the current entry and refuses to replay a stale update over changed metadata.
Conflicts (`not_committed`, code 1020) are distinguished from an unknown commit
result (1021), which must not be retried or have its manifests deleted.
This capability covers entry and KV operations, including when write batching
is enabled: an explicit transaction bypasses the batcher. It does not make
`DeleteFolderChildren` atomic with an outer transaction; that operation keeps
its separate batch transactions to respect FoundationDB's size and time limits.
## Installation
### Prerequisites
+23 -1
View File
@@ -20,6 +20,7 @@ package foundationdb
import (
"bytes"
"context"
"errors"
"fmt"
"sync"
"time"
@@ -360,12 +361,33 @@ func (store *FoundationDBStore) CommitTransaction(ctx context.Context) error {
// Commit the transaction
err := tx.Commit().Get()
if err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
return fmt.Errorf("failed to commit transaction: %w", commitError(err))
}
return nil
}
// RefusesConflictingCommits covers single-entry updates and their shared KV
// records: ordinary Get reads add conflict ranges, and entry/KV writes use the
// same context transaction, bypassing the batcher. Bulk folder deletion uses
// separate transactions, so this does not advertise IsolatingTransactionStore.
func (store *FoundationDBStore) RefusesConflictingCommits() bool {
return true
}
var _ filer.ConflictRefusingStore = (*FoundationDBStore)(nil)
func commitError(err error) error {
var fdbErr fdb.Error
// not_committed (1020) guarantees that nothing was committed. In
// particular, commit_unknown_result (1021) must not trigger retries or
// disposal of manifests that a successful commit may reference.
if errors.As(err, &fdbErr) && fdbErr.Code == 1020 {
return fmt.Errorf("%w: %w", filer.ErrTransactionConflict, err)
}
return err
}
func (store *FoundationDBStore) RollbackTransaction(ctx context.Context) error {
// Get transaction from context
tx, exists := store.getTransactionFromContext(ctx)
@@ -0,0 +1,110 @@
//go:build foundationdb
package foundationdb
import (
"context"
"errors"
"fmt"
"os"
"testing"
"time"
"github.com/apple/foundationdb/bindings/go/src/fdb"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func TestCommitErrorOnlyMarksKnownUncommittedConflicts(t *testing.T) {
conflict := fdb.Error{Code: 1020}
for _, err := range []error{conflict, fmt.Errorf("commit: %w", conflict)} {
got := commitError(err)
if !errors.Is(got, filer.ErrTransactionConflict) {
t.Fatalf("commitError(%v) = %v, want transaction conflict", err, got)
}
var original fdb.Error
if !errors.As(got, &original) || original.Code != conflict.Code {
t.Fatalf("commitError lost FoundationDB's error: %v", got)
}
}
// An unknown result must not let the retry loop delete manifests that
// may have committed. Timeouts and other errors keep their own meaning.
for _, err := range []error{nil, fdb.Error{Code: 1021}, fmt.Errorf("commit: %w", fdb.Error{Code: 1021}), fdb.Error{Code: 1007}, errors.New("unavailable")} {
if got := commitError(err); got != err {
t.Fatalf("commitError(%v) = %v, want unchanged", err, got)
}
}
}
func TestEntryAndKVTransactionsRefuseConcurrentDeletes(t *testing.T) {
if _, err := os.Stat(getTestClusterFile()); err != nil {
t.Skip("FoundationDB cluster file is not available")
}
store := &FoundationDBStore{directoryPrefix: fmt.Sprintf("seaweedfs-conflict-test-%d", time.Now().UnixNano())}
if err := store.initialize(getTestClusterFile(), 740); err != nil {
t.Fatal(err)
}
t.Cleanup(store.Shutdown)
ctx := context.Background()
path := util.FullPath("/conflict/file")
entry := &filer.Entry{FullPath: path, Attr: filer.Attr{Mode: 0644}}
key, value := []byte("hard-link"), []byte("shared metadata")
for _, kv := range []bool{false, true} {
t.Run(map[bool]string{false: "entry", true: "shared KV"}[kv], func(t *testing.T) {
var err error
if kv {
err = store.KvPut(ctx, key, value)
} else {
err = store.InsertEntry(ctx, entry)
}
if err != nil {
t.Fatal(err)
}
txCtx, err := store.BeginTransaction(ctx)
if err != nil {
t.Fatal(err)
}
defer store.RollbackTransaction(txCtx)
if kv {
_, err = store.KvGet(txCtx, key)
} else {
_, err = store.FindEntry(txCtx, path)
}
if err != nil {
t.Fatal(err)
}
if kv {
err = store.KvDelete(ctx, key)
} else {
err = store.DeleteEntry(ctx, path)
}
if err != nil {
t.Fatal(err)
}
if kv {
err = store.KvPut(txCtx, key, value)
} else {
err = store.UpdateEntry(txCtx, entry)
}
if err != nil {
t.Fatal(err)
}
if err = store.CommitTransaction(txCtx); !errors.Is(err, filer.ErrTransactionConflict) {
t.Fatalf("commit = %v, want transaction conflict", err)
}
if kv {
_, err = store.KvGet(ctx, key)
if !errors.Is(err, filer.ErrKvNotFound) {
t.Fatalf("KV after refused commit = %v, want absent", err)
}
} else {
_, err = store.FindEntry(ctx, path)
if !errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("entry after refused commit = %v, want absent", err)
}
}
})
}
}
+9
View File
@@ -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.
+134 -39
View File
@@ -25,6 +25,7 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
// fencedFindEntry reads an entry with an exact log-position fence: the stamp
@@ -979,10 +980,13 @@ func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntr
}
}
// Serialize concurrent mutations to the same path on this filer so the
// read (preconditions, garbage diff) and the write are atomic. Callers
// route a key's writes to this owner filer, making this local lock
// sufficient.
return fs.updateEntry(ctx, req, fullpath, fs.cleanupChunks)
}
func (fs *FilerServer) updateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest, fullpath string,
prepareChunks func(context.Context, string, *filer.Entry, *filer_pb.Entry) (chunks, garbage []*filer_pb.FileChunk, err error),
) (*filer_pb.UpdateEntryResponse, error) {
// Serialize concurrent mutations to the same path on this filer.
lockPath := util.FullPath(fullpath)
pathLock := fs.entryLockTable.AcquireLock("UpdateEntry", lockPath, util.ExclusiveLock)
defer fs.entryLockTable.ReleaseLock(lockPath, pathLock)
@@ -991,19 +995,57 @@ 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)
transactional := fs.filer.RefusesConflictingCommits(lockPath)
var entry *filer.Entry
var observed *filer_pb.WriteCondition_Clause
var refusal error
findEntry := fs.filer.FindEntry
read := func(ctx context.Context) error {
var err error
refusal = nil
entry, err = findEntry(ctx, lockPath)
// Only the initial lookup may import remote metadata. A rename can
// retain the old remote object after removing its filer entry.
findEntry = fs.filer.FindEntryWithoutRemoteFetch
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
// A TTL lookup can remove the entry. Commit that removal.
refusal = status.Errorf(codes.NotFound, "not found %s: %v", fullpath, err)
return nil
}
return fmt.Errorf("not found %s: %w", fullpath, err)
}
return &filer_pb.UpdateEntryResponse{}, fmt.Errorf("not found %s: %v", fullpath, err)
if refusal = validateUpdateEntryPreconditions(entry, req.ExpectedExtended); refusal != nil {
return nil
}
if conditionIsSet(req.Condition) && !writeConditionSatisfied(req.Condition, entry) {
glog.V(3).InfofCtx(ctx, "UpdateEntry %s: precondition failed: %v", fullpath, req.Condition)
refusal = status.Errorf(codes.FailedPrecondition, "precondition failed: %s", fullpath)
return nil
}
if observed != nil && !clauseSatisfied(observed, entry) {
refusal = status.Errorf(codes.FailedPrecondition, "entry changed during update: %s", fullpath)
}
if transactional && observed == nil {
observed = &filer_pb.WriteCondition_Clause{
Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL,
ExpectedEntry: proto.Clone(entry.ToProtoEntry()).(*filer_pb.Entry),
}
}
return nil
}
if err := validateUpdateEntryPreconditions(entry, req.ExpectedExtended); err != nil {
// Finish the lookup (including any expiry removal) before doing volume
// I/O. Fetching or uploading manifests can outlast a FoundationDB transaction.
if _, err := fs.runEntryTransaction(ctx, lockPath, read); err != nil {
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)
if refusal != nil {
return &filer_pb.UpdateEntryResponse{}, refusal
}
chunks, garbage, err := prepareChunks(ctx, fullpath, entry, req.Entry)
if err != nil {
return &filer_pb.UpdateEntryResponse{}, fmt.Errorf("UpdateEntry cleanupChunks %s: %w", fullpath, err)
}
if err := fs.checkScopeWorm(ctx, string(lockPath)); err != nil {
return &filer_pb.UpdateEntryResponse{}, err
@@ -1016,41 +1058,94 @@ func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntr
return &filer_pb.UpdateEntryResponse{}, err
}
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)
var newEntry *filer.Entry
var stamp int64
var unchanged bool
uncertain, err := fs.runEntryTransaction(ctx, lockPath, func(ctx context.Context) error {
fs.filer.ReleaseEntryCommitTsNs(stamp)
stamp = 0
if transactional {
// A writer may have retired chunks while we prepared or retried.
// The prepared update and garbage list are valid only for this snapshot.
if err := read(ctx); err != nil || refusal != nil {
return err
}
}
newEntry = filer.FromPbEntry(req.Directory, req.Entry)
newEntry.Chunks = chunks
// Remote storage manages expiry for remote entries.
if newEntry.Remote != nil {
newEntry.TtlSec = 0
}
if unchanged = filer.EqualEntry(entry, newEntry); unchanged {
return nil
}
stamp = fs.filer.StampEntryCommitTsNs(newEntry)
return fs.filer.UpdateEntry(ctx, entry, newEntry, req.IsFromOtherCluster)
})
if err == nil {
err = refusal
}
if err != nil {
// A commit with unknown outcome may already reference these manifests.
if !uncertain || stamp == 0 {
fs.filer.DeleteChunksNotRecursive(filer.DoMinusChunks(chunks, req.Entry.GetChunks()))
}
fs.filer.ReleaseEntryCommitTsNs(stamp)
glog.V(3).InfofCtx(ctx, "UpdateEntry %s: %v", fullpath, err)
return &filer_pb.UpdateEntryResponse{}, 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
resp := &filer_pb.UpdateEntryResponse{LogTsNs: logTsNs, LogSignature: fs.filer.Signature}
if unchanged {
return resp, nil
}
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 retries known conflicts on capable stores and calls
// attempt directly elsewhere. On error, uncertain is true if writes from
// attempt may be visible, so the caller must retain chunks they could reference.
func (fs *FilerServer) runEntryTransaction(ctx context.Context, path util.FullPath, attempt func(context.Context) error) (uncertain bool, err error) {
if !fs.filer.RefusesConflictingCommits(path) {
err := attempt(ctx)
return err != nil, err
}
for n := 1; ; n++ {
txCtx, err := fs.filer.BeginTransaction(ctx)
if err != nil {
return false, err
}
if err := attempt(txCtx); err != nil {
fs.filer.RollbackTransaction(txCtx)
return false, err
}
commitErr := fs.filer.CommitTransaction(txCtx)
if commitErr == nil {
return false, nil
}
fs.filer.RollbackTransaction(txCtx)
conflict := errors.Is(commitErr, filer.ErrTransactionConflict)
if !conflict || n == entryUpdateAttempts {
return !conflict, 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 {
+12 -5
View File
@@ -294,8 +294,8 @@ type metadataEvent struct {
oldEntry *filer.Entry
newEntry *filer.Entry
deleteChunks bool
// the old entry's remote object is deleted once the rename has committed:
// it was copied to the new key, and a rename that fails must not lose it
// The old entry's remote object is deleted once the rename has committed:
// it was copied to the new key, or belonged to an overwritten target.
deleteOldRemote bool
}
@@ -468,7 +468,7 @@ func (fs *FilerServer) moveSelfEntry(ctx context.Context, stream filer_pb.Seawee
var existingTarget *filer.Entry
if !skipTargetLookup {
if targetEntry, findErr := fs.filer.FindEntry(ctx, newPath); findErr == nil {
if targetEntry, findErr := fs.filer.FindEntryForOverwrite(ctx, newPath); findErr == nil {
existingTarget = targetEntry.ShallowClone()
} else if findErr != filer_pb.ErrNotFound {
return findErr
@@ -524,6 +524,12 @@ func (fs *FilerServer) moveSelfEntry(ctx context.Context, stream filer_pb.Seawee
if existingTarget != nil && !inPlace {
targetCtx := filer.WithSuppressedMetadataEvents(ctx)
// A remote delete cannot be rolled back with the target's metadata.
// The queued target event performs it after commit unless a remote
// copy replaces that object (in which case it must be kept).
if existingTarget.Remote != nil {
targetCtx = filer.WithKeepRemoteObject(targetCtx)
}
if copiedRemote != nil || deferredCopy {
// the copy has replaced or still needs the target's object; keep it
targetCtx = filer.WithKeepRemoteObject(targetCtx)
@@ -652,8 +658,9 @@ func (fs *FilerServer) moveSelfEntry(ctx context.Context, stream filer_pb.Seawee
if existingTarget != nil {
*metadataEvents = append(*metadataEvents, metadataEvent{
oldEntry: existingTarget,
deleteChunks: true,
oldEntry: existingTarget,
deleteChunks: true,
deleteOldRemote: existingTarget.Remote != nil && copiedRemote == nil && !deferredCopy,
})
}
*metadataEvents = append(*metadataEvents, metadataEvent{
@@ -0,0 +1,101 @@
package weed_server
import (
"context"
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
)
// The expired target is logically absent but still owns data. Both rename
// RPCs must capture it before overwriting its metadata, and publish its
// deletion and release its local/remote data only after a successful commit.
func TestRenameOverExpiredS3TargetDefersCleanupUntilCommit(t *testing.T) {
for _, remote := range []bool{false, true} {
for _, stream := range []bool{false, true} {
for _, fail := range []bool{false, true} {
name := map[bool]string{false: "local", true: "remote"}[remote] + "/" +
map[bool]string{false: "atomic", true: "stream"}[stream] + "/" +
map[bool]string{false: "commit", true: "rollback"}[fail]
t.Run(name, func(t *testing.T) {
client := &renameRemoteClient{}
server, base := newRenameRemoteTestServer(t, client)
store := &txnRenameStore{renameTestStore: base}
server.filer.Store = filer.NewFilerStoreWrapper(store)
queue := &captureQueue{}
swapNotificationQueue(t, queue)
const source, target = "/buckets/b/src/f", "/buckets/b/dst/f"
store.entries[source] = fileEntryWithChunk(source, 101, updatedChunk)
expired := fileEntryWithChunk(target, 202, storedChunk)
expired.TtlSec = 1
expired.Mtime = time.Now().Add(-time.Hour)
expired.Extended = map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}
if remote {
expired.Remote = remoteOnlyRenameEntry(target, 202).Remote
}
store.entries[target] = expired
commitErr := errors.New("commit refused")
store.refuse = func(int) error {
if got := len(queue.snapshot()); got != 0 {
t.Fatalf("events before commit = %d, want none", got)
}
if got := client.recorded(); len(got) != 0 {
t.Fatalf("remote effects before commit = %v, want none", got)
}
checkDeletions(t, server.filer)
if fail {
return commitErr
}
return nil
}
var err error
if stream {
err = server.StreamRenameEntry(&filer_pb.StreamRenameEntryRequest{
OldDirectory: "/buckets/b/src", OldName: "f", NewDirectory: "/buckets/b/dst", NewName: "f",
}, &inPlaceRenameStream{})
} else {
err = renameFile(server, source, target)
}
if fail {
if err == nil {
t.Fatal("rename succeeded despite refused commit")
}
checkChunk(t, store, source, updatedChunk)
checkChunk(t, store, target, storedChunk)
checkDeletions(t, server.filer)
if len(queue.snapshot()) != 0 || len(client.recorded()) != 0 {
t.Fatal("rolled-back rename published a delete or removed a remote object")
}
return
}
if err != nil {
t.Fatal(err)
}
checkChunk(t, store, target, updatedChunk)
if _, err := store.renameTestStore.FindEntry(context.Background(), source); !errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("source after rename: %v, want NotFound", err)
}
checkDeletions(t, server.filer, storedChunk)
events := queue.snapshot()
if len(events) != 2 || events[0].key != target || events[0].notification.NewEntry != nil ||
!events[0].notification.DeleteChunks || events[1].key != source {
t.Fatalf("events = %+v, want target delete then rename", events)
}
calls := client.recorded()
if remote {
if len(calls) != 1 || calls[0] != "delete origin/dst/f" {
t.Fatalf("remote effects = %v, want expired target deleted once", calls)
}
} else if len(calls) != 0 {
t.Fatalf("remote effects = %v, want none", calls)
}
})
}
}
}
}
@@ -0,0 +1,513 @@
package weed_server
import (
"context"
"errors"
"testing"
"time"
"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/pb/remote_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"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 write 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 != 2 {
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)
}
// A deferred remote copy can fail after the metadata rename commits. The
// destination still reads the old remote key until the copy succeeds.
type retainedRemoteSource struct{ copyingRenameRemoteClient }
func (c retainedRemoteSource) StatFile(loc *remote_pb.RemoteStorageLocation) (*filer_pb.RemoteEntry, error) {
if loc.Path == "/src/f" {
c.record("stat " + loc.Path)
return remoteOnlyRenameEntry("/buckets/b/src/f", 101).Remote, nil
}
return c.copyingRenameRemoteClient.StatFile(loc)
}
func TestUpdateEntryRetryDoesNotFetchRenamedRemoteSource(t *testing.T) {
const source, target = "/buckets/b/src/f", "/buckets/b/dst/f"
client := retainedRemoteSource{copyingRenameRemoteClient{&renameRemoteClient{copyErr: errors.New("copy unavailable")}}}
server, base := newRenameRemoteTestServer(t, client)
store := &txnRenameStore{renameTestStore: base}
server.filer.Store = filer.NewFilerStoreWrapper(conflictRefusingStore{store})
// The source exists only on the remote. The first update lookup
// imports it, then the peer moves the imported entry.
store.entries[target] = remoteOnlyRenameEntry(target, 202)
peer := &FilerServer{filer: server.filer, option: server.option, entryLockTable: util.NewLockTable[util.FullPath]()}
queue := &captureQueue{}
swapNotificationQueue(t, queue)
var eventsAfterRename int
store.refuse = func(commit int) error {
if commit != 2 {
return nil
}
if err := renameFile(peer, source, target); err != nil {
t.Fatalf("concurrent rename: %v", err)
}
eventsAfterRename = len(queue.snapshot())
return writeConflict(commit)
}
req := updateOfF(updatedChunk)
req.Directory = "/buckets/b/src"
_, err := server.UpdateEntry(context.Background(), req)
if status.Code(err) != codes.NotFound {
t.Fatalf("UpdateEntry = %v, want NotFound", err)
}
if calls := client.recorded(); len(calls) != 1 || calls[0] != "stat /src/f" {
t.Fatalf("remote calls = %v, want only the initial source lookup", calls)
}
if _, err := base.FindEntry(context.Background(), source); !errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("source after retry: %v, want absent", err)
}
dst, err := base.FindEntry(context.Background(), target)
if err != nil || string(dst.Extended[filer.ExtRemoteRenameSourceKey]) != source {
t.Fatalf("destination = %+v, %v, want pending copy from %s", dst, err, source)
}
if got := len(queue.snapshot()); got != eventsAfterRename {
t.Fatalf("events = %d, want %d as after the rename", got, eventsAfterRename)
}
checkDeletions(t, server.filer)
}
// 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")
}
// An unconditional request is still based on the entry the first attempt
// read. A replacement at its path must not inherit that stale snapshot.
func TestUpdateEntryRefusesWhatWasRenamedOverTheEntry(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)); status.Code(err) != codes.FailedPrecondition {
t.Fatalf("UpdateEntry: %v, want FailedPrecondition", err)
}
if got := store.commitCount(); got != 3 {
t.Fatalf("commits = %d, want a lookup and two write attempts", got)
}
checkChunk(t, store, "/ckpt/run/f", otherChunk)
checkDeletions(t, f)
events := queue.snapshot()
if len(events) != 0 {
t.Fatalf("metadata events = %+v, want none", events)
}
}
func TestUpdateEntryRetriesAnUnchangedEntry(t *testing.T) {
server, f, store, queue := updateConflictServer(t, func(map[string]*filer.Entry) {})
if _, err := server.UpdateEntry(context.Background(), updateOfF(updatedChunk)); err != nil {
t.Fatalf("UpdateEntry: %v", err)
}
if got := store.commitCount(); got != 3 {
t.Fatalf("commits = %d, want a lookup and two write attempts", got)
}
checkChunk(t, store, "/ckpt/run/f", updatedChunk)
checkDeletions(t, f, storedChunk)
if got := len(queue.snapshot()); got != 1 {
t.Fatalf("events = %d, want the committed update only", got)
}
}
// prepare stands in for a volume upload. Its result belongs to the request
// across retries, and becomes safe to delete only after a definite failure.
func TestUpdateEntryPreparesManifestsBetweenTransactions(t *testing.T) {
const manifestID = "4,0d04"
unknown := errors.New("commit outcome unknown")
for _, tc := range []struct {
name string
changeDuringPreparation bool
commitError error
refuseAllWrites bool
wantCode codes.Code
wantStored string
wantDeletions []string
}{
{name: "reuse after conflict", commitError: filer.ErrTransactionConflict, wantStored: manifestID, wantDeletions: []string{storedChunk}},
{name: "replaced during upload", changeDuringPreparation: true, wantCode: codes.FailedPrecondition, wantStored: otherChunk, wantDeletions: []string{manifestID}},
{name: "exhausted conflicts release upload", commitError: filer.ErrTransactionConflict, refuseAllWrites: true, wantCode: codes.Unknown, wantStored: storedChunk, wantDeletions: []string{manifestID}},
{name: "unknown outcome retains upload", commitError: unknown, wantCode: codes.Unknown, wantStored: storedChunk},
} {
t.Run(tc.name, func(t *testing.T) {
server, f, store, queue := updateConflictServer(t, nil)
store.refuse = func(commit int) error {
if commit == 2 || (commit > 2 && tc.refuseAllWrites) {
return tc.commitError
}
return nil
}
calls := 0
prepare := func(ctx context.Context, path string, old *filer.Entry, _ *filer_pb.Entry) ([]*filer_pb.FileChunk, []*filer_pb.FileChunk, error) {
calls++
if txnWrites(ctx) != nil || store.commitCount() != 1 {
t.Fatal("manifest preparation must run after the lookup commits and outside the write transaction")
}
if tc.changeDuringPreparation {
store.entries[path] = fileEntryWithChunk(path, 202, otherChunk)
}
manifest := written(manifestID, 2)
manifest.IsChunkManifest = true
return []*filer_pb.FileChunk{manifest}, old.GetChunks(), nil
}
_, err := server.updateEntry(context.Background(), updateOfF(updatedChunk), "/ckpt/run/f", prepare)
if status.Code(err) != tc.wantCode || calls != 1 {
t.Fatalf("update = %v, preparations = %d, want %v and one preparation", err, calls, tc.wantCode)
}
checkChunk(t, store, "/ckpt/run/f", tc.wantStored)
checkDeletions(t, f, tc.wantDeletions...)
wantEvents := 0
if tc.wantCode == codes.OK {
wantEvents = 1
}
if got := len(queue.snapshot()); got != wantEvents {
t.Fatalf("events = %d, want %d", got, wantEvents)
}
})
}
}
func TestUpdateEntryDoesNotRestoreChunksDeletedByConcurrentWriter(t *testing.T) {
for _, rename := range []bool{false, true} {
t.Run(map[bool]string{false: "same inode updated", true: "another inode renamed over it"}[rename], func(t *testing.T) {
server, f, store, queue := updateConflictServer(t, nil)
store.entries["/ckpt/run/g"] = fileEntryWithChunk("/ckpt/run/g", 202, otherChunk)
peer := &FilerServer{filer: f, option: &FilerOption{}, entryLockTable: util.NewLockTable[util.FullPath]()}
var peerEvents int
store.refuse = func(commit int) error {
if commit != 2 {
return nil
}
var err error
if rename {
_, err = peer.AtomicRenameEntry(context.Background(), &filer_pb.AtomicRenameEntryRequest{
OldDirectory: "/ckpt/run", OldName: "g", NewDirectory: "/ckpt/run", NewName: "f",
})
} else {
_, err = peer.UpdateEntry(context.Background(), updateOfF(otherChunk))
}
if err != nil {
t.Fatalf("peer mutation: %v", err)
}
peerEvents = len(queue.snapshot())
return writeConflict(commit)
}
// Metadata changes and partial flushes keep previously published
// chunks. The peer has deleted this one before the retry begins.
_, err := server.UpdateEntry(context.Background(), updateOfF(storedChunk))
if status.Code(err) != codes.FailedPrecondition {
t.Fatalf("UpdateEntry: %v, want FailedPrecondition", err)
}
checkChunk(t, store, "/ckpt/run/f", otherChunk)
checkDeletions(t, f, storedChunk)
if got := len(queue.snapshot()); got != peerEvents {
t.Fatalf("events = %d, want only the peer's %d", got, peerEvents)
}
})
}
}
// 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 = func(commit int) error {
if commit == 1 {
return nil
}
return writeConflict(commit)
}
_, 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 != 1+entryUpdateAttempts {
t.Fatalf("commits = %d, want a lookup and %d write attempts", 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)
}
// The lookup of an expired entry removes it. NotFound is then the update's
// answer, not a failure of its transaction: the removal is committed with
// it, where a rollback would bring the expired entry back for the next
// lookup to remove, and to announce, again.
func TestUpdateEntryCommitsWhatItsLookupRemoved(t *testing.T) {
server, f, store, queue := updateConflictServer(t, func(map[string]*filer.Entry) {})
store.refuse = nil
expired := fileEntryWithChunk("/ckpt/run/f", 101, storedChunk)
expired.TtlSec = 1
expired.Crtime = time.Now().Add(-time.Hour)
store.entries["/ckpt/run/f"] = expired
_, err := server.UpdateEntry(context.Background(), updateOfF(updatedChunk))
checkGone(t, err, f, store, queue, "/ckpt/run/f")
if got := store.commitCount(); got != 1 {
t.Fatalf("commits = %d, want the one that removes the expired entry", got)
}
}
// An expired S3 object's removal tells the subscribers and deletes a remote
// copy at once, which a refused commit could not take back. The update leaves
// it to a lookup outside a transaction.
func TestUpdateEntryLeavesAnExpiredS3ObjectToALookupOutsideIt(t *testing.T) {
server, f, store, queue := updateConflictServer(t, func(map[string]*filer.Entry) {})
store.refuse = nil
expired := fileEntryWithChunk("/ckpt/run/f", 101, storedChunk)
expired.TtlSec = 1
expired.Mtime = time.Now().Add(-time.Hour)
expired.Extended = map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}
store.entries["/ckpt/run/f"] = expired
_, err := server.UpdateEntry(context.Background(), updateOfF(updatedChunk))
if status.Code(err) != codes.NotFound {
t.Fatalf("UpdateEntry: %v, want NotFound", err)
}
if events := queue.snapshot(); len(events) != 0 {
t.Fatalf("metadata events = %+v, want none", events)
}
checkChunk(t, store, "/ckpt/run/f", storedChunk)
if _, err := f.FindEntry(context.Background(), "/ckpt/run/f"); !errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("lookup outside a transaction: %v, want NotFound", err)
}
if _, err := store.renameTestStore.FindEntry(context.Background(), "/ckpt/run/f"); !errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("after the lookup: %v, want the expired object removed", err)
}
if events := queue.snapshot(); len(events) != 1 || events[0].notification.NewEntry != nil {
t.Fatalf("metadata events = %+v, want the one delete", events)
}
}
// A precondition that does not hold is an answer too: the run commits, and
// leaves the entry alone.
func TestUpdateEntryCommitsARunThatFailsItsPrecondition(t *testing.T) {
server, f, store, queue := updateConflictServer(t, func(map[string]*filer.Entry) {})
store.refuse = nil
request := updateOfF(updatedChunk)
request.ExpectedExtended = map[string][]byte{"k": []byte("v")}
_, err := server.UpdateEntry(context.Background(), request)
if status.Code(err) != codes.FailedPrecondition {
t.Fatalf("UpdateEntry: %v, want FailedPrecondition", err)
}
if got := store.commitCount(); got != 1 {
t.Fatalf("commits = %d, want 1", got)
}
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 run that fails stores nothing: it is rolled back, and what it made
// outside the store is given up, as for a run whose commit was refused.
func TestEntryTransactionRollsBackAFailedRun(t *testing.T) {
server, _, store, _ := updateConflictServer(t, func(map[string]*filer.Entry) {})
store.refuse = nil
failed := errors.New("the write failed")
runs := 0
uncertain, err := server.runEntryTransaction(context.Background(), "/ckpt/run/f", func(ctx context.Context) error {
runs++
if err := server.filer.Store.DeleteEntry(ctx, "/ckpt/run/f"); err != nil {
t.Fatalf("delete in the transaction: %v", err)
}
return failed
})
if !errors.Is(err, failed) {
t.Fatalf("runEntryTransaction: %v, want the run's error", err)
}
if runs != 1 || uncertain {
t.Fatalf("runs = %d, uncertain = %v, want one rolled-back attempt", runs, uncertain)
}
if got := store.commitCount(); got != 0 {
t.Fatalf("commits = %d, want none", got)
}
checkChunk(t, store, "/ckpt/run/f", storedChunk)
}
// 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)
}