diff --git a/weed/filer/filer.go b/weed/filer/filer.go index c5d1656f2f..c666b31fcf 100644 --- a/weed/filer/filer.go +++ b/weed/filer/filer.go @@ -624,6 +624,11 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry, unlockDirectory := func() {} oldEntry := existing + // Whether oldEntry is what the store holds at the path, so that the write + // below can take its word for the hard link the name leaves behind instead + // of reading the path a second time. An entry a caller fetched is not that: + // this cannot tell how its lookup read. + oldFromStore := false if oldEntry == nil { var findErr error // A lazy fetch here would persist outside the transaction and wait on @@ -633,7 +638,7 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry, if ctx.Value(storeTransactionKey{}) != nil && !o_excl { findCtx = context.WithValue(ctx, lazyFetchContextKey{}, true) } - oldEntry, findErr = f.FindEntry(findCtx, entry.FullPath) + oldEntry, oldFromStore, findErr = f.findEntry(findCtx, entry.FullPath) if findErr != nil && !errors.Is(findErr, filer_pb.ErrNotFound) { // A create cannot decide whether the path exists when the lookup // itself failed; proceeding would upsert over it. @@ -642,7 +647,7 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry, if oldEntry == nil && entry.IsDirectory() { unlockDirectory = f.lockDirectoryCreate(ctx, entry.FullPath) defer unlockDirectory() - if oldEntry, findErr = f.FindEntry(context.WithValue(ctx, lazyFetchContextKey{}, true), entry.FullPath); findErr != nil && !errors.Is(findErr, filer_pb.ErrNotFound) { + if oldEntry, oldFromStore, findErr = f.findEntry(context.WithValue(ctx, lazyFetchContextKey{}, true), entry.FullPath); findErr != nil && !errors.Is(findErr, filer_pb.ErrNotFound) { return fmt.Errorf("find entry %s: %w", entry.FullPath, findErr) } } @@ -672,7 +677,16 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry, stamped = true glog.V(4).InfofCtx(ctx, "InsertEntry %s: new entry: %v", entry.FullPath, entry.Name()) - if err := f.Store.InsertEntry(ctx, entry); err != nil { + // A lookup that read the store and found the path empty answers what the + // write otherwise reads it for: the hard link the name leaves behind. An + // entry that carries a link keeps the write's own read, which runs inside + // the change of its record: another filer storing the same name between + // this lookup and the write would otherwise have it counted twice. + insert := f.Store.InsertEntry + if oldFromStore && len(entry.HardLinkId) == 0 { + insert = f.Store.InsertEntryKnownAbsent + } + if err := insert(ctx, entry); err != nil { glog.ErrorfCtx(ctx, "insert entry %s: %v", entry.FullPath, err) return fmt.Errorf("insert entry %s: %v", entry.FullPath, err) } @@ -725,7 +739,7 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry, glog.V(4).InfofCtx(ctx, "UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name()) f.stampEntryCommitTsNs(entry) stamped = true - if err := f.UpdateEntry(ctx, oldEntry, entry, isFromOtherCluster); err != nil { + if err := f.updateEntry(ctx, oldEntry, entry, isFromOtherCluster, oldFromStore); err != nil { if errors.Is(err, filer_pb.ErrExistingIsDirectory) || errors.Is(err, filer_pb.ErrExistingIsFile) { glog.V(2).InfofCtx(ctx, "update entry %s: %v", entry.FullPath, err) } else { @@ -769,7 +783,7 @@ func (f *Filer) ReplaceFileForRename(ctx context.Context, entry *Entry, maxFilen if entry.FullPath.HasDotSegment() { return fmt.Errorf("invalid path %s", entry.FullPath) } - current, findErr := f.FindEntry(context.WithValue(ctx, lazyFetchContextKey{}, true), entry.FullPath) + current, currentFromStore, findErr := f.findEntry(context.WithValue(ctx, lazyFetchContextKey{}, true), entry.FullPath) if findErr != nil && !errors.Is(findErr, filer_pb.ErrNotFound) { return fmt.Errorf("find entry %s: %w", entry.FullPath, findErr) } @@ -780,7 +794,19 @@ func (f *Filer) ReplaceFileForRename(ctx context.Context, entry *Entry, maxFilen entry.Attr.Atime = entryInitialAtime(entry.Attr) } f.ensureEntryInode(entry) - if err := f.Store.InsertEntry(ctx, entry); err != nil { + // What this lookup found is what the write otherwise reads the path for + // again: the hard link the replaced name had. An entry that carries a link + // keeps the write's own read, as in CreateEntry. + insert := f.Store.InsertEntry + switch { + case current == nil && currentFromStore && len(entry.HardLinkId) == 0: + insert = f.Store.InsertEntryKnownAbsent + case current != nil: + insert = func(ctx context.Context, e *Entry) error { + return f.Store.InsertEntryReplaces(ctx, e, current) + } + } + if err := insert(ctx, entry); err != nil { glog.ErrorfCtx(ctx, "replace entry %s: %v", entry.FullPath, err) return fmt.Errorf("replace entry %s: %w", entry.FullPath, err) } @@ -1002,7 +1028,16 @@ func (f *Filer) EnsureDirectoryEntry(ctx context.Context, dirPath util.FullPath, return nil } +// UpdateEntry replaces the entry a caller read as oldEntry at entry's path. func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry, isFromOtherCluster bool) (err error) { + return f.updateEntry(ctx, oldEntry, entry, isFromOtherCluster, false) +} + +// updateEntry writes entry over oldEntry, which is what the store holds at its +// path when oldFromStore: the write can then take the hard link it replaces +// from oldEntry instead of reading the path again. See CreateEntry for the +// lookup that sets it. +func (f *Filer) updateEntry(ctx context.Context, oldEntry, entry *Entry, isFromOtherCluster bool, oldFromStore bool) (err error) { if entry.FullPath.HasDotSegment() { return fmt.Errorf("invalid path %s", entry.FullPath) } @@ -1041,6 +1076,9 @@ func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry, isFromO if entry.Attr.Atime.IsZero() { entry.Attr.Atime = entryInitialAtime(entry.Attr) } + if oldFromStore { + return f.Store.UpdateEntryReplaces(ctx, entry, oldEntry) + } return f.Store.UpdateEntry(ctx, entry) } @@ -1064,12 +1102,25 @@ var ( } ) +// FindEntry looks up the entry at p, serving a path the store does not hold +// from a remote mount when one covers it. func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) { + entry, _, err = f.findEntry(ctx, p) + return +} + +// findEntry also reports whether the entry it returns is what the store holds +// at p. A write needs that to know it may skip reading the path itself: an +// entry fetched from remote describes an object the store does not hold, and a +// lookup inside a transaction lets an expired entry live until the commit, so +// neither answer says what is stored there. +func (f *Filer) findEntry(ctx context.Context, p util.FullPath) (entry *Entry, fromStore bool, err error) { if string(p) == "/" { - return Root, nil + return Root, false, nil } entry, err = f.Store.FindEntry(ctx, p) + fromStore = true // A directory is deleted here one row at a time, which would strand whatever is // under it, so a TTL an older build left on one is not acted on. if entry != nil && entry.TtlSec > 0 && !entry.IsDirectory() { @@ -1077,16 +1128,21 @@ func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, e if entry.GetS3ExpireTime().Before(time.Now()) && !entry.IsS3Versioning() { // Its remote delete and event would outlive a refused commit, so a // lookup outside a transaction removes it. + gone := false 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) + } else { + gone = true } } - return nil, filer_pb.ErrNotFound + // The row still stands where the transaction keeps it or the delete + // failed, and a write replacing it owes that entry its hard link. + return nil, gone, filer_pb.ErrNotFound } } else if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) { - f.Store.DeleteOneEntry(ctx, entry) - return nil, filer_pb.ErrNotFound + gone := f.Store.DeleteOneEntry(ctx, entry) == nil + return nil, gone, filer_pb.ErrNotFound } } @@ -1094,11 +1150,11 @@ func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, e if lazy, lazyErr := f.maybeLazyFetchFromRemote(ctx, p); lazyErr != nil { glog.V(1).InfofCtx(ctx, "FindEntry lazy fetch %s: %v", p, lazyErr) } else if lazy != nil { - return lazy, nil + return lazy, false, nil } } - return entry, err + return entry, fromStore, err } // FindEntryWithoutRemoteFetch applies the usual expiry checks but leaves a diff --git a/weed/filer/filer_lazy_remote_test.go b/weed/filer/filer_lazy_remote_test.go index 1a7137096c..d5a6328439 100644 --- a/weed/filer/filer_lazy_remote_test.go +++ b/weed/filer/filer_lazy_remote_test.go @@ -44,6 +44,21 @@ type stubFilerStore struct { deleteErrByPath map[string]error updateErr error deleteFolderErr error + finds int // FindEntry calls, for tests counting what a write reads +} + +// findCount is how many times the store was read, since the last reset. +func (s *stubFilerStore) findCount() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.finds +} + +// resetFindCount starts the count of reads over. +func (s *stubFilerStore) resetFindCount() { + s.mu.Lock() + defer s.mu.Unlock() + s.finds = 0 } func newStubFilerStore() *stubFilerStore { @@ -207,6 +222,7 @@ func (s *stubFilerStore) UpdateEntry(_ context.Context, entry *Entry) error { func (s *stubFilerStore) FindEntry(_ context.Context, p util.FullPath) (*Entry, error) { s.mu.Lock() defer s.mu.Unlock() + s.finds++ if s.findErr != nil { return nil, s.findErr } diff --git a/weed/filer/filer_write_reads_test.go b/weed/filer/filer_write_reads_test.go new file mode 100644 index 0000000000..1d9ee7b66d --- /dev/null +++ b/weed/filer/filer_write_reads_test.go @@ -0,0 +1,181 @@ +package filer + +import ( + "context" + "os" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" + "github.com/stretchr/testify/require" +) + +// What one write reads the store for. A create looked the path up to +// decide what it makes of it; the store wrapper used to look it up again to +// learn the hard link the name left behind. The write now takes that from the +// lookup it already has, so a plain file write reads the path once. + +func fileAt(p string) *Entry { + return &Entry{ + FullPath: util.FullPath(p), + Attr: Attr{Mode: 0o644, Mtime: time.Unix(1700000000, 0), Crtime: time.Unix(1700000000, 0)}, + Chunks: []*filer_pb.FileChunk{{FileId: "5,0c050a"}}, + } +} + +// writeCountingFiler is a filer over its own store, the way Filer.SetStore +// builds one: the wrapper counts the names of a hard-linked file. +func writeCountingFiler(t *testing.T) (*Filer, *stubFilerStore) { + t.Helper() + store := newStubFilerStore() + f := newTestFiler(t, store, NewFilerRemoteStorage()) + f.Store.(*FilerStoreWrapper).countsLinks = true + return f, store +} + +func TestCreateNewFileReadsThePathOnce(t *testing.T) { + f, store := writeCountingFiler(t) + ctx := context.Background() + + require.NoError(t, f.CreateEntry(ctx, fileAt("/d/new"), nil, false, false, nil, true, 255)) + + require.Equal(t, 1, store.findCount(), "a create that found the path empty must not read it again in the write") +} + +func TestOverwriteFileReadsThePathOnce(t *testing.T) { + f, store := writeCountingFiler(t) + ctx := context.Background() + require.NoError(t, f.CreateEntry(ctx, fileAt("/d/f"), nil, false, false, nil, true, 255)) + + store.resetFindCount() + replacement := fileAt("/d/f") + replacement.Chunks = []*filer_pb.FileChunk{{FileId: "6,0c060a"}} + require.NoError(t, f.CreateEntry(ctx, replacement, nil, false, false, nil, true, 255)) + + require.Equal(t, 1, store.findCount(), "replacing a plain file reads the path once") + + stored, err := f.Store.FindEntry(ctx, util.FullPath("/d/f")) + require.NoError(t, err) + require.Equal(t, "6,0c060a", stored.GetChunks()[0].FileId, "the lookup still decides what the write stores") +} + +// The read the wrapper keeps for this case is the one that decides what the +// replaced name carried. A write that has a link to drop will not take a +// caller's word for it, so it reads the path — and the link still goes. +func TestReplacingALinkedNameReadsAndDropsTheLink(t *testing.T) { + f, store := writeCountingFiler(t) + ctx := context.Background() + wrapper := f.Store.(*FilerStoreWrapper) + + id := linkedFile(t, store, "/d/x", "/d/y") + checkNames(t, wrapper, 2, "/d/x", "/d/y") + + store.resetFindCount() + require.NoError(t, f.CreateEntry(ctx, fileAt("/d/x"), nil, false, false, nil, true, 255)) + + require.Equal(t, 2, store.findCount(), "dropping a link is decided from the store, not from a row read earlier") + + // one name is gone, so the file counts one name left + shared := &Entry{} + value, err := store.KvGet(ctx, id) + require.NoError(t, err) + require.NoError(t, shared.DecodeAttributesAndChunks(value)) + require.Equal(t, int32(1), shared.HardLinkCounter, "the dropped name's link was not taken off") + + // The write brought no link of its own, so it counted no names: the count + // in the record is what the file's remaining name reads. + require.Equal(t, int32(-1), namesCounted(t, store, id)) + + // the other name still reads the file, and its chunks are still there + checkNames(t, wrapper, 1, "/d/y") + stored, err := wrapper.FindEntry(ctx, util.FullPath("/d/y")) + require.NoError(t, err) + require.Len(t, stored.GetChunks(), 1) +} + +// Two filers overwrite one name of a linked file. The first takes the link off; +// the second must not take it off again from a row it read before the first +// wrote: a second drop deletes the record, and the file's other name loses its +// chunks. This is the reason a write with a link at stake reads the path itself. +func TestStaleLinkedRowIsNotTrusted(t *testing.T) { + store := newStubFilerStore() + wrapper := countingWrapper(store) + ctx := context.Background() + + id := linkedFile(t, store, "/d/x", "/d/y") + + // what this filer read, before the other one got there + stale := store.entries["/d/x"].ShallowClone() + require.NotEmpty(t, stale.HardLinkId) + + // the other filer's write replaces the name with a plain file + require.NoError(t, wrapper.UpdateEntry(ctx, fileAt("/d/x"))) + after := &Entry{} + value, err := store.KvGet(ctx, id) + require.NoError(t, err) + require.NoError(t, after.DecodeAttributesAndChunks(value)) + require.Equal(t, int32(1), after.HardLinkCounter) + + // this filer's write, a moment later, with a row that is no longer there + require.NoError(t, wrapper.UpdateEntryReplaces(ctx, fileAt("/d/x"), stale)) + + value, err = store.KvGet(ctx, id) + require.NoError(t, err, "the record is gone: the link was dropped twice") + twice := &Entry{} + require.NoError(t, twice.DecodeAttributesAndChunks(value)) + require.Equal(t, int32(1), twice.HardLinkCounter, "the link was dropped twice") + + // /d/y still reads the file + checkNames(t, wrapper, 1, "/d/y") +} + +// A file with a hard link is still read by the write: its record may change +// under a change the store refused and sent again, so each run judges the name +// as the store holds it then. This pins the exception, so it is a choice and +// not an oversight. +func TestWritingALinkedFileStillReadsThePath(t *testing.T) { + f, store := writeCountingFiler(t) + ctx := context.Background() + + source := fileAt("/d/a") + source.HardLinkId = NewHardLinkId() + source.HardLinkCounter = 1 + require.NoError(t, f.CreateEntry(ctx, source, nil, false, false, nil, true, 255)) + + store.resetFindCount() + again := source.ShallowClone() + again.Attr.Mtime = time.Unix(1700000002, 0) + require.NoError(t, f.CreateEntry(ctx, again, nil, false, false, nil, true, 255)) + + require.Equal(t, 2, store.findCount(), "a linked name is judged from the store, not from the caller's read") +} + +// A directory is read twice by a create: once before taking the lock that +// keeps two mkdirs of one name apart, once again under it. The write itself +// adds no third read — a directory has no link of its own to leave behind. +func TestCreateDirectoryReadsThePathTwiceAtMost(t *testing.T) { + f, store := writeCountingFiler(t) + ctx := context.Background() + + dir := &Entry{FullPath: util.FullPath("/d2"), Attr: Attr{Mode: os.ModeDir | 0755}} + require.NoError(t, f.CreateEntry(ctx, dir, nil, false, false, nil, true, 255)) + + require.Equal(t, 2, store.findCount(), "the create's recheck under its lock, and nothing from the write") +} + +// An insert whose lookup found the path empty takes the write's shortcut only +// for an entry with no link of its own: a linked entry has its name counted +// inside the change of its record, which has to see whether another filer +// stored that name meanwhile, or the count runs one above the names. +func TestNewLinkedNameStillReadsThePath(t *testing.T) { + f, store := writeCountingFiler(t) + ctx := context.Background() + + entry := fileAt("/d/linked") + entry.HardLinkId = NewHardLinkId() + entry.HardLinkCounter = 1 + require.NoError(t, f.CreateEntry(ctx, entry, nil, false, false, nil, true, 255)) + + require.Equal(t, 2, store.findCount(), "a linked name is counted from the store, not from the create's lookup") +} diff --git a/weed/filer/filerstore_hardlink.go b/weed/filer/filerstore_hardlink.go index 04f60ca40a..3da4fbec3e 100644 --- a/weed/filer/filerstore_hardlink.go +++ b/weed/filer/filerstore_hardlink.go @@ -16,23 +16,51 @@ import ( // about to store, and returns the hard link of the name at entry's path when // the write replaces that name with another file. The caller drops that link // once the write has gone through (dropLink), not before. The name is looked -// up with findCtx. names is for the caller to record before it stores entry +// up with findCtx, unless existingKnown says a caller already read it and hands +// it down as existing. names is for the caller to record before it stores entry // (recordLinkNames). -func (fsw *FilerStoreWrapper) handleUpdateToHardLinks(ctx, findCtx context.Context, entry *Entry) (replaced HardLinkId, names *linkNames, err error) { +// +// The caller's read is trusted only where the write has nothing to work out +// from it: an entry with no hard link replacing a row with no hard link drops +// no link and joins no record. A link another filer stores at the name after +// the caller's read stays counted, as it did when the path was read just before +// a write it is not atomic with. Where a link is at stake the path is read +// again, and for two reasons: +// +// - entry has a hard link: changeLinkRecord may run its change again after +// the store refused a commit, and each run must judge the name as the store +// holds it by then; +// - the row read by the caller has one: it is about to be dropped, and a +// caller's read reaches further back than the write. Another filer that +// replaced the same name in between already dropped that link, and dropping +// it twice deletes the record under the file's remaining names. +func (fsw *FilerStoreWrapper) handleUpdateToHardLinks(ctx, findCtx context.Context, entry *Entry, existing *Entry, existingKnown bool) (replaced HardLinkId, names *linkNames, err error) { if entry.IsDirectory() { return nil, nil, nil } - // check what is existing entry - // glog.V(4).Infof("handleUpdateToHardLinks FindEntry %s", entry.FullPath) - actualStore := fsw.getActualStore(entry.FullPath) - existingEntry, err := actualStore.FindEntry(findCtx, entry.FullPath) - if err != nil && err != filer_pb.ErrNotFound { - return nil, nil, fmt.Errorf("update existing entry %s: %v", entry.FullPath, err) + var existingEntry *Entry + var found bool + if existingKnown && len(entry.HardLinkId) == 0 && + (existing == nil || len(existing.HardLinkId) == 0) { + existingEntry, found = existing, existing != nil + } else { + // check what is existing entry + // glog.V(4).Infof("handleUpdateToHardLinks FindEntry %s", entry.FullPath) + actualStore := fsw.getActualStore(entry.FullPath) + var findErr error + if existingEntry, findErr = actualStore.FindEntry(findCtx, entry.FullPath); findErr != nil { + if findErr != filer_pb.ErrNotFound { + return nil, nil, fmt.Errorf("update existing entry %s: %v", entry.FullPath, findErr) + } + existingEntry = nil + } else { + found = existingEntry != nil + } } // the name at entry's path is one of the file's names already - held := err == nil && bytes.Equal(existingEntry.HardLinkId, entry.HardLinkId) + held := found && bytes.Equal(existingEntry.HardLinkId, entry.HardLinkId) if len(entry.HardLinkId) > 0 { // handle hard links @@ -45,7 +73,7 @@ func (fsw *FilerStoreWrapper) handleUpdateToHardLinks(ctx, findCtx context.Conte } // the old hard link, dropped after the write - if err == nil && len(existingEntry.HardLinkId) != 0 && !held { + if found && len(existingEntry.HardLinkId) != 0 && !held { return existingEntry.HardLinkId, names, nil } return nil, names, nil @@ -58,8 +86,9 @@ func (fsw *FilerStoreWrapper) handleUpdateToHardLinks(ctx, findCtx context.Conte // A filer's own store looks the name up, counts it, saves the record, records // the name and stores it as one change of the record (changeLinkRecord): // another filer that deletes the name in between would otherwise leave it -// stored and not counted. -func (fsw *FilerStoreWrapper) writeWithHardLink(ctx context.Context, entry *Entry, write func(context.Context, *Entry) error) (replaced HardLinkId, err error) { +// stored and not counted. A caller that has read the path itself hands the +// entry it found down, and the write keeps to that one read. +func (fsw *FilerStoreWrapper) writeWithHardLink(ctx context.Context, entry *Entry, existing *Entry, existingKnown bool, write func(context.Context, *Entry) error) (replaced HardLinkId, err error) { // A name in a path-specific store is outside the record's transaction: a // change run again would find the name its first run stored and count it // as one the file already had. It is stored once the count is settled. @@ -83,7 +112,7 @@ func (fsw *FilerStoreWrapper) writeWithHardLink(ctx context.Context, entry *Entr findCtx = ctx } var err error - if replaced, names, err = fsw.handleUpdateToHardLinks(txCtx, findCtx, entry); err != nil { + if replaced, names, err = fsw.handleUpdateToHardLinks(txCtx, findCtx, entry, existing, existingKnown); err != nil { return err } if err = fsw.recordLinkNames(txCtx, names); err != nil || !together { diff --git a/weed/filer/filerstore_wrapper.go b/weed/filer/filerstore_wrapper.go index a3d609c0e4..0f3a4f2498 100644 --- a/weed/filer/filerstore_wrapper.go +++ b/weed/filer/filerstore_wrapper.go @@ -29,6 +29,8 @@ type VirtualFilerStore interface { DeleteHardLink(ctx context.Context, hardLinkId HardLinkId) error DeleteOneEntry(ctx context.Context, entry *Entry) error InsertEntryKnownAbsent(ctx context.Context, entry *Entry) error + InsertEntryReplaces(ctx context.Context, entry *Entry, existing *Entry) error + UpdateEntryReplaces(ctx context.Context, entry *Entry, existing *Entry) error AddPathSpecificStore(path string, storeId string, store FilerStore) OnBucketCreation(bucket string) OnBucketDeletion(bucket string) @@ -150,6 +152,19 @@ func (fsw *FilerStoreWrapper) Initialize(configuration util.Configuration, prefi } func (fsw *FilerStoreWrapper) InsertEntry(ctx context.Context, entry *Entry) error { + return fsw.insertEntry(ctx, entry, nil, false) +} + +// InsertEntryReplaces stores entry at a path the caller has read and found +// holding existing. The write works out from that read what hard link the name +// leaves behind, instead of reading the path a second time to learn it. Where +// existing is nil the caller did not read the path, so this reads it like +// InsertEntry; a caller that found it empty says so with InsertEntryKnownAbsent. +func (fsw *FilerStoreWrapper) InsertEntryReplaces(ctx context.Context, entry *Entry, existing *Entry) error { + return fsw.insertEntry(ctx, entry, existing, existing != nil) +} + +func (fsw *FilerStoreWrapper) insertEntry(ctx context.Context, entry *Entry, existing *Entry, existingKnown bool) error { if err := ctx.Err(); err != nil { return err } @@ -170,7 +185,7 @@ func (fsw *FilerStoreWrapper) InsertEntry(ctx context.Context, entry *Entry) err entry.FullPath, entry.HardLinkId, entry.HardLinkCounter) } - replacedLink, err := fsw.writeWithHardLink(ctx, entry, actualStore.InsertEntry) + replacedLink, err := fsw.writeWithHardLink(ctx, entry, existing, existingKnown, actualStore.InsertEntry) if err != nil { return err } @@ -179,7 +194,10 @@ func (fsw *FilerStoreWrapper) InsertEntry(ctx context.Context, entry *Entry) err } // InsertEntryKnownAbsent skips the pre-insert FindEntry path when the caller has -// already established that the target path does not exist. +// already established that the target path does not exist. It skips it for an +// entry with a hard link too, where InsertEntryReplaces reads the path again: a +// name the store does not hold joins its file's names, and no name there leaves +// a link to drop. func (fsw *FilerStoreWrapper) InsertEntryKnownAbsent(ctx context.Context, entry *Entry) error { if err := ctx.Err(); err != nil { return err @@ -223,6 +241,18 @@ func (fsw *FilerStoreWrapper) InsertEntryKnownAbsent(ctx context.Context, entry } func (fsw *FilerStoreWrapper) UpdateEntry(ctx context.Context, entry *Entry) error { + return fsw.updateEntry(ctx, entry, nil, false) +} + +// UpdateEntryReplaces updates entry at a path the caller has read and found +// holding existing, saving the read that would otherwise learn from the store +// what hard link the name had before. As in InsertEntryReplaces, a nil existing +// leaves the write to read the path itself. +func (fsw *FilerStoreWrapper) UpdateEntryReplaces(ctx context.Context, entry *Entry, existing *Entry) error { + return fsw.updateEntry(ctx, entry, existing, existing != nil) +} + +func (fsw *FilerStoreWrapper) updateEntry(ctx context.Context, entry *Entry, existing *Entry, existingKnown bool) error { if err := ctx.Err(); err != nil { return err } @@ -243,7 +273,7 @@ func (fsw *FilerStoreWrapper) UpdateEntry(ctx context.Context, entry *Entry) err entry.FullPath, entry.HardLinkId, entry.HardLinkCounter) } - replacedLink, err := fsw.writeWithHardLink(ctx, entry, actualStore.UpdateEntry) + replacedLink, err := fsw.writeWithHardLink(ctx, entry, existing, existingKnown, actualStore.UpdateEntry) if err != nil { return err } diff --git a/weed/filer/leveldb2/leveldb2_store_test.go b/weed/filer/leveldb2/leveldb2_store_test.go index 7e8854ca43..2b316a3327 100644 --- a/weed/filer/leveldb2/leveldb2_store_test.go +++ b/weed/filer/leveldb2/leveldb2_store_test.go @@ -2,12 +2,15 @@ package leveldb import ( "context" + "fmt" "math" "strings" "testing" + "time" "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/util" ) @@ -224,3 +227,89 @@ func TestUnavailableDatabaseFailsListAndDelete(t *testing.T) { t.Fatal("delete children on a closed database succeeded") } } + +// benchChunks is a file's chunk list, long enough that decoding the row a write +// replaces is real work — which is what reading that path twice pays twice. +func benchChunks(n int) []*filer_pb.FileChunk { + chunks := make([]*filer_pb.FileChunk, 0, n) + for i := 0; i < n; i++ { + chunks = append(chunks, &filer_pb.FileChunk{ + FileId: fmt.Sprintf("3,%08d", i), + Offset: int64(i) * 4096, + Size: 4096, + ModifiedTsNs: 1700000000000000000 + int64(i), + }) + } + return chunks +} + +func benchLeveldb2Filer(b *testing.B) *filer.Filer { + b.Helper() + store := &LevelDB2Store{} + if err := store.initialize(b.TempDir(), 2); err != nil { + b.Fatalf("open store: %v", err) + } + // Filer.Shutdown would also stop the workers NewFiler starts, and is the + // right cleanup for a test. Here it waits out shutdownMetadataLogFlushBudget + // for the metadata-log windows these writes queue (measured at ~30s per + // invocation, two benchmarks per run), which a benchmark cannot pay. The + // store is closed either way, and the workers live only as long as the + // benchmark process. + b.Cleanup(store.Shutdown) + testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil) + testFiler.SetStore(store) + return testFiler +} + +// BenchmarkCreateEntryOverwrite measures a create replacing a file: the path is +// read to decide what the write replaces, and was read again by the store +// wrapper to learn the hard link the name left behind. +func BenchmarkCreateEntryOverwrite(b *testing.B) { + testFiler := benchLeveldb2Filer(b) + ctx := context.Background() + path := util.FullPath("/d/f") + chunks := benchChunks(20) + + seed := &filer.Entry{ + FullPath: path, + Attr: filer.Attr{Mode: 0o644, Mtime: time.Unix(1700000000, 0), Crtime: time.Unix(1700000000, 0)}, + Chunks: chunks, + } + if err := testFiler.CreateEntry(ctx, seed, nil, false, false, nil, true, 255); err != nil { + b.Fatalf("seed: %v", err) + } + + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + entry := &filer.Entry{ + FullPath: path, + Attr: filer.Attr{Mode: 0o644, Mtime: time.Unix(1700000001, 0), Crtime: time.Unix(1700000000, 0)}, + Chunks: chunks, + } + if err := testFiler.CreateEntry(ctx, entry, nil, false, false, nil, true, 255); err != nil { + b.Fatalf("create: %v", err) + } + } +} + +// BenchmarkCreateEntryNewFile is the other branch of a create: the lookup found +// the path empty, and the write takes that for its answer as well. +func BenchmarkCreateEntryNewFile(b *testing.B) { + testFiler := benchLeveldb2Filer(b) + ctx := context.Background() + chunks := benchChunks(20) + + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + entry := &filer.Entry{ + FullPath: util.FullPath(fmt.Sprintf("/d/f%d", i)), + Attr: filer.Attr{Mode: 0o644, Mtime: time.Unix(1700000001, 0), Crtime: time.Unix(1700000000, 0)}, + Chunks: chunks, + } + if err := testFiler.CreateEntry(ctx, entry, nil, false, false, nil, true, 255); err != nil { + b.Fatalf("create: %v", err) + } + } +} diff --git a/weed/server/filer_grpc_server_condition_test.go b/weed/server/filer_grpc_server_condition_test.go index 5b775f73cd..f06143d333 100644 --- a/weed/server/filer_grpc_server_condition_test.go +++ b/weed/server/filer_grpc_server_condition_test.go @@ -348,9 +348,12 @@ func TestCreateEntryConditionEnforced(t *testing.T) { } } -// CreateEntry reuses a provided existing entry instead of reading the store -// again; passing nil makes it look the path up itself. -func TestCreateEntryReusesProvidedExisting(t *testing.T) { +// One create reads the path once, whether the caller brought the entry it +// fetched or CreateEntry looked it up itself: existing saves the create's +// lookup, and the write no longer reads the path a second time for the +// hard link the name leaves behind. Either read coming back makes its +// run count two. +func TestCreateEntryReadsThePathOnce(t *testing.T) { existing := &filer.Entry{ FullPath: "/test/obj", Attr: filer.Attr{Inode: 1, Mtime: time.Unix(1700000000, 0), Crtime: time.Unix(1700000000, 0)}, @@ -363,9 +366,6 @@ func TestCreateEntryReusesProvidedExisting(t *testing.T) { } } - // Provided existing vs nil: the only difference is CreateEntry's own lookup, - // so providing it must save exactly one path read (other store-layer reads - // during the overwrite are the same in both runs). store := newRenameTestStore() store.entries["/test/obj"] = existing.ShallowClone() f := newRenameTestFiler(t, store) @@ -382,8 +382,25 @@ func TestCreateEntryReusesProvidedExisting(t *testing.T) { } withNil := store2.findEntryCallCount("/test/obj") - if withNil != withExisting+1 { - t.Fatalf("providing existing should save one path lookup: existing=%d nil=%d", withExisting, withNil) + if withExisting != 1 || withNil != 1 { + t.Fatalf("one create should read the path once: existing=%d nil=%d", withExisting, withNil) + } + + // And the create has to use what it was given, not just count one read: over + // an empty store only the update branch carries crtime from the entry passed + // in, so a create that ignored it would look the path up, find nothing, and + // insert a row with no crtime. + store3 := newRenameTestStore() + f3 := newRenameTestFiler(t, store3) + if err := f3.CreateEntry(context.Background(), newEntry(), existing, false, false, nil, true, f3.MaxFilenameLength); err != nil { + t.Fatalf("create over an empty store: %v", err) + } + got, err := store3.FindEntry(context.Background(), "/test/obj") + if err != nil { + t.Fatalf("read back: %v", err) + } + if !got.Attr.Crtime.Equal(existing.Attr.Crtime) { + t.Fatalf("the create did not use the entry it was given: crtime %v, want %v", got.Attr.Crtime, existing.Attr.Crtime) } } diff --git a/weed/server/filer_server_handlers_write_autochunk.go b/weed/server/filer_server_handlers_write_autochunk.go index 43c934134b..cd3c7211c4 100644 --- a/weed/server/filer_server_handlers_write_autochunk.go +++ b/weed/server/filer_server_handlers_write_autochunk.go @@ -508,6 +508,9 @@ func (fs *FilerServer) saveMetaData(ctx context.Context, r *http.Request, fileNa } } + // The recheck below reads the path; handing it to the create saves that a + // third lookup of the same entry follows. + var existingForWrite *filer.Entry if isAppend || isOffsetWrite { if distributedLock != nil && !distributedLock.IsLocked() { replyerr = fmt.Errorf("lost distributed lock for %s; retry the request", path) @@ -525,6 +528,7 @@ func (fs *FilerServer) saveMetaData(ctx context.Context, r *http.Request, fileNa replyerr = fmt.Errorf("entry %s changed during append; retry the request", path) return } + existingForWrite = freshEntry } else if fs.entryLockTable != nil { // CreateEntry deletes the chunks of the entry it replaces, so concurrent // overwrites must not both replace the same entry. @@ -554,7 +558,7 @@ func (fs *FilerServer) saveMetaData(ctx context.Context, r *http.Request, fileNa }) } if !routed { - dbErr = fs.filer.CreateEntry(context.WithoutCancel(ctx), entry, nil, false, false, nil, skipCheckParentDirEntry(r), so.MaxFileNameLength) + dbErr = fs.filer.CreateEntry(context.WithoutCancel(ctx), entry, existingForWrite, false, false, nil, skipCheckParentDirEntry(r), so.MaxFileNameLength) } if dbErr != nil { replyerr = dbErr