diff --git a/weed/filer/filer.go b/weed/filer/filer.go index 2b5d86e5e2..251f0dfa95 100644 --- a/weed/filer/filer.go +++ b/weed/filer/filer.go @@ -472,7 +472,10 @@ func (f *Filer) ListExistingPeerUpdates(ctx context.Context) (existingNodes []*m } func (f *Filer) SetStore(store FilerStore) (isFresh bool) { - f.Store = NewFilerStoreWrapper(store) + wrapper := NewFilerStoreWrapper(store) + // this store holds every name of a hard-linked file: it counts them + wrapper.countsLinks = true + f.Store = wrapper isFresh = f.setOrLoadFilerStoreSignature(store) diff --git a/weed/filer/filer_hardlink_count_test.go b/weed/filer/filer_hardlink_count_test.go new file mode 100644 index 0000000000..e42fecf24e --- /dev/null +++ b/weed/filer/filer_hardlink_count_test.go @@ -0,0 +1,862 @@ +package filer + +import ( + "bytes" + "context" + "errors" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" + "github.com/stretchr/testify/require" +) + +// A filer's own store counts the names of a hard-linked file itself and lets +// no write leave the file's link count below them (linkNames). These tests +// send it what clients send, counts worked out from an entry another client +// has changed since, and check the record against the names. + +// countingWrapper is the wrapper Filer.SetStore puts around a filer's store. +func countingWrapper(store FilerStore) *FilerStoreWrapper { + wrapper := NewFilerStoreWrapper(store) + wrapper.countsLinks = true + return wrapper +} + +// linkName is the row a client sends for name: the file linkedFile made, with +// the count the client believes in. +func linkName(id HardLinkId, name util.FullPath, count int32) *Entry { + return &Entry{ + FullPath: name, + Attr: Attr{Mode: 0o644}, + HardLinkId: id, + HardLinkCounter: count, + Chunks: []*filer_pb.FileChunk{{FileId: linkedChunk, Size: 4}}, + } +} + +// namesCounted is the number of names the store has counted for id, -1 when +// it has counted none. +func namesCounted(t *testing.T, store *stubFilerStore, id HardLinkId) int32 { + t.Helper() + value, err := store.KvGet(context.Background(), linkNamesKey(id)) + if errors.Is(err, ErrKvNotFound) { + return -1 + } + require.NoError(t, err) + return int32(util.BytesToUint32(value)) +} + +func checkNames(t *testing.T, wrapper *FilerStoreWrapper, want int32, names ...util.FullPath) { + t.Helper() + for _, name := range names { + e, err := wrapper.FindEntry(context.Background(), name) + require.NoError(t, err, "%s", name) + require.Equal(t, want, e.HardLinkCounter, "%s", name) + require.Len(t, e.GetChunks(), 1, "%s", name) + } +} + +// Two mounts each add a name to a file with two. Each read the count as 2 and +// sends 3, with its update of the name it linked from and with the new name. +// Four names are counted, in whatever order the four writes arrive. Counted +// as 3, deleting three of them deleted the record and the chunks under the +// fourth. +func TestTwoLinksFromOneCountAreBothCounted(t *testing.T) { + for _, order := range [][]int{{0, 1, 2, 3}, {0, 2, 1, 3}, {1, 3, 0, 2}, {2, 3, 0, 1}} { + t.Run(fmt.Sprint(order), func(t *testing.T) { + store := newStubFilerStore() + id := linkedFile(t, store, "/d/x", "/d/y") + wrapper := countingWrapper(store) + ctx := context.Background() + writes := []func() error{ + func() error { return wrapper.UpdateEntry(ctx, linkName(id, "/d/x", 3)) }, + func() error { return wrapper.UpdateEntry(ctx, linkName(id, "/d/y", 3)) }, + func() error { return wrapper.InsertEntry(ctx, linkName(id, "/d/a", 3)) }, + func() error { return wrapper.InsertEntry(ctx, linkName(id, "/d/b", 3)) }, + } + for _, i := range order { + require.NoError(t, writes[i]()) + } + require.Equal(t, int32(4), linkCount(t, store, id)) + checkNames(t, wrapper, 4, "/d/x", "/d/y", "/d/a", "/d/b") + + for _, name := range []util.FullPath{"/d/x", "/d/y", "/d/a"} { + require.NoError(t, wrapper.DeleteEntry(ctx, name)) + } + require.Equal(t, int32(1), linkCount(t, store, id), "the record went before the file's last name") + checkNames(t, wrapper, 1, "/d/b") + }) + } +} + +// A write through one name carries the count its client had before another +// added a name: a mode change, or a flush of the file's content, which a mount +// sends as a create over the name. The count stays. +func TestWriteWithAnOldCountKeepsTheCount(t *testing.T) { + for _, write := range []struct { + name string + run func(*FilerStoreWrapper, context.Context, *Entry) error + }{ + {"UpdateEntry", (*FilerStoreWrapper).UpdateEntry}, + {"InsertEntry", (*FilerStoreWrapper).InsertEntry}, + } { + t.Run(write.name, func(t *testing.T) { + store := newStubFilerStore() + id := linkedFile(t, store, "/d/x", "/d/y", "/d/a") + wrapper := countingWrapper(store) + ctx := context.Background() + + old := linkName(id, "/d/y", 2) + old.Attr.Mode = 0o600 + require.NoError(t, write.run(wrapper, ctx, old)) + require.Equal(t, int32(3), linkCount(t, store, id)) + require.Equal(t, int32(3), old.HardLinkCounter, "the entry, and the event made from it, carry the count") + checkNames(t, wrapper, 3, "/d/x", "/d/y", "/d/a") + y, err := wrapper.FindEntry(ctx, "/d/y") + require.NoError(t, err) + require.EqualValues(t, 0o600, y.Attr.Mode, "the write itself is stored") + }) + } +} + +// The first link of a file: the client gives the file's one name a link id +// and sends the count with the new name in it already, then the new name. Or +// the other way around. The record has the client's count from the first +// write on, so that the file is not taken for one with a single name while +// the second is on its way, and the filer counts the names as they come. +func TestFirstLinkCountsTheNamesAsTheyCome(t *testing.T) { + chunk := []*filer_pb.FileChunk{{FileId: linkedChunk, Size: 4}} + plain := func(store *stubFilerStore) { + store.entries["/d/x"] = &Entry{FullPath: "/d/x", Attr: Attr{Mode: 0o644}, Chunks: chunk} + } + t.Run("old name first", func(t *testing.T) { + store := newStubFilerStore() + plain(store) + wrapper := countingWrapper(store) + ctx := context.Background() + id := NewHardLinkId() + + require.NoError(t, wrapper.UpdateEntry(ctx, linkName(id, "/d/x", 2))) + require.Equal(t, int32(2), linkCount(t, store, id)) + require.Equal(t, int32(1), namesCounted(t, store, id)) + require.NoError(t, wrapper.InsertEntry(ctx, linkName(id, "/d/y", 2))) + require.Equal(t, int32(2), linkCount(t, store, id)) + require.Equal(t, int32(2), namesCounted(t, store, id)) + checkNames(t, wrapper, 2, "/d/x", "/d/y") + }) + t.Run("new name first", func(t *testing.T) { + store := newStubFilerStore() + plain(store) + wrapper := countingWrapper(store) + ctx := context.Background() + id := NewHardLinkId() + + require.NoError(t, wrapper.InsertEntryKnownAbsent(ctx, linkName(id, "/d/y", 2))) + require.Equal(t, int32(1), namesCounted(t, store, id)) + require.NoError(t, wrapper.UpdateEntry(ctx, linkName(id, "/d/x", 2))) + require.Equal(t, int32(2), linkCount(t, store, id)) + require.Equal(t, int32(2), namesCounted(t, store, id)) + checkNames(t, wrapper, 2, "/d/x", "/d/y") + }) + // Another client deletes the source between the two writes of the link. + // The count the source's update left has the coming name in it: the + // delete is not the file's last (lastLinkDropped goes by the count it + // read), the chunks stay, and the new name reads them. + t.Run("the source goes before the new name comes", func(t *testing.T) { + store := newStubFilerStore() + plain(store) + wrapper := countingWrapper(store) + ctx := context.Background() + id := NewHardLinkId() + + require.NoError(t, wrapper.UpdateEntry(ctx, linkName(id, "/d/x", 2))) + x, err := wrapper.FindEntry(ctx, "/d/x") + require.NoError(t, err) + require.Equal(t, int32(2), x.HardLinkCounter, "the delete would take the source for the file's last name") + require.NoError(t, wrapper.DeleteEntry(ctx, "/d/x")) + require.Equal(t, int32(1), linkCount(t, store, id)) + require.Equal(t, int32(0), namesCounted(t, store, id)) + + require.NoError(t, wrapper.InsertEntry(ctx, linkName(id, "/d/y", 2))) + require.Equal(t, int32(1), namesCounted(t, store, id)) + y, err := wrapper.FindEntry(ctx, "/d/y") + require.NoError(t, err) + require.Len(t, y.GetChunks(), 1) + }) + t.Run("the new name is not made", func(t *testing.T) { + store := newStubFilerStore() + plain(store) + wrapper := countingWrapper(store) + ctx := context.Background() + id := NewHardLinkId() + + require.NoError(t, wrapper.UpdateEntry(ctx, linkName(id, "/d/x", 2))) + // the client takes the link id off the name again + require.NoError(t, wrapper.UpdateEntry(ctx, &Entry{FullPath: "/d/x", Attr: Attr{Mode: 0o644}, Chunks: chunk})) + x, err := wrapper.FindEntry(ctx, "/d/x") + require.NoError(t, err) + require.Empty(t, x.HardLinkId) + require.Equal(t, int32(0), namesCounted(t, store, id), "a name was left counted on a link no name holds") + }) +} + +// A write the store refuses, sent again: the name is counted once it is +// stored, and once. Counted with the refused attempt as well, every retry +// left the count one higher, and the record and the chunks outlived the +// file's last name. +func TestRefusedWriteOfANameIsCountedOnceWhenSentAgain(t *testing.T) { + for _, counted := range []bool{false, true} { + t.Run(fmt.Sprintf("names counted before=%v", counted), func(t *testing.T) { + store := newStubFilerStore() + id := linkedFile(t, store, "/d/x", "/d/y") + wrapper := countingWrapper(store) + ctx := context.Background() + if counted { + require.NoError(t, wrapper.UpdateEntry(ctx, linkName(id, "/d/x", 2))) + require.Equal(t, int32(2), namesCounted(t, store, id)) + } + + store.insertErr = storeRefusal + for i := 0; i < 3; i++ { + require.ErrorIs(t, wrapper.InsertEntry(ctx, linkName(id, "/d/a", 3)), storeRefusal) + } + require.Equal(t, int32(2), namesCounted(t, store, id), "a name that was not stored was counted") + store.insertErr = nil + require.NoError(t, wrapper.InsertEntry(ctx, linkName(id, "/d/a", 3))) + require.Equal(t, int32(3), linkCount(t, store, id)) + require.Equal(t, int32(3), namesCounted(t, store, id)) + + for _, name := range []util.FullPath{"/d/x", "/d/y", "/d/a"} { + require.NoError(t, wrapper.DeleteEntry(ctx, name)) + } + require.Equal(t, int32(0), linkCount(t, store, id), "the record outlived the file's last name") + require.Equal(t, int32(-1), namesCounted(t, store, id)) + }) + } +} + +// namesPutFailingStore refuses the puts of the names key that refuse picks, +// by their number. +type namesPutFailingStore struct { + *stubFilerStore + id HardLinkId + puts int + refuse func(put int) bool +} + +func (s *namesPutFailingStore) KvPut(ctx context.Context, key []byte, value []byte) error { + if bytes.Equal(key, linkNamesKey(s.id)) { + if s.puts++; s.refuse != nil && s.refuse(s.puts) { + return storeRefusal + } + } + return s.stubFilerStore.KvPut(ctx, key, value) +} + +// A store without transactions may fail between a name and the names +// recorded for it. They are recorded first: a name that cannot be counted is +// not stored, and sent again it is counted once. Recorded after the name, the +// failure left the name stored and not counted, and the write sent again +// found it there and did not count it either. +func TestNameThatCannotBeCountedIsNotStored(t *testing.T) { + for _, where := range []string{"default store", "path-specific store"} { + for _, known := range []bool{false, true} { + t.Run(fmt.Sprintf("%s, known absent=%v", where, known), func(t *testing.T) { + inner := newStubFilerStore() + id := linkedFile(t, inner, "/d/x", "/d/y") + store := &namesPutFailingStore{stubFilerStore: inner, id: id} + wrapper := countingWrapper(store) + names, name := inner, util.FullPath("/d/a") + if where == "path-specific store" { + names, name = newStubFilerStore(), "/s/a" + wrapper.AddPathSpecificStore("/s/", "s", names) + } + insert := wrapper.InsertEntry + if known { + insert = wrapper.InsertEntryKnownAbsent + } + ctx := context.Background() + require.NoError(t, wrapper.UpdateEntry(ctx, linkName(id, "/d/x", 2))) + require.Equal(t, int32(2), namesCounted(t, inner, id)) + + store.refuse = func(int) bool { return true } + require.ErrorIs(t, insert(ctx, linkName(id, name, 3)), storeRefusal) + require.Empty(t, names.entries[pathInStore(where, name)], "a name that could not be counted was stored") + store.refuse = nil + require.NoError(t, insert(ctx, linkName(id, name, 3))) + require.Equal(t, int32(3), namesCounted(t, inner, id)) + + for _, n := range []util.FullPath{"/d/x", "/d/y", name} { + require.NoError(t, wrapper.DeleteEntry(ctx, n)) + } + require.Equal(t, int32(0), linkCount(t, inner, id), "the record outlived the file's last name") + }) + } + } +} + +// pathInStore is the path a store holds name under: a path-specific store has +// its location cut off. +func pathInStore(where string, name util.FullPath) string { + if where == "path-specific store" { + return "/" + name.Name() + } + return string(name) +} + +// A name that was counted and then refused by the store is counted off again. +// Where that fails as well, the names recorded are above the names stored and +// the file is leaked. They are never below, which would delete it under a +// name. +func TestNameRefusedAfterItWasCountedLeavesTheNamesNoLower(t *testing.T) { + for _, where := range []string{"default store", "path-specific store"} { + t.Run(where, func(t *testing.T) { + inner := newStubFilerStore() + id := linkedFile(t, inner, "/d/x", "/d/y") + store := &namesPutFailingStore{stubFilerStore: inner, id: id} + wrapper := countingWrapper(store) + names, name := inner, util.FullPath("/d/a") + if where == "path-specific store" { + names, name = newStubFilerStore(), "/s/a" + wrapper.AddPathSpecificStore("/s/", "s", names) + } + ctx := context.Background() + require.NoError(t, wrapper.UpdateEntry(ctx, linkName(id, "/d/x", 2))) + require.Equal(t, int32(2), namesCounted(t, inner, id)) + + // the name is counted, refused, and cannot be counted off + names.insertErr = storeRefusal + counted := store.puts + store.refuse = func(put int) bool { return put > counted+1 } + require.ErrorIs(t, wrapper.InsertEntry(ctx, linkName(id, name, 3)), storeRefusal) + require.Equal(t, int32(3), namesCounted(t, inner, id)) + + names.insertErr, store.refuse = nil, nil + require.NoError(t, wrapper.InsertEntry(ctx, linkName(id, name, 3))) + for _, n := range []util.FullPath{"/d/x", "/d/y", name} { + require.NoError(t, wrapper.DeleteEntry(ctx, n)) + } + require.Equal(t, int32(1), linkCount(t, inner, id), "leaked, by the one name counted twice") + }) + } +} + +// storedThenFailingStore stores an entry and then fails the insert, as a +// store whose write deadline passes after it took the entry does. +type storedThenFailingStore struct { + *stubFilerStore +} + +func (s *storedThenFailingStore) InsertEntry(ctx context.Context, entry *Entry) error { + if err := s.stubFilerStore.InsertEntry(ctx, entry); err != nil { + return err + } + return context.DeadlineExceeded +} + +// A write that fails after the store took the name leaves the name counted, +// so a later write with the count from before the link cannot bring the +// count below the names. +func TestNameStoredByAFailedWriteStaysCounted(t *testing.T) { + for _, where := range []string{"default store", "path-specific store"} { + t.Run(where, func(t *testing.T) { + inner := newStubFilerStore() + id := linkedFile(t, inner, "/d/x", "/d/y") + var store FilerStore = inner + if where == "default store" { + store = &storedThenFailingStore{inner} + } + wrapper := countingWrapper(store) + name := util.FullPath("/d/a") + if where == "path-specific store" { + name = "/s/a" + wrapper.AddPathSpecificStore("/s/", "s", &storedThenFailingStore{newStubFilerStore()}) + } + ctx := context.Background() + require.NoError(t, wrapper.UpdateEntry(ctx, linkName(id, "/d/x", 2))) + require.ErrorIs(t, wrapper.InsertEntry(ctx, linkName(id, name, 3)), context.DeadlineExceeded) + require.Equal(t, int32(3), namesCounted(t, inner, id)) + + require.NoError(t, wrapper.UpdateEntry(ctx, linkName(id, "/d/x", 2))) + require.NoError(t, wrapper.DeleteEntry(ctx, "/d/x")) + require.NoError(t, wrapper.DeleteEntry(ctx, "/d/y")) + require.Equal(t, int32(1), linkCount(t, inner, id), "the file was deleted under a name it has") + }) + } +} + +// A rename stores the file under the new name (WithMovedLink) and deletes the +// old one (OP "MV"): the name moves, link and all, and neither the count nor +// the names counted change at any step. +func TestRenameOfALinkedNameKeepsTheCount(t *testing.T) { + store := newStubFilerStore() + id := linkedFile(t, store, "/d/x", "/d/y") + wrapper := countingWrapper(store) + ctx := context.Background() + + require.NoError(t, wrapper.InsertEntry(WithMovedLink(ctx), linkName(id, "/e/z", 2))) + require.Equal(t, int32(2), linkCount(t, store, id)) + require.Equal(t, int32(2), namesCounted(t, store, id)) + require.NoError(t, wrapper.DeleteEntry(context.WithValue(ctx, "OP", "MV"), "/d/x")) + require.Equal(t, int32(2), linkCount(t, store, id)) + require.Equal(t, int32(2), namesCounted(t, store, id)) + checkNames(t, wrapper, 2, "/d/y", "/e/z") + + require.NoError(t, wrapper.InsertEntryKnownAbsent(WithMovedLink(ctx), linkName(id, "/e/w", 2))) + z, err := wrapper.FindEntry(ctx, "/e/z") + require.NoError(t, err) + require.NoError(t, wrapper.DeleteOneEntry(context.WithValue(ctx, "OP", "MV"), z)) + require.Equal(t, int32(2), linkCount(t, store, id)) + require.Equal(t, int32(2), namesCounted(t, store, id)) + checkNames(t, wrapper, 2, "/d/y", "/e/w") + + // a renamed file written over a name of another file takes that name off the other + other := linkedFile(t, store, "/d/p", "/d/q") + require.NoError(t, wrapper.InsertEntry(WithMovedLink(ctx), linkName(id, "/d/q", 2))) + require.NoError(t, wrapper.DeleteEntry(context.WithValue(ctx, "OP", "MV"), "/e/w")) + require.Equal(t, int32(2), linkCount(t, store, id)) + require.Equal(t, int32(1), linkCount(t, store, other)) +} + +// A peer's update of a name is replayed as a delete of the row and an insert +// of the new one (Filer.Replay). The count comes out as it went in, also for +// a file's only name, whose record goes with the delete and is made again, +// and also when the event carries a count from before another name was added. +func TestReplayedUpdateKeepsTheCount(t *testing.T) { + for _, names := range [][]util.FullPath{{"/d/x"}, {"/d/x", "/d/y"}, {"/d/x", "/d/y", "/d/z"}} { + t.Run(fmt.Sprint(len(names)), func(t *testing.T) { + store := newStubFilerStore() + id := linkedFile(t, store, names...) + wrapper := countingWrapper(store) + ctx := context.Background() + + sent := int32(len(names)) + if sent > 2 { + sent = 2 // from before the third name + } + require.NoError(t, wrapper.DeleteEntry(ctx, "/d/x")) + require.NoError(t, wrapper.InsertEntry(ctx, linkName(id, "/d/x", sent))) + require.Equal(t, int32(len(names)), linkCount(t, store, id)) + checkNames(t, wrapper, int32(len(names)), names...) + }) + } +} + +// One file's name written over a name of another: the first gains a name, the +// second loses one. +func TestNameWrittenOverAnotherFilesNameCountsBoth(t *testing.T) { + store := newStubFilerStore() + f := linkedFile(t, store, "/d/f1", "/d/f2") + g := linkedFile(t, store, "/d/g1", "/d/g2") + wrapper := countingWrapper(store) + + require.NoError(t, wrapper.InsertEntry(context.Background(), linkName(g, "/d/f2", 2))) + require.Equal(t, int32(3), linkCount(t, store, g)) + require.Equal(t, int32(1), linkCount(t, store, f)) +} + +// A name whose record is lost says how many names its file had. Nothing else +// does, so that count is kept: too high leaks the chunks, too low deletes them +// under whatever other names are left. +func TestNameWithoutARecordKeepsItsCount(t *testing.T) { + store := newStubFilerStore() + id := linkedFile(t, store, "/d/x", "/d/y", "/d/z") + delete(store.kv, string(id)) + wrapper := countingWrapper(store) + + require.NoError(t, wrapper.UpdateEntry(context.Background(), linkName(id, "/d/x", 3))) + require.Equal(t, int32(3), linkCount(t, store, id)) + + // and so does one a rename moves + delete(store.kv, string(id)) + require.NoError(t, wrapper.InsertEntry(WithMovedLink(context.Background()), linkName(id, "/e/y", 3))) + require.Equal(t, int32(3), linkCount(t, store, id)) +} + +// A store that only copies some of a filer's entries (a mount's metadata +// cache) does not see every name: it stores the count the filer sent. +func TestCopyOfTheEntriesTakesTheCountItIsGiven(t *testing.T) { + store := newStubFilerStore() + id := linkedFile(t, store, "/d/x") + wrapper := NewFilerStoreWrapper(store) + + require.NoError(t, wrapper.UpdateEntry(context.Background(), linkName(id, "/d/x", 5))) + require.Equal(t, int32(5), linkCount(t, store, id)) + require.NoError(t, wrapper.InsertEntry(context.Background(), linkName(id, "/d/y", 6))) + require.Equal(t, int32(6), linkCount(t, store, id)) +} + +// Names added and removed at once on one filer: every one is counted. +func TestConcurrentLinksAndUnlinksAreAllCounted(t *testing.T) { + store := newStubFilerStore() + id := linkedFile(t, store, "/d/x", "/d/y") + wrapper := countingWrapper(store) + ctx := context.Background() + const n = 40 + for i := 0; i < n; i++ { + require.NoError(t, wrapper.InsertEntry(ctx, linkName(id, util.FullPath(fmt.Sprintf("/d/old%d", i)), 2))) + } + require.Equal(t, int32(n+2), linkCount(t, store, id)) + + var wg sync.WaitGroup + errs := make(chan error, 2*n) + for i := 0; i < n; i++ { + wg.Add(2) + go func(i int) { + defer wg.Done() + errs <- wrapper.InsertEntry(ctx, linkName(id, util.FullPath(fmt.Sprintf("/d/new%d", i)), 2)) + }(i) + go func(i int) { + defer wg.Done() + if i%2 == 0 { + errs <- wrapper.DeleteEntry(ctx, util.FullPath(fmt.Sprintf("/d/old%d", i))) + } + }(i) + } + wg.Wait() + close(errs) + for err := range errs { + require.NoError(t, err) + } + require.Equal(t, int32(2+n+n/2), linkCount(t, store, id)) +} + +// versionedStore is a store two filers share whose commits are refused when a +// row or a key the transaction wrote was committed by another since it began, +// as TiKV refuses them. +type versionedStore struct { + *stubFilerStore + vmu sync.Mutex + clock int64 + committed map[string]int64 + // afterRead runs after a transaction read a row ("r/d/x") or a key ("k" + // and the key), outside every lock + afterRead func(what string) +} + +type versionedTxn struct { + store *versionedStore + start int64 + rows map[string]*Entry // nil: deleted + keys map[string][]byte // nil: deleted +} + +type versionedTxnKey struct{} + +func newVersionedStore() *versionedStore { + return &versionedStore{stubFilerStore: newStubFilerStore(), committed: map[string]int64{}} +} + +func (s *versionedStore) RefusesConflictingCommits() bool { return true } + +func (s *versionedStore) txn(ctx context.Context) *versionedTxn { + txn, _ := ctx.Value(versionedTxnKey{}).(*versionedTxn) + return txn +} + +// wrote marks what a write outside a transaction committed. +func (s *versionedStore) wrote(what string) { + s.vmu.Lock() + defer s.vmu.Unlock() + s.clock++ + s.committed[what] = s.clock +} + +func (s *versionedStore) BeginTransaction(ctx context.Context) (context.Context, error) { + s.vmu.Lock() + defer s.vmu.Unlock() + return context.WithValue(ctx, versionedTxnKey{}, &versionedTxn{store: s, start: s.clock, rows: map[string]*Entry{}, keys: map[string][]byte{}}), nil +} + +func (s *versionedStore) CommitTransaction(ctx context.Context) error { + txn := s.txn(ctx) + s.vmu.Lock() + defer s.vmu.Unlock() + for p := range txn.rows { + if s.committed["r"+p] > txn.start { + return fmt.Errorf("row %s: %w", p, ErrTransactionConflict) + } + } + for key := range txn.keys { + if s.committed["k"+key] > txn.start { + return fmt.Errorf("key %x: %w", key, ErrTransactionConflict) + } + } + s.clock++ + bare := context.Background() + for p, row := range txn.rows { + if row == nil { + s.stubFilerStore.DeleteEntry(bare, util.FullPath(p)) + } else { + s.stubFilerStore.InsertEntry(bare, row) + } + s.committed["r"+p] = s.clock + } + for key, value := range txn.keys { + if value == nil { + s.stubFilerStore.KvDelete(bare, []byte(key)) + } else { + s.stubFilerStore.KvPut(bare, []byte(key), value) + } + s.committed["k"+key] = s.clock + } + return nil +} + +func (s *versionedStore) RollbackTransaction(context.Context) error { return nil } + +func (s *versionedStore) FindEntry(ctx context.Context, p util.FullPath) (*Entry, error) { + txn := s.txn(ctx) + if txn != nil { + if row, found := txn.rows[string(p)]; found { + if row == nil { + return nil, filer_pb.ErrNotFound + } + return row.ShallowClone(), nil + } + } + from := s + if txn != nil { + // reads go through the transaction's store, as TiKV's do + from = txn.store + } + row, err := from.stubFilerStore.FindEntry(ctx, p) + if txn != nil && s.afterRead != nil { + s.afterRead("r" + string(p)) + } + return row, err +} + +func (s *versionedStore) InsertEntry(ctx context.Context, entry *Entry) error { + if txn := s.txn(ctx); txn != nil { + txn.rows[string(entry.FullPath)] = entry + return nil + } + s.wrote("r" + string(entry.FullPath)) + return s.stubFilerStore.InsertEntry(ctx, entry) +} + +func (s *versionedStore) UpdateEntry(ctx context.Context, entry *Entry) error { + return s.InsertEntry(ctx, entry) +} + +func (s *versionedStore) DeleteEntry(ctx context.Context, p util.FullPath) error { + if txn := s.txn(ctx); txn != nil { + txn.rows[string(p)] = nil + return nil + } + s.wrote("r" + string(p)) + return s.stubFilerStore.DeleteEntry(ctx, p) +} + +func (s *versionedStore) KvGet(ctx context.Context, key []byte) ([]byte, error) { + txn := s.txn(ctx) + if txn != nil { + if value, found := txn.keys[string(key)]; found { + if value == nil { + return nil, ErrKvNotFound + } + return value, nil + } + } + value, err := s.stubFilerStore.KvGet(ctx, key) + if txn != nil && s.afterRead != nil { + s.afterRead("k" + string(key)) + } + return value, err +} + +func (s *versionedStore) KvPut(ctx context.Context, key []byte, value []byte) error { + if txn := s.txn(ctx); txn != nil { + txn.keys[string(key)] = append([]byte{}, value...) + return nil + } + s.wrote("k" + string(key)) + return s.stubFilerStore.KvPut(ctx, key, value) +} + +func (s *versionedStore) KvDelete(ctx context.Context, key []byte) error { + if txn := s.txn(ctx); txn != nil { + txn.keys[string(key)] = nil + return nil + } + s.wrote("k" + string(key)) + return s.stubFilerStore.KvDelete(ctx, key) +} + +// once runs f the first time what is read in a transaction. +func (s *versionedStore) once(t *testing.T, what string, f func() error) (ran *bool) { + ran = new(bool) + s.afterRead = func(read string) { + if read == what && !*ran { + *ran = true + require.NoError(t, f()) + } + } + return ran +} + +// Two filers on one store each add a name to the same file, the second +// between the first one's read of the names counted and its write. The store +// refuses the first one's commit, it counts again from what is there now, and +// both names are counted. The same for a name taken off in between. +func TestLinkCountedAgainAfterAnotherFilerChangedTheRecord(t *testing.T) { + for _, between := range []struct { + name string + run func(*FilerStoreWrapper, HardLinkId) error + want int32 + }{ + {"link", func(other *FilerStoreWrapper, id HardLinkId) error { + return other.InsertEntry(context.Background(), linkName(id, "/d/b", 3)) + }, 4}, + {"unlink", func(other *FilerStoreWrapper, id HardLinkId) error { + return other.DeleteEntry(context.Background(), "/d/y") + }, 2}, + } { + t.Run(between.name, func(t *testing.T) { + store := newVersionedStore() + id := linkedFile(t, store.stubFilerStore, "/d/x", "/d/y") + one, other := countingWrapper(store), countingWrapper(store) + + raced := store.once(t, "k"+string(id), func() error { return between.run(other, id) }) + require.NoError(t, one.InsertEntry(context.Background(), linkName(id, "/d/a", 3))) + require.True(t, *raced) + require.Equal(t, between.want, namesCounted(t, store.stubFilerStore, id)) + // the count is the client's 3 where that is more than the names: too high only leaks + count := between.want + if count < 3 { + count = 3 + } + require.Equal(t, count, linkCount(t, store.stubFilerStore, id)) + }) + } +} + +// A mount flushes a file through one of its names, a create over the name, +// while another filer deletes that name: its row goes after this filer looked +// the name up and found it one of the file's, and its link comes off after +// this filer's write (dropLink). The write stores the name again. The store +// refuses the commit over the delete of the row, and run again the write +// finds the name gone and counts it. Kept at the old count, the name was one +// more than the count once the delete took its link off. +func TestNameDeletedByAnotherFilerIsCountedWhenStoredAgain(t *testing.T) { + store := newVersionedStore() + id := linkedFile(t, store.stubFilerStore, "/d/x", "/d/y") + one, other := countingWrapper(store), countingWrapper(store) + ctx := context.Background() + + raced := store.once(t, "r/d/y", func() error { return store.DeleteEntry(ctx, "/d/y") }) + require.NoError(t, one.InsertEntry(ctx, linkName(id, "/d/y", 2))) + require.True(t, *raced) + require.NoError(t, other.DeleteHardLink(ctx, id)) + require.Equal(t, int32(2), linkCount(t, store.stubFilerStore, id)) + checkNames(t, one, 2, "/d/x", "/d/y") +} + +// A name in a path-specific store is not in the record's transaction. The +// change of the record that is refused and run again must not find the name +// its first run stored: it is stored after the count is settled, and counted +// once. +func TestNameInAPathSpecificStoreIsCountedOnce(t *testing.T) { + store := newVersionedStore() + id := linkedFile(t, store.stubFilerStore, "/d/x", "/d/y") + elsewhere := newStubFilerStore() + one, other := countingWrapper(store), countingWrapper(store) + one.AddPathSpecificStore("/s/", "s", elsewhere) + other.AddPathSpecificStore("/s/", "s", elsewhere) + + raced := store.once(t, "k"+string(id), func() error { + return other.InsertEntry(context.Background(), linkName(id, "/d/b", 3)) + }) + require.NoError(t, one.InsertEntry(context.Background(), linkName(id, "/s/a", 3))) + require.True(t, *raced) + require.Equal(t, int32(4), linkCount(t, store.stubFilerStore, id)) + checkNames(t, one, 4, "/d/x", "/d/y", "/d/b", "/s/a") + + require.NoError(t, one.InsertEntryKnownAbsent(context.Background(), linkName(id, "/s/c", 3))) + require.Equal(t, int32(5), linkCount(t, store.stubFilerStore, id)) +} + +// insertHookStore runs onInsert before it stores an entry. +type insertHookStore struct { + *stubFilerStore + onInsert func(*Entry) + inserts atomic.Int32 +} + +func (s *insertHookStore) InsertEntry(ctx context.Context, entry *Entry) error { + if s.onInsert != nil { + s.onInsert(entry) + } + defer s.inserts.Add(1) + return s.stubFilerStore.InsertEntry(ctx, entry) +} + +// Two creates of one new name in a path-specific store on this filer: the +// second waits for the first one's name, finds it, and does not count it +// again. Counted twice, the file outlived its last name. +func TestNameInAPathSpecificStoreCreatedTwiceIsCountedOnce(t *testing.T) { + store := newStubFilerStore() + id := linkedFile(t, store, "/d/x", "/d/y") + elsewhere := &insertHookStore{stubFilerStore: newStubFilerStore()} + one := countingWrapper(store) + one.AddPathSpecificStore("/s/", "s", elsewhere) + ctx := context.Background() + + var second sync.Once + elsewhere.onInsert = func(*Entry) { + second.Do(func() { + done := make(chan error, 1) + go func() { done <- one.InsertEntry(ctx, linkName(id, "/s/a", 3)) }() + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(100 * time.Millisecond): + } + }) + } + require.NoError(t, one.InsertEntry(ctx, linkName(id, "/s/a", 3))) + require.Eventually(t, func() bool { return elsewhere.inserts.Load() == 2 }, time.Second, 10*time.Millisecond) + checkNames(t, one, 3, "/d/x", "/d/y", "/s/a") + + for _, name := range []util.FullPath{"/d/x", "/d/y", "/s/a"} { + require.NoError(t, one.DeleteEntry(ctx, name)) + } + require.Equal(t, int32(0), linkCount(t, store, id)) +} + +// A name in a path-specific store of the same kind is looked up there, not +// through the default store's transaction: written again, it keeps the count. +func TestNameInAPathSpecificStoreOfTheSameKindIsFoundThere(t *testing.T) { + store := newVersionedStore() + id := linkedFile(t, store.stubFilerStore, "/d/x", "/d/y") + elsewhere := newVersionedStore() + one := countingWrapper(store) + one.AddPathSpecificStore("/s/", "s", elsewhere) + ctx := context.Background() + + require.NoError(t, one.InsertEntry(ctx, linkName(id, "/s/a", 3))) + require.Equal(t, int32(3), linkCount(t, store.stubFilerStore, id)) + require.NoError(t, one.UpdateEntry(ctx, linkName(id, "/s/a", 3))) + require.Equal(t, int32(3), linkCount(t, store.stubFilerStore, id)) +} + +// Inside a transaction the caller opened, the record is changed in that +// transaction: its commit is the caller's to run again. +func TestLinkCountInsideACallersTransactionOpensNone(t *testing.T) { + store := newVersionedStore() + id := linkedFile(t, store.stubFilerStore, "/d/x", "/d/y") + f := &Filer{Store: countingWrapper(store)} + + ctx, err := f.BeginTransaction(context.Background()) + require.NoError(t, err) + require.NoError(t, f.Store.InsertEntry(ctx, linkName(id, "/d/a", 3))) + require.Equal(t, int32(2), linkCount(t, store.stubFilerStore, id), "written before the caller committed") + require.NoError(t, f.CommitTransaction(ctx)) + require.Equal(t, int32(3), linkCount(t, store.stubFilerStore, id)) +} diff --git a/weed/filer/filerstore_hardlink.go b/weed/filer/filerstore_hardlink.go index 54db58feb7..04f60ca40a 100644 --- a/weed/filer/filerstore_hardlink.go +++ b/weed/filer/filerstore_hardlink.go @@ -15,37 +15,351 @@ import ( // handleUpdateToHardLinks saves the shared record of entry, a file a write is // 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. -func (fsw *FilerStoreWrapper) handleUpdateToHardLinks(ctx context.Context, entry *Entry) (replaced HardLinkId, err error) { +// 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 +// (recordLinkNames). +func (fsw *FilerStoreWrapper) handleUpdateToHardLinks(ctx, findCtx context.Context, entry *Entry) (replaced HardLinkId, names *linkNames, err error) { if entry.IsDirectory() { - return nil, nil - } - - if len(entry.HardLinkId) > 0 { - // handle hard links - glog.V(4).InfofCtx(ctx, "handleUpdateToHardLinks %s HardLinkId %x counter=%d chunks=%d", - entry.FullPath, entry.HardLinkId, entry.HardLinkCounter, len(entry.GetChunks())) - if err := fsw.setHardLink(ctx, entry); err != nil { - return nil, fmt.Errorf("setHardLink %d: %v", entry.HardLinkId, err) - } + 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(ctx, entry.FullPath) + existingEntry, err := actualStore.FindEntry(findCtx, entry.FullPath) if err != nil && err != filer_pb.ErrNotFound { - return nil, fmt.Errorf("update existing entry %s: %v", entry.FullPath, err) + return nil, nil, fmt.Errorf("update existing entry %s: %v", entry.FullPath, err) + } + // the name at entry's path is one of the file's names already + held := err == nil && bytes.Equal(existingEntry.HardLinkId, entry.HardLinkId) + + if len(entry.HardLinkId) > 0 { + // handle hard links + glog.V(4).InfofCtx(ctx, "handleUpdateToHardLinks %s HardLinkId %x counter=%d chunks=%d", + entry.FullPath, entry.HardLinkId, entry.HardLinkCounter, len(entry.GetChunks())) + var saveErr error + if names, saveErr = fsw.saveHardLink(ctx, entry, !held); saveErr != nil { + return nil, nil, fmt.Errorf("setHardLink %d: %v", entry.HardLinkId, saveErr) + } } // the old hard link, dropped after the write - if err == nil && len(existingEntry.HardLinkId) != 0 && !bytes.Equal(existingEntry.HardLinkId, entry.HardLinkId) { - return existingEntry.HardLinkId, nil + if err == nil && len(existingEntry.HardLinkId) != 0 && !held { + return existingEntry.HardLinkId, names, nil } - return nil, nil + return nil, names, nil } +// writeWithHardLink saves entry's shared record, if it has one, and stores +// entry with write. It returns the hard link the name at entry's path had +// before, for the caller to drop, when the write put another file there. +// +// 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) { + // 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. + // Two filers that store the same such name at the same moment both find + // it absent and both count it: the count is one too high from then on, + // and the file's record and chunks outlive its last name. + together := fsw.getActualStore(entry.FullPath) == fsw.defaultStore + var names *linkNames + storeName := func(ctx context.Context) error { return write(ctx, entry) } + var store func(context.Context) error + if !together { + store = func(ctx context.Context) error { + return fsw.storeCountedName(ctx, entry, names, false, storeName) + } + } + err = fsw.changeLinkRecord(ctx, entry, func(txCtx context.Context) error { + // A store of the same kind would read the name through the + // default store's transaction, from the default store. + findCtx := txCtx + if !together { + findCtx = ctx + } + var err error + if replaced, names, err = fsw.handleUpdateToHardLinks(txCtx, findCtx, entry); err != nil { + return err + } + if err = fsw.recordLinkNames(txCtx, names); err != nil || !together { + return err + } + return fsw.storeCountedName(txCtx, entry, names, true, storeName) + }, store) + return replaced, err +} + +// saveHardLink saves the shared record of entry, whose name joins the file's +// names with this write or is one of them already. A filer's own store +// (countsLinks) first raises entry's count to the names it counts itself +// (countLink); the caller is inside changeLinkRecord, and records the names +// it gets back before it stores the name. +func (fsw *FilerStoreWrapper) saveHardLink(ctx context.Context, entry *Entry, joins bool) (names *linkNames, err error) { + if fsw.countsLinks { + if names, err = fsw.countLink(ctx, entry, joins); err != nil { + return nil, err + } + } + return names, fsw.setHardLink(ctx, entry) +} + +type movedLinkKey struct{} + +// WithMovedLink marks the context of the write that stores a renamed entry +// under its new name. The name brings its hard link along: it is not counted +// as a new one, as the delete of its old name (OP "MV") does not count it off. +func WithMovedLink(ctx context.Context) context.Context { + return context.WithValue(ctx, movedLinkKey{}, true) +} + +// linkNames is the number of names a filer's own store counts for a +// hard-linked file, kept next to the file's shared record under linkNamesKey. +// +// The count in the record is the clients': each works it out from the entry +// it last read, one more for the name it is about to make, and its write +// replaces the whole record. Two mounts that each add a name to a file with +// two both send three, and one that only changes the mode sends the count it +// had before another added a name. The record then counted fewer names than +// the file had, the delete of the last counted one deleted the record and +// the chunks (lastLinkDropped), and the names left over read chunks that +// were gone. +// +// So the filer counts as well: one more for each name stored that did not +// hold the link before, one less for each deleted. The record gets whichever +// is higher, the count a client sends or the names counted here. It is never +// lower than what the client alone would have left, which still has the name +// of a link in the making in it while only the source's update has arrived, +// and never lower than the names the file has. +type linkNames struct { + id HardLinkId + count int32 // the names once the write is stored + joined bool // the write adds one + recorded int32 // the names recorded now; -1: none +} + +// linkNamesKey does not start with the random link id, which may start as a +// directory's entry keys do in a store keyed by path (etcd, leveldb) and be +// listed there. The prefix is short: the id stays in the first 8 bytes that +// SQL and Cassandra split off as the key's directory. +func linkNamesKey(hardLinkId HardLinkId) []byte { + return append([]byte("names."), hardLinkId...) +} + +// readLinkNames reads the names counted for hardLinkId; known is false where +// none were counted yet (a record from before the filer counted). +func (fsw *FilerStoreWrapper) readLinkNames(ctx context.Context, hardLinkId HardLinkId) (count int32, known bool, err error) { + value, err := fsw.KvGet(ctx, linkNamesKey(hardLinkId)) + if errors.Is(err, ErrKvNotFound) { + return 0, false, nil + } + if err != nil { + return 0, false, err + } + if len(value) != 4 { + return 0, false, nil + } + return int32(util.BytesToUint32(value)), true, nil +} + +func (fsw *FilerStoreWrapper) writeLinkNames(ctx context.Context, hardLinkId HardLinkId, count int32) error { + value := make([]byte, 4) + util.Uint32toBytes(value, uint32(count)) + return fsw.KvPut(ctx, linkNamesKey(hardLinkId), value) +} + +// countLink raises entry's link count to the names the file has once this +// write is stored, and returns them for recordLinkNames. The caller is inside +// changeLinkRecord. +func (fsw *FilerStoreWrapper) countLink(ctx context.Context, entry *Entry, joins bool) (*linkNames, error) { + names := &linkNames{id: entry.HardLinkId, joined: joins && ctx.Value(movedLinkKey{}) == nil, recorded: -1} + count, known, err := fsw.readLinkNames(ctx, entry.HardLinkId) + if err != nil { + return nil, err + } + if known { + names.count, names.recorded = count, count + } else if value, err := fsw.KvGet(ctx, entry.HardLinkId); err == nil { + // A record from before the filer counted: its count stands in, and is + // recorded now. Read again after a write the store refused, the record + // would have that write's count in it. + shared := &Entry{} + if err = shared.DecodeAttributesAndChunks(value); err != nil { + return nil, err + } + names.count, names.recorded = shared.HardLinkCounter, shared.HardLinkCounter + if err = fsw.writeLinkNames(ctx, entry.HardLinkId, names.recorded); err != nil { + return nil, err + } + } else if !errors.Is(err, ErrKvNotFound) { + return nil, err + } + if names.joined { + names.count++ + } + if names.count < 1 { + names.count = 1 // the name being written + } + if entry.HardLinkCounter < names.count { + entry.HardLinkCounter = names.count + } + return names, nil +} + +// recordLinkNames records the names counted for a hard link, inside the +// change of the record that counted them and before the name that was counted +// is stored. storeCountedName takes the name off them again when the store +// does not take it, so a write the store refused counts once when it is sent +// again. +// +// Where one of the two fails halfway on a store without transactions, the +// names recorded are one above the names stored, and the file is leaked. +// Recorded after the name, they were left one below: sent again, the write +// found its name stored and did not count it, and a count below the names is +// what deletes a file under one of them. +func (fsw *FilerStoreWrapper) recordLinkNames(ctx context.Context, names *linkNames) error { + if names == nil || names.recorded == names.count { + return nil + } + return fsw.writeLinkNames(ctx, names.id, names.count) +} + +// storeCountedName stores, with write, entry's name, which recordLinkNames +// has counted. A name the store does not take is counted off again, from what +// is recorded by then: a caller past the change that counted (inChange false, +// under the record's lock still) may find another filer has changed it. +func (fsw *FilerStoreWrapper) storeCountedName(ctx context.Context, entry *Entry, names *linkNames, inChange bool, write func(context.Context) error) error { + err := write(ctx) + if err == nil || names == nil || names.recorded == names.count || fsw.nameStoredAnyway(ctx, entry) { + return err + } + unrecord := func(ctx context.Context) error { + count, known, readErr := fsw.readLinkNames(ctx, names.id) + if readErr != nil || !known { + return readErr + } + added := names.count + if names.recorded > 0 { + added -= names.recorded + } + if count -= added; count <= 0 && names.recorded < 0 { + return fsw.KvDelete(ctx, linkNamesKey(names.id)) // none were recorded before + } + if count < 0 { + count = 0 + } + return fsw.writeLinkNames(ctx, names.id, count) + } + var unrecordErr error + if inChange { + unrecordErr = unrecord(ctx) + } else { + unrecordErr = fsw.commitLinkRecord(ctx, names.id, unrecord) + } + if unrecordErr != nil { + glog.ErrorfCtx(ctx, "hard link %x counts a name that was not stored: %v", names.id, unrecordErr) + } + return err +} + +// nameStoredAnyway tells whether a write that returned an error stored +// entry's name all the same, as one whose deadline passed after the store +// took it does. Where that cannot be told, the name stays counted. +func (fsw *FilerStoreWrapper) nameStoredAnyway(ctx context.Context, entry *Entry) bool { + stored, err := fsw.getActualStore(entry.FullPath).FindEntry(ctx, entry.FullPath) + if errors.Is(err, filer_pb.ErrNotFound) { + return false + } + return err != nil || bytes.Equal(stored.HardLinkId, entry.HardLinkId) +} + +// changeLinkRecord runs change, which reads the shared record of entry's hard +// link and writes it back, so that no other change of the record comes +// between the two. Entries without a hard link, and stores that take the +// count as it is sent, just run it. store, if any, stores a name the record's +// transaction does not hold once change is saved, before this filer changes +// the record again: the next change finds the name. +// +// On this filer the record's lock sees to that. Another filer on the same +// store is kept out by a transaction, where the store refuses to commit one +// over a change made since it began (ConflictRefusingStore); change then runs +// again, with the count the client sent. A caller that has a transaction open +// already leaves the refusal to it. Other stores shared by several filers have +// no such guard, nor has a change inside a transaction of a store that does +// not refuse such commits (the SQL stores). +func (fsw *FilerStoreWrapper) changeLinkRecord(ctx context.Context, entry *Entry, change, store func(ctx context.Context) error) error { + if !fsw.countsLinks || len(entry.HardLinkId) == 0 || entry.IsDirectory() { + if err := change(ctx); err != nil || store == nil { + return err + } + return store(ctx) + } + sent := entry.HardLinkCounter + return fsw.lockLinkRecord(ctx, entry.HardLinkId, func(ctx context.Context) error { + entry.HardLinkCounter = sent + return change(ctx) + }, store) +} + +func (fsw *FilerStoreWrapper) lockLinkRecord(ctx context.Context, hardLinkId HardLinkId, change, store func(ctx context.Context) error) error { + inTransaction := ctx.Value(storeTransactionKey{}) != nil + // A real transaction keeps its connection until it commits, and the + // holder of the lock may be waiting for one (as for lockDirectoryCreate): + // inside one the lock is not taken, and the change is as safe from the + // others as the store's transactions make it. + isolating, _ := fsw.defaultStore.(IsolatingTransactionStore) + if !inTransaction || isolating == nil || !isolating.IsolatesTransactions() { + var h uint32 + for _, b := range hardLinkId { + h = h*31 + uint32(b) + } + lock := &fsw.linkLocks[h%uint32(len(fsw.linkLocks))] + lock.Lock() + defer lock.Unlock() + } + if err := fsw.commitLinkRecord(ctx, hardLinkId, change); err != nil || store == nil { + return err + } + return store(ctx) +} + +// commitLinkRecord runs change in a transaction of its own where the store +// refuses conflicting commits, and again while it does; the caller holds the +// record's lock. +func (fsw *FilerStoreWrapper) commitLinkRecord(ctx context.Context, hardLinkId HardLinkId, change func(ctx context.Context) error) error { + refusing, ok := fsw.defaultStore.(ConflictRefusingStore) + if !ok || !refusing.RefusesConflictingCommits() || ctx.Value(storeTransactionKey{}) != nil { + return change(ctx) + } + for attempt := 1; ; attempt++ { + txCtx, err := fsw.BeginTransaction(ctx) + if err != nil { + return err + } + if err = change(txCtx); err != nil { + fsw.RollbackTransaction(txCtx) + return err + } + if err = fsw.CommitTransaction(txCtx); err == nil { + return nil + } + fsw.RollbackTransaction(txCtx) + if !errors.Is(err, ErrTransactionConflict) || attempt == linkRecordAttempts { + return err + } + glog.V(1).InfofCtx(ctx, "hard link %x: changing its record again (%d of %d): %v", hardLinkId, attempt+1, linkRecordAttempts, err) + time.Sleep(time.Duration(attempt) * 10 * time.Millisecond) + } +} + +// linkRecordAttempts bounds how often a change of a hard link's record runs +// its transaction while the store refuses the commit. +const linkRecordAttempts = 5 + // dropLink takes the name at p off its file's hard link once the store no // longer holds the name: deleted, or replaced by a write of another file. // @@ -114,6 +428,15 @@ func (fsw *FilerStoreWrapper) maybeReadHardLink(ctx context.Context, entry *Entr } func (fsw *FilerStoreWrapper) DeleteHardLink(ctx context.Context, hardLinkId HardLinkId) error { + if !fsw.countsLinks { + return fsw.deleteHardLink(ctx, hardLinkId) + } + return fsw.lockLinkRecord(ctx, hardLinkId, func(ctx context.Context) error { + return fsw.deleteHardLink(ctx, hardLinkId) + }, nil) +} + +func (fsw *FilerStoreWrapper) deleteHardLink(ctx context.Context, hardLinkId HardLinkId) error { key := hardLinkId glog.V(4).InfofCtx(ctx, "DeleteHardLink HardLinkId %x", key) value, err := fsw.KvGet(ctx, key) @@ -131,11 +454,34 @@ func (fsw *FilerStoreWrapper) DeleteHardLink(ctx context.Context, hardLinkId Har } entry.HardLinkCounter-- + names, counted := int32(0), false + if fsw.countsLinks { + if names, counted, err = fsw.readLinkNames(ctx, hardLinkId); err != nil { + return err + } + if names--; counted && entry.HardLinkCounter < names { + // the names counted here outlast a count a client left too low + entry.HardLinkCounter = names + } + } if entry.HardLinkCounter <= 0 { glog.V(4).InfofCtx(ctx, "DeleteHardLink KvDelete HardLinkId %x counter reached %d", key, entry.HardLinkCounter) + if counted { + if err = fsw.KvDelete(ctx, linkNamesKey(hardLinkId)); err != nil { + return err + } + } return fsw.KvDelete(ctx, key) } + if counted { + if names < 0 { + names = 0 + } + if err = fsw.writeLinkNames(ctx, hardLinkId, names); err != nil { + return err + } + } // POSIX: update ctime when nlink changes (a hard link was removed). entry.Attr.Ctime = time.Now().UTC() diff --git a/weed/filer/filerstore_wrapper.go b/weed/filer/filerstore_wrapper.go index 584768a386..a3d609c0e4 100644 --- a/weed/filer/filerstore_wrapper.go +++ b/weed/filer/filerstore_wrapper.go @@ -7,6 +7,7 @@ import ( "io" "math" "strings" + "sync" "time" "github.com/seaweedfs/seaweedfs/weed/glog" @@ -40,6 +41,14 @@ type FilerStoreWrapper struct { pathToStore ptrie.Trie[string] storeIdToStore map[string]FilerStore hasPathSpecificStore bool // fast check to skip MatchPrefix when no path-specific stores + + // countsLinks is set on a filer's own store (Filer.SetStore): it holds + // every name of a hard-linked file, so it counts them itself and lets + // no write leave the file's link count below that (linkNames). A wrapper + // around a copy of some entries, such as a mount's metadata cache, stores + // the count it is given. + countsLinks bool + linkLocks [64]sync.Mutex } func NewFilerStoreWrapper(store FilerStore) *FilerStoreWrapper { @@ -161,14 +170,10 @@ func (fsw *FilerStoreWrapper) InsertEntry(ctx context.Context, entry *Entry) err entry.FullPath, entry.HardLinkId, entry.HardLinkCounter) } - replacedLink, err := fsw.handleUpdateToHardLinks(ctx, entry) + replacedLink, err := fsw.writeWithHardLink(ctx, entry, actualStore.InsertEntry) if err != nil { return err } - - if err := actualStore.InsertEntry(ctx, entry); err != nil { - return err - } fsw.dropLink(ctx, entry.FullPath, replacedLink) return nil } @@ -194,9 +199,24 @@ func (fsw *FilerStoreWrapper) InsertEntryKnownAbsent(ctx context.Context, entry if len(entry.HardLinkId) > 0 { glog.V(4).InfofCtx(ctx, "InsertEntryKnownAbsent %s has HardLinkId %x counter=%d", entry.FullPath, entry.HardLinkId, entry.HardLinkCounter) - if err := fsw.setHardLink(ctx, entry); err != nil { - return fmt.Errorf("setHardLink %x: %v", entry.HardLinkId, err) + var names *linkNames + storeName := func(ctx context.Context) error { return actualStore.InsertEntry(ctx, entry) } + var store func(context.Context) error + if actualStore != fsw.defaultStore { + store = func(ctx context.Context) error { + return fsw.storeCountedName(ctx, entry, names, false, storeName) + } } + return fsw.changeLinkRecord(ctx, entry, func(ctx context.Context) error { + var err error + if names, err = fsw.saveHardLink(ctx, entry, true); err != nil { + return fmt.Errorf("setHardLink %x: %v", entry.HardLinkId, err) + } + if err = fsw.recordLinkNames(ctx, names); err != nil || store != nil { + return err // outside the record's transaction: stored after it + } + return fsw.storeCountedName(ctx, entry, names, true, storeName) + }, store) } return actualStore.InsertEntry(ctx, entry) @@ -223,14 +243,10 @@ func (fsw *FilerStoreWrapper) UpdateEntry(ctx context.Context, entry *Entry) err entry.FullPath, entry.HardLinkId, entry.HardLinkCounter) } - replacedLink, err := fsw.handleUpdateToHardLinks(ctx, entry) + replacedLink, err := fsw.writeWithHardLink(ctx, entry, actualStore.UpdateEntry) if err != nil { return err } - - if err := actualStore.UpdateEntry(ctx, entry); err != nil { - return err - } fsw.dropLink(ctx, entry.FullPath, replacedLink) return nil } diff --git a/weed/filer/leveldb/leveldb_store_hardlink_test.go b/weed/filer/leveldb/leveldb_store_hardlink_test.go new file mode 100644 index 0000000000..c35f6de1b0 --- /dev/null +++ b/weed/filer/leveldb/leveldb_store_hardlink_test.go @@ -0,0 +1,135 @@ +package leveldb + +import ( + "context" + "errors" + "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" +) + +// A filer on a real store, sent what two mounts send when both add a name to +// a file at once: each read the file's count as 2 and sends 3. The filer +// counts the four names itself and keeps the count at no less, a later write +// with an old count changes nothing, and the file outlives the three names a +// count of 3 would have taken for all of them. +func TestTwoClientsLinkingOneFileAreBothCounted(t *testing.T) { + testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil) + store := &LevelDBStore{} + if err := store.initialize(t.TempDir()); err != nil { + t.Fatalf("initialize leveldb: %v", err) + } + t.Cleanup(store.Shutdown) + testFiler.SetStore(store) + ctx := context.Background() + + name := func(p util.FullPath, id filer.HardLinkId, count int32) *filer.Entry { + return &filer.Entry{ + FullPath: p, + Attr: filer.Attr{Mode: 0644, Mtime: time.Unix(1700000000, 0)}, + Chunks: []*filer_pb.FileChunk{{FileId: "3,0c03", Size: 4}}, + HardLinkId: id, + HardLinkCounter: count, + } + } + create := func(p util.FullPath, id filer.HardLinkId, count int32) { + t.Helper() + if err := testFiler.CreateEntry(ctx, name(p, id, count), nil, false, false, nil, false, testFiler.MaxFilenameLength); err != nil { + t.Fatalf("create %s: %v", p, err) + } + } + update := func(p util.FullPath, id filer.HardLinkId, count int32) { + t.Helper() + old, err := testFiler.FindEntry(ctx, p) + if err != nil { + t.Fatalf("find %s: %v", p, err) + } + if err := testFiler.UpdateEntry(ctx, old, name(p, id, count), false); err != nil { + t.Fatalf("update %s: %v", p, err) + } + } + check := func(want int32, paths ...util.FullPath) { + t.Helper() + for _, p := range paths { + e, err := testFiler.FindEntry(ctx, p) + if err != nil { + t.Fatalf("find %s: %v", p, err) + } + if e.HardLinkCounter != want || len(e.GetChunks()) != 1 { + t.Fatalf("%s: link count %d with %d chunk(s), want %d with 1", p, e.HardLinkCounter, len(e.GetChunks()), want) + } + } + } + remove := func(p util.FullPath) { + t.Helper() + if err := testFiler.DeleteEntryMetaAndData(ctx, p, false, false, true, false, nil, time.Time{}); err != nil { + t.Fatalf("delete %s: %v", p, err) + } + } + + create("/d/x", nil, 0) + id := filer.NewHardLinkId() + + // the first link, as a mount sends it + update("/d/x", id, 2) + create("/d/y", id, 2) + check(2, "/d/x", "/d/y") + + // two mounts, each from a count of 2 + update("/d/x", id, 3) + update("/d/y", id, 3) + create("/d/a", id, 3) + create("/d/b", id, 3) + check(4, "/d/x", "/d/y", "/d/a", "/d/b") + + // a mount that has not heard of either link changes the file through y + update("/d/y", id, 2) + check(4, "/d/x", "/d/y", "/d/a", "/d/b") + + remove("/d/x") + remove("/d/y") + remove("/d/a") + check(1, "/d/b") + + remove("/d/b") + if _, err := testFiler.FindEntry(ctx, "/d/b"); !errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("find /d/b after its delete: %v", err) + } + if _, err := store.KvGet(ctx, id); !errors.Is(err, filer.ErrKvNotFound) { + t.Fatalf("the file's record after its last name went: %v", err) + } +} + +// A link id is random bytes and can start as the keys of the root's entries +// do here: the root still lists. +func TestRootListsWithALinkIdLikeItsKeys(t *testing.T) { + testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil) + store := &LevelDBStore{} + if err := store.initialize(t.TempDir()); err != nil { + t.Fatalf("initialize leveldb: %v", err) + } + t.Cleanup(store.Shutdown) + testFiler.SetStore(store) + ctx := context.Background() + + id := filer.HardLinkId("/\x00abcdefghijklmn\x01") + for _, p := range []util.FullPath{"/d/x", "/d/y"} { + entry := &filer.Entry{ + FullPath: p, + Attr: filer.Attr{Mode: 0644, Mtime: time.Unix(1700000000, 0)}, + Chunks: []*filer_pb.FileChunk{{FileId: "3,0c03", Size: 4}}, + HardLinkId: id, + HardLinkCounter: 2, + } + if err := testFiler.CreateEntry(ctx, entry, nil, false, false, nil, false, testFiler.MaxFilenameLength); err != nil { + t.Fatalf("create %s: %v", p, err) + } + } + if _, err := store.ListDirectoryEntries(ctx, "/", "", true, 100, func(*filer.Entry) (bool, error) { return true, nil }); err != nil { + t.Fatalf("list /: %v", err) + } +} diff --git a/weed/mount/weedfs_file_mkrm_test.go b/weed/mount/weedfs_file_mkrm_test.go index 137efcf6ac..77f28c4564 100644 --- a/weed/mount/weedfs_file_mkrm_test.go +++ b/weed/mount/weedfs_file_mkrm_test.go @@ -17,6 +17,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/proto" ) type createEntryTestServer struct { @@ -27,7 +28,11 @@ type createEntryTestServer struct { lastUID uint32 lastGID uint32 lastMode uint32 + lastEntry *filer_pb.Entry cachedRemote *filer_pb.Entry + // updateEntry and lookupEntry answer those calls when set + updateEntry func(*filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) + lookupEntry func(*filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) } type createEntrySnapshot struct { @@ -44,6 +49,7 @@ func (s *createEntryTestServer) CreateEntry(ctx context.Context, req *filer_pb.C s.lastDirectory = req.GetDirectory() if req.GetEntry() != nil { s.lastName = req.GetEntry().GetName() + s.lastEntry = proto.Clone(req.GetEntry()).(*filer_pb.Entry) if req.GetEntry().GetAttributes() != nil { s.lastUID = req.GetEntry().GetAttributes().GetUid() s.lastGID = req.GetEntry().GetAttributes().GetGid() @@ -54,9 +60,19 @@ func (s *createEntryTestServer) CreateEntry(ctx context.Context, req *filer_pb.C } func (s *createEntryTestServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) { + if s.updateEntry != nil { + return s.updateEntry(req) + } return &filer_pb.UpdateEntryResponse{}, nil } +func (s *createEntryTestServer) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + if s.lookupEntry != nil { + return s.lookupEntry(req) + } + return s.UnimplementedSeaweedFilerServer.LookupDirectoryEntry(ctx, req) +} + func (s *createEntryTestServer) snapshot() createEntrySnapshot { s.mu.Lock() defer s.mu.Unlock() diff --git a/weed/mount/weedfs_link.go b/weed/mount/weedfs_link.go index 93ff5eb0d6..3ca1833412 100644 --- a/weed/mount/weedfs_link.go +++ b/weed/mount/weedfs_link.go @@ -9,6 +9,8 @@ import ( "time" "github.com/seaweedfs/go-fuse/v2/fuse" + "google.golang.org/grpc/codes" + grpcstatus "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweedfs/weed/filer" @@ -184,7 +186,46 @@ func (wfs *WFS) Link(cancel <-chan struct{}, in *fuse.LinkIn, name string, out * // apply changes to the filer, and also apply to local metaCache wfs.mapPbIdFromLocalToFiler(request.Entry) - updateResp, err := wfs.streamUpdateEntry(context.Background(), updateOldEntryRequest) + var updateResp *filer_pb.UpdateEntryResponse + var err error + if len(origHardLinkId) > 0 { + updateResp, err = wfs.streamUpdateEntry(context.Background(), updateOldEntryRequest) + } else { + // The file's first link, under a link id made up here. Another client + // may have linked the file since the entry was read, and the filer + // refuses the file a second id. The stream reduces that refusal to + // EIO; the unary RPC keeps it apart from an I/O failure. + update := func() error { + return wfs.withFilerClient(context.Background(), false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error { + var updateErr error + updateResp, updateErr = client.UpdateEntry(ctx, updateOldEntryRequest) + if grpcstatus.Code(updateErr) == codes.FailedPrecondition { + // the filer's verdict: no other filer's error replaces it + return errors.Join(filer_pb.ErrPreconditionFailed, updateErr) + } + return updateErr + }) + } + if err = update(); errors.Is(err, filer_pb.ErrPreconditionFailed) { + // link under the id the file has by now + stored, _, _, getErr := filer_pb.GetEntry(ctx, wfs, oldEntryPath) + if getErr == nil && stored != nil && len(stored.HardLinkId) > 0 && stored.Attributes != nil { + glog.V(1).Infof("Link: %s is hard link %x already, not %x", oldEntryPath, stored.HardLinkId, oldEntry.HardLinkId) + // a rollback puts back what the file has now + origHardLinkId, origHardLinkCounter = stored.HardLinkId, stored.HardLinkCounter + // both writes carry the file as stored now, not as first read + oldEntry = stored + oldEntry.HardLinkCounter++ + oldEntry.Attributes.Mtime, oldEntry.Attributes.MtimeNs = linkNow.Unix(), int32(linkNow.Nanosecond()) + oldEntry.Attributes.Ctime, oldEntry.Attributes.CtimeNs = linkNow.Unix(), int32(linkNow.Nanosecond()) + updateOldEntryRequest.Entry = oldEntry + request.Entry.Attributes, request.Entry.Chunks, request.Entry.Extended = oldEntry.Attributes, oldEntry.GetChunks(), oldEntry.Extended + request.Entry.Content, request.Entry.RemoteEntry = oldEntry.Content, oldEntry.RemoteEntry + request.Entry.HardLinkId, request.Entry.HardLinkCounter = oldEntry.HardLinkId, oldEntry.HardLinkCounter + err = update() + } + } + } if err == nil { updateEvent := updateResp.GetMetadataEvent() if updateEvent == nil { diff --git a/weed/mount/weedfs_link_test.go b/weed/mount/weedfs_link_test.go index ef8b3fcb26..2c368429b3 100644 --- a/weed/mount/weedfs_link_test.go +++ b/weed/mount/weedfs_link_test.go @@ -1,15 +1,22 @@ package mount import ( + "bytes" "context" + "net" + "sync" "testing" "time" "github.com/seaweedfs/go-fuse/v2/fuse" "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/mount/meta_cache" + "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/util" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // linkTestSource seeds the meta cache with an entry and registers it with @@ -329,3 +336,125 @@ func TestSyncHardLinkSiblingFetchFailureKeepsVersion(t *testing.T) { t.Errorf("pending event was fenced by the patched version: FileSize = %d, want 99", sib.FileSize) } } + +// Two mounts link a file that has one name at the same moment. Each gives the +// file a link id of its own, and the filer refuses the second: the file has +// the first one's by then. The mount reads the entry again and makes its name +// under the id the file has, instead of failing the link or, as before the +// filer refused, moving the file to an id of its own and splitting its names +// over two. +func TestFirstLinkTakesTheLinkIdAnotherClientGaveTheFile(t *testing.T) { + t.Run("one filer", func(t *testing.T) { + wfs, server := newCreateTestWFS(t) + testFirstLinkTakesTheLinkId(t, wfs, server) + }) + // the refusal stays the answer when the next filer cannot be reached + t.Run("next filer down", func(t *testing.T) { + wfs, server := newCreateTestWFS(t) + down, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + downPort := down.Addr().(*net.TCPAddr).Port + down.Close() + wfs.option.FilerAddresses = append(wfs.option.FilerAddresses, pb.NewServerAddressWithGrpcPort("127.0.0.1:1", downPort)) + testFirstLinkTakesTheLinkId(t, wfs, server) + }) +} + +func testFirstLinkTakesTheLinkId(t *testing.T, wfs *WFS, server *createEntryTestServer) { + sourcePath, sourceInode := linkTestSource(t, wfs, "shared.txt", 0) + + theirs := filer.NewHardLinkId() + var mu sync.Mutex + var updates []*filer_pb.Entry + server.updateEntry = func(req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) { + mu.Lock() + defer mu.Unlock() + updates = append(updates, proto.Clone(req.GetEntry()).(*filer_pb.Entry)) + if !bytes.Equal(req.GetEntry().GetHardLinkId(), theirs) { + return nil, status.Errorf(codes.FailedPrecondition, "already a hard link: %s", sourcePath) + } + return &filer_pb.UpdateEntryResponse{}, nil + } + server.lookupEntry = func(req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{ + Name: req.GetName(), + Attributes: &filer_pb.FuseAttributes{FileMode: 0o600, FileSize: 12, Crtime: 1, Mtime: 1, Uid: 99, Gid: 100}, + Chunks: []*filer_pb.FileChunk{{FileId: "3,0c03", Size: 12}}, + Content: []byte("inline"), + RemoteEntry: &filer_pb.RemoteEntry{StorageName: "s3", RemoteETag: "etag"}, + HardLinkId: theirs, + HardLinkCounter: 2, + }}, nil + } + + out := doLink(t, wfs, sourceInode, "mine.txt") + if out.NodeId != sourceInode { + t.Fatalf("Link NodeId = %d, want the source node id %d", out.NodeId, sourceInode) + } + + mu.Lock() + defer mu.Unlock() + if len(updates) != 2 { + t.Fatalf("the source was updated %d times, want the refused update and one more", len(updates)) + } + if len(updates[0].GetHardLinkId()) == 0 || bytes.Equal(updates[0].GetHardLinkId(), theirs) { + t.Fatalf("first update carried link id %x, want one made by this mount", updates[0].GetHardLinkId()) + } + if !bytes.Equal(updates[1].GetHardLinkId(), theirs) || updates[1].GetHardLinkCounter() != 3 { + t.Fatalf("second update carried link id %x count %d, want the file's %x and 3", updates[1].GetHardLinkId(), updates[1].GetHardLinkCounter(), theirs) + } + if updates[1].GetAttributes().GetFileMode() != 0o600 || len(updates[1].GetChunks()) != 1 || string(updates[1].GetContent()) != "inline" { + t.Fatalf("second update carried mode %o, %d chunks and content %q, want the stored 600, 1 and \"inline\"", updates[1].GetAttributes().GetFileMode(), len(updates[1].GetChunks()), updates[1].GetContent()) + } + server.mu.Lock() + created := server.lastEntry + server.mu.Unlock() + if created.GetName() != "mine.txt" || !bytes.Equal(created.GetHardLinkId(), theirs) { + t.Fatalf("new name %q was made under link id %x, want %x", created.GetName(), created.GetHardLinkId(), theirs) + } + if created.GetAttributes().GetFileMode() != 0o600 || len(created.GetChunks()) != 1 || string(created.GetContent()) != "inline" { + t.Fatalf("new name has mode %o, %d chunks and content %q, want the stored 600, 1 and \"inline\"", created.GetAttributes().GetFileMode(), len(created.GetChunks()), created.GetContent()) + } + if created.GetRemoteEntry().GetRemoteETag() != "etag" { + t.Fatalf("new name has remote entry %v, want the stored one", created.GetRemoteEntry()) + } + linked, _, st := wfs.maybeLoadEntry(context.Background(), sourcePath) + if st != fuse.OK { + t.Fatalf("reload source: %v", st) + } + if !bytes.Equal(linked.HardLinkId, theirs) { + t.Fatalf("the mount has the source under link id %x, want %x", linked.HardLinkId, theirs) + } +} + +// A refusal with nothing behind it (the entry read again has no link id) +// fails the link: nothing is made under an id the filer did not take. +func TestFirstLinkRefusedWithoutALinkToTakeFails(t *testing.T) { + wfs, server := newCreateTestWFS(t) + _, sourceInode := linkTestSource(t, wfs, "shared.txt", 0) + + server.updateEntry = func(req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) { + return nil, status.Errorf(codes.FailedPrecondition, "precondition failed") + } + server.lookupEntry = func(req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{ + Name: req.GetName(), + Attributes: &filer_pb.FuseAttributes{FileMode: 0o644, FileSize: 12, Crtime: 1, Mtime: 1, Uid: 99, Gid: 100}, + }}, nil + } + + st := wfs.Link(make(chan struct{}), &fuse.LinkIn{ + InHeader: fuse.InHeader{NodeId: 1, Caller: fuse.Caller{Owner: fuse.Owner{Uid: 99, Gid: 100}}}, + Oldnodeid: sourceInode, + }, "mine.txt", &fuse.EntryOut{}) + if st == fuse.OK { + t.Fatal("Link reported success after the filer refused the source's update") + } + server.mu.Lock() + defer server.mu.Unlock() + if server.lastEntry != nil { + t.Fatalf("name %q was made after the refusal", server.lastEntry.GetName()) + } +} diff --git a/weed/server/filer_grpc_server.go b/weed/server/filer_grpc_server.go index 5b8c2b2140..4f02496ddb 100644 --- a/weed/server/filer_grpc_server.go +++ b/weed/server/filer_grpc_server.go @@ -1027,6 +1027,11 @@ func (fs *FilerServer) updateEntry(ctx context.Context, req *filer_pb.UpdateEntr if observed != nil && !clauseSatisfied(observed, entry) { refusal = status.Errorf(codes.FailedPrecondition, "entry changed during update: %s", fullpath) } + if refusal == nil && !req.IsFromOtherCluster { + if refusal, err = fs.refuseSecondHardLink(ctx, fullpath, entry, req.Entry); err != nil { + return err + } + } if transactional && observed == nil { observed = &filer_pb.WriteCondition_Clause{ Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, @@ -1156,6 +1161,35 @@ func (fs *FilerServer) runEntryTransaction(ctx context.Context, path util.FullPa } } +// refuseSecondHardLink refuses an update that gives a name which already +// holds a hard link another link id, one no file has yet. +// +// A client that links a file gives the file's name a link id first, a new one +// when the entry it read had none. Two clients that both read the entry +// before either wrote each bring an id of their own. Taken, the second would +// move the name to its id: the name the first client makes next would be +// alone on the first id, the second client's alone with the old name on the +// other, and the same chunks would belong to two files, each deleting them +// under the other when its last name goes. Refused, the client reads the +// entry again and links under the id the file has. +// +// An id that has a record belongs to a file already: writing it over a name +// of another file replaces that name, as before. A replicated update is not +// refused: the other cluster's link ids never get records here. +func (fs *FilerServer) refuseSecondHardLink(ctx context.Context, fullpath string, stored *filer.Entry, requested *filer_pb.Entry) (refusal, err error) { + if len(stored.HardLinkId) == 0 || len(requested.GetHardLinkId()) == 0 || bytes.Equal(stored.HardLinkId, requested.GetHardLinkId()) { + return nil, nil + } + if _, err := fs.filer.Store.KvGet(ctx, requested.GetHardLinkId()); !errors.Is(err, filer.ErrKvNotFound) { + if err != nil { + return nil, fmt.Errorf("read hard link %x of %s: %w", requested.GetHardLinkId(), fullpath, err) + } + return nil, nil + } + glog.V(1).InfofCtx(ctx, "UpdateEntry %s: is hard link %x already, not given %x", fullpath, stored.HardLinkId, requested.GetHardLinkId()) + return status.Errorf(codes.FailedPrecondition, "already a hard link: %s", fullpath), nil +} + func validateUpdateEntryPreconditions(entry *filer.Entry, expectedExtended map[string][]byte) error { if len(expectedExtended) == 0 { return nil diff --git a/weed/server/filer_grpc_server_hardlink_chunks_test.go b/weed/server/filer_grpc_server_hardlink_chunks_test.go index f5f43010b1..fd7039ebd1 100644 --- a/weed/server/filer_grpc_server_hardlink_chunks_test.go +++ b/weed/server/filer_grpc_server_hardlink_chunks_test.go @@ -9,6 +9,8 @@ import ( "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/util" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // A write that replaces one name of a hard-linked file unlinks that name and @@ -256,3 +258,80 @@ func TestAtomicRenameEntryOverLastHardLinkDeletesItsChunks(t *testing.T) { t.Fatal("hard link record kept after its last link was replaced") } } + +// Two clients link a file at the same moment, each from an entry that had no +// link yet, so each gives the name a link id of its own. The file has the +// first one's when the second arrives. Taken, the second would move the name +// to its id and leave the first client's new name alone on the other: one +// file's chunks under two link ids, each deleting them under the other with +// its last name. The update is refused, nothing changes, and the client links +// under the id the file has. +func TestUpdateEntryRefusesAFileASecondLinkId(t *testing.T) { + server, f, store, id := hardLinkChunkServer(t, 2) + second := filer.HardLinkId("hl-chunks-test-02") + + _, err := server.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{ + Directory: "/dir", Entry: dstEntry(second, 2, written(replacedChunk, 1)), + }) + if status.Code(err) != codes.FailedPrecondition { + t.Fatalf("update with a second link id: %v, want FailedPrecondition", err) + } + checkDeletions(t, f) + checkOtherLink(t, f, replacedChunk, 2) + dst, err := f.FindEntry(context.Background(), "/dir/dst.txt") + if err != nil { + t.Fatalf("find dst: %v", err) + } + if string(dst.HardLinkId) != string(id) { + t.Fatalf("dst has link id %q, want the file's %q", dst.HardLinkId, id) + } + if _, found := store.kv[string(second)]; found { + t.Fatal("the refused link id got a record") + } + + updateDst(t, server, dstEntry(id, 3, written(replacedChunk, 1))) + checkDeletions(t, f) +} + +// filer.sync sends the other cluster's link id without its record: taken. +func TestUpdateEntryFromOtherClusterTakesItsLinkId(t *testing.T) { + server, f, _, _ := hardLinkChunkServer(t, 2) + other := filer.HardLinkId("hl-chunks-test-02") + + if _, err := server.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{ + Directory: "/dir", Entry: dstEntry(other, 2, written(replacedChunk, 1)), IsFromOtherCluster: true, + }); err != nil { + t.Fatalf("replicated update with another link id: %v", err) + } + dst, err := f.FindEntry(context.Background(), "/dir/dst.txt") + if err != nil { + t.Fatalf("find dst: %v", err) + } + if string(dst.HardLinkId) != string(other) { + t.Fatalf("dst has link id %q, want the replicated %q", dst.HardLinkId, other) + } +} + +// A link id that has a record is another file's, not a second one for this +// file: an update that carries it puts that file at the name, which leaves +// the old file as a create over the name does. +func TestUpdateEntryWithAnotherFilesLinkIdReplacesTheName(t *testing.T) { + server, f, store, id := hardLinkChunkServer(t, 2) + another := filer.HardLinkId("hl-chunks-test-03") + shared := fileEntryWithChunk("/dir/third.txt", 505, writtenChunk) + shared.HardLinkId, shared.HardLinkCounter = another, 1 + blob, err := shared.EncodeAttributesAndChunks() + if err != nil { + t.Fatalf("encode hard link: %v", err) + } + store.kv[string(another)] = blob + store.entries["/dir/third.txt"] = shared + + updateDst(t, server, dstEntry(another, 2, written(writtenChunk, 2))) + + checkDeletions(t, f) + checkOtherLink(t, f, replacedChunk, 1) + if _, found := store.kv[string(id)]; !found { + t.Fatal("hard link record deleted while a link remains") + } +} diff --git a/weed/server/filer_grpc_server_rename.go b/weed/server/filer_grpc_server_rename.go index 0456df812a..a6f2e87202 100644 --- a/weed/server/filer_grpc_server_rename.go +++ b/weed/server/filer_grpc_server_rename.go @@ -588,7 +588,7 @@ func (fs *FilerServer) moveSelfEntry(ctx context.Context, stream filer_pb.Seawee if inPlace { var createdParents []*filer.Entry fs.filer.StampEntryCommitTsNs(newEntry) - replaceErr := fs.filer.ReplaceFileForRename(filer.WithCreatedParents(ctx, &createdParents), newEntry, fs.filer.MaxFilenameLength) + replaceErr := fs.filer.ReplaceFileForRename(filer.WithCreatedParents(filer.WithMovedLink(ctx), &createdParents), newEntry, fs.filer.MaxFilenameLength) // as for a create below: a parent the write had to create again // reaches peers through its own event, published before the move for _, parent := range createdParents { @@ -603,13 +603,13 @@ func (fs *FilerServer) moveSelfEntry(ctx context.Context, stream filer_pb.Seawee return filer_pb.ErrEntryNameTooLong } fs.filer.StampEntryCommitTsNs(newEntry) - if createErr := fs.filer.Store.InsertEntryKnownAbsent(filer.WithSuppressedMetadataEvents(ctx), newEntry); createErr != nil { + if createErr := fs.filer.Store.InsertEntryKnownAbsent(filer.WithSuppressedMetadataEvents(filer.WithMovedLink(ctx)), newEntry); createErr != nil { fs.filer.ReleaseEntryCommitTsNs(newEntry.CommitTsNs) return fmt.Errorf("insert entry %s: %v", newEntry.FullPath, createErr) } } else { var createdParents []*filer.Entry - createErr := fs.filer.CreateEntry(filer.WithCreatedParents(ctx, &createdParents), newEntry, nil, false, false, signatures, false, fs.filer.MaxFilenameLength) + createErr := fs.filer.CreateEntry(filer.WithCreatedParents(filer.WithMovedLink(ctx), &createdParents), newEntry, nil, false, false, signatures, false, fs.filer.MaxFilenameLength) // Peers replay events into their own store, so a new parent only // reaches them through its own create event, published before the move. for _, parent := range createdParents {