mount: keep a clean handle off the file a peer renamed over the one it has open (#12920)

* mount: keep a clean handle off the file a peer renamed over the one it has open

A peer renames another file over the one a handle has open here. When this
mount has looked the rename's source up, MovePath reports the handle's inode
as replaced and the handle is marked deleted. When it has not, which is the
usual case for "write a temp file, rename it over the real one" done on
another mount, MovePath has nothing to move and reports nothing. The event
for the target path then reaches the handle as an update: a dirty handle
refuses it, but a clean one installs the newcomer's entry, and everything
the descriptor does afterwards lands in the replacement: writes, mmap
writes, ftruncate, fchmod, fsetxattr.

A clean handle now takes an entry with another inode at its path for what it
is. The handle is marked deleted, as after a delete, and its inode gives the
name up as a replaced rename target does, so the kernel gets ESTALE for the
old inode, walks the path again and reaches the newcomer under an inode of
its own. An entry or a handle without an inode cannot tell and installs as
before, and so does an update in place, which keeps the inode.

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

* mount: a replaced handle keeps a surviving hard link, a renamed one ignores its old name

From the review of a4c9a89a6.

- A hard-linked file replaced under one of its names lives on under the
  others. The handle follows it to a name this mount knows, as after a
  peer's unlink of one name, instead of being marked deleted.
- A handle that just followed its file's rename no longer reads the cache
  at the path it left. When another file had taken that name before the
  rename was applied to the handle, the handle was marked deleted (and
  before this branch, installed that file's entry).
- The replaced name is taken from the inode only while it is still the
  inode's (RemovePathOf): a rename on this mount may have handed it to
  another inode in between.
- The kernel keeps resolving the name to the old inode for as long as it
  trusts its lookup (entryValidSec). A chmod by path in that window went to
  the detached handle and reported success. The lookup is dropped with
  EntryNotify, from the invalidation worker after the handle's locks are
  released.

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

* mount: mark a replaced handle deleted only once its inode gives up the name

The worker looks the inode up by name before it takes the handle's lock,
so a rename on this mount can move the inode off that name in between.
The handle was then marked deleted while its file lived on under the new
name, and its flushes were dropped. RemovePathOf now decides: when the
name is no longer the inode's, the event is another file's and the
handle is left alone.

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

* mount: release the worker gate on every exit of the renamed-handle test

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

* mount: check alias ownership before following surviving links

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-11-23 14:19:08 -08:00
1 parent c7cf9db27c
commit 6f248fc190
4 files changed
+503 -10

No files matched your search

+32
View File
@@ -607,6 +607,22 @@ func (i *InodeToPath) AddPath(inode uint64, path util.FullPath) {
}
}
// RemovePathOf takes path away from inode when the path is still the inode's,
// and reports whether it was. Checked and removed under one lock: a rename on
// this mount may have given the path to another inode since the caller looked,
// and that mapping is not the caller's to drop.
func (i *InodeToPath) RemovePathOf(inode uint64, path util.FullPath) bool {
i.Lock()
defer i.Unlock()
if current, found := i.path2inode[path]; !found || current != inode {
return false
}
delete(i.path2inode, path)
i.dropDirPath(inode)
i.removePathFromInode2Path(inode, path)
return true
}
// RemovePath drops the name. onStillReferenced, if given, runs under the
// table's lock when the kernel still holds lookup references to the inode:
// such an inode keeps receiving requests until the final forget, and holding
@@ -639,6 +655,22 @@ func (i *InodeToPath) RemoveAlias(path util.FullPath) (util.FullPath, bool) {
if !found {
return "", false
}
return i.removeAlias(inode, path)
}
// RemoveAliasOf drops path only while it still names inode and the inode
// keeps another name. Ownership is checked under the same lock as removal.
func (i *InodeToPath) RemoveAliasOf(inode uint64, path util.FullPath) (util.FullPath, bool) {
i.Lock()
defer i.Unlock()
if current, found := i.path2inode[path]; !found || current != inode {
return "", false
}
return i.removeAlias(inode, path)
}
// removeAlias requires the table lock and a path that belongs to inode.
func (i *InodeToPath) removeAlias(inode uint64, path util.FullPath) (util.FullPath, bool) {
ie := i.inode2path[inode]
if ie == nil {
return "", false
+27
View File
@@ -231,6 +231,33 @@ func TestLookupRecordsHardLinkNames(t *testing.T) {
}
}
func TestRemoveAliasOfChecksOwnership(t *testing.T) {
table := NewInodeToPath(util.FullPath("/"), 0)
inode := table.Lookup("/a", 1, false, true, 42, true)
if survivor, ok := table.RemoveAliasOf(inode, "/a"); ok || survivor != "" || !table.HasPath("/a") {
t.Fatal("removed the only name")
}
table.AddPath(inode, "/b")
if survivor, ok := table.RemoveAliasOf(inode+1, "/a"); ok || survivor != "" {
t.Fatalf("removed another inode's name: survivor %q", survivor)
}
if paths := table.GetAllPaths(inode); len(paths) != 2 || paths[0] != "/a" || paths[1] != "/b" {
t.Fatalf("ownership mismatch changed inode paths: %v", paths)
}
if got, found := table.GetInode("/a"); !found || got != inode {
t.Fatalf("ownership mismatch changed /a mapping: %d (found %v)", got, found)
}
if survivor, ok := table.RemoveAliasOf(inode, "/a"); !ok || survivor != "/b" || table.HasPath("/a") {
t.Fatalf("RemoveAliasOf(/a) = %q, %v, want /b", survivor, ok)
}
if survivor, ok := table.RemoveAliasOf(inode, "/a"); ok || survivor != "" {
t.Fatal("removed an absent name")
}
if got, status := table.GetPath(inode); status != fuse.OK || got != "/b" {
t.Fatalf("surviving path %q (%v), want /b", got, status)
}
}
func TestRemoveAliasKeepsSoleName(t *testing.T) {
table := NewInodeToPath(util.FullPath("/"), 0)
inode := table.Lookup("/a", 1, false, true, 42, true)
+84 -10
View File
@@ -1007,7 +1007,7 @@ func (wfs *WFS) onEntryInvalidation(invalidation meta_cache.EntryInvalidation) {
// the handle's own path bookkeeping. This is for the rest: the kernel goes
// on addressing a moved inode by nodeid whether or not anything holds it
// open.
handled, replacedInode := wfs.invalidateOpenFileHandle(invalidation)
handled, replacedInode, detached := wfs.invalidateOpenFileHandle(invalidation)
if !handled && invalidation.RenamedTo != "" {
_, replacedInode = wfs.inodeToPath.MovePath(invalidation.Path, invalidation.RenamedTo)
} else if !handled && invalidation.Deleted && len(invalidation.LiveHardLinkId) > 0 {
@@ -1023,6 +1023,32 @@ func (wfs *WFS) onEntryInvalidation(invalidation meta_cache.EntryInvalidation) {
if replacedInode != 0 {
wfs.markHandleDeleted(replacedInode)
}
// The kernel still resolves the name to the inode whose handle just lost
// it, for as long as it trusts its lookup. With that lookup dropped, a
// call by path reaches the file that has the name now.
if detached {
wfs.invalidateKernelEntry(invalidation.Path)
}
}
// invalidateKernelEntry drops the kernel's cached lookup of path, so its next
// use of the name asks again. Called from the invalidation worker with no
// handle lock held, for the reasons invalidateKernelDirListing gives: the
// kernel takes the parent directory's lock for it, and waits there for any
// request on that directory this mount is still serving.
func (wfs *WFS) invalidateKernelEntry(path util.FullPath) {
server := wfs.fuseServer
if server == nil {
return
}
dir, name := path.DirAndName()
dirInode, found := wfs.inodeToPath.GetInode(util.FullPath(dir))
if !found {
return
}
if status := server.EntryNotify(dirInode, name); status != fuse.OK && status != fuse.ENOENT && status != fuse.ENOSYS {
glog.V(4).Infof("invalidate kernel lookup of %s: %v", path, status)
}
}
// invalidateKernelDirListing drops the kernel's cached listing of the directory
@@ -1059,8 +1085,10 @@ func (wfs *WFS) MountRoot() util.FullPath {
// open, reporting whether it found one: a handle owns its inode's rename
// bookkeeping, and the caller moves the table only for inodes without one. Any
// inode a rename destroyed comes back for the caller to mark, since marking it
// here would hold two handle locks at once.
func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidation) (handled bool, replacedInode uint64) {
// here would hold two handle locks at once. detached reports that the handle's
// inode gave the event's path up to another file, for the caller to tell the
// kernel once the handle's locks are released.
func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidation) (handled bool, replacedInode uint64, detached bool) {
filePath, eventEntry, eventTsNs := invalidation.Path, invalidation.Entry, invalidation.TsNs
inode, inodeFound := wfs.inodeToPath.GetInode(filePath)
if !inodeFound {
@@ -1081,8 +1109,10 @@ func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidati
// below - a fence that skipped it would strand the inode and the handle on
// a name the filer has vacated. MovePath reports whether the source was
// still ours to move, which is what makes a replayed rename a no-op here.
moved := false
if invalidation.RenamedTo != "" {
if sourceInode, replaced := wfs.inodeToPath.MovePath(filePath, invalidation.RenamedTo); sourceInode != 0 {
moved = true
if replaced != inode {
replacedInode = replaced
}
@@ -1114,11 +1144,17 @@ func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidati
// A cached parent's store entry is the ordered merge of this event and
// anything applied since. An uncached parent takes no store writes, so a
// hit there is a stale leftover — use the event entry instead.
//
// A handle that just followed its file to another name has nothing to
// learn at the path it left: whatever the cache holds there by now is
// another file's. The rename's event for the new path brings the entry.
var candidate *filer_pb.Entry
candidateTsNs := eventTsNs
if storeEntry, storeVersionTsNs, found := wfs.cachedEntrySince(filePath, eventTsNs); found {
candidate = storeEntry.ToProtoEntry()
candidateTsNs = storeVersionTsNs
if !moved {
if storeEntry, storeVersionTsNs, found := wfs.cachedEntrySince(filePath, eventTsNs); found {
candidate = storeEntry.ToProtoEntry()
candidateTsNs = storeVersionTsNs
}
}
if candidate == nil && eventEntry != nil {
candidate = proto.Clone(eventEntry).(*filer_pb.Entry)
@@ -1139,7 +1175,7 @@ func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidati
if invalidation.Deleted {
// The next flush reads the survivor's stored entry before
// publishing, so the version stays where it was.
if len(invalidation.LiveHardLinkId) > 0 && wfs.followSurvivingLink(fh, filePath) {
if len(invalidation.LiveHardLinkId) > 0 && wfs.followSurvivingLink(fh, inode, filePath) {
fh.linkRefresh = invalidation.LiveHardLinkId
return
}
@@ -1174,6 +1210,35 @@ func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidati
}
return
}
// Another file has the name: a peer renamed it over the one this handle
// has open, from a source this mount never looked up, so no MovePath
// reported the handle's inode as replaced. Installing the newcomer would
// send every later write, truncate and chmod through this descriptor to
// it. The inode gives the name up instead, as a replaced rename target
// does: the kernel walks the path again and reaches the newcomer under an
// inode of its own.
if replacedByAnotherFile(candidate, base) {
// A hard-linked file lives on under its other names, and the handle
// with it under one this mount knows, as after a peer's unlink of
// one name. The next flush reads the survivor's stored entry before
// publishing, so the version stays where it was.
if len(base.HardLinkId) > 0 && wfs.followSurvivingLink(fh, inode, filePath) {
detached = true
fh.linkRefresh = base.HardLinkId
return
}
// A local rename may have moved the inode off the name since it was
// looked up; the file then lives on under its new one.
if !wfs.inodeToPath.RemovePathOf(inode, filePath) {
return
}
// No name left here: the handle's file is gone, as after a delete.
detached = true
fh.isDeleted = true
fh.deleteEpoch++
fh.advanceEntryVersion(candidateTsNs, 0)
return
}
// Dirty pages overlay content, so only a content change invalidates them:
// a metadata-only event (chmod, touch, or a committed copy's own event
// against an approximate base) leaves them valid.
@@ -1187,6 +1252,15 @@ func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidati
return
}
// replacedByAnotherFile reports whether stored is provably not the file base
// was: both carry an inode and the two differ. An update in place keeps the
// inode, so does a hard link made of the file; an entry without one cannot
// tell, and is not taken for another file.
func replacedByAnotherFile(stored, base *filer_pb.Entry) bool {
storedInode, baseInode := stored.GetAttributes().GetInode(), base.GetAttributes().GetInode()
return storedInode != 0 && baseInode != 0 && storedInode != baseInode
}
// cachedEntrySince returns the meta cache's entry at path when its directory is
// cached and the entry is no older than tsNs.
func (wfs *WFS) cachedEntrySince(path util.FullPath, tsNs int64) (*filer.Entry, int64, bool) {
@@ -1203,9 +1277,9 @@ func (wfs *WFS) cachedEntrySince(path util.FullPath, tsNs int64) (*filer.Entry,
// followSurvivingLink drops a hard link name another client deleted and
// keeps the handle on a name of the inode this mount still knows, reporting
// false when it knows none.
func (wfs *WFS) followSurvivingLink(fh *FileHandle, removed util.FullPath) bool {
survivor, ok := wfs.inodeToPath.RemoveAlias(removed)
// false when it knows none or the removed name no longer belongs to owner.
func (wfs *WFS) followSurvivingLink(fh *FileHandle, owner uint64, removed util.FullPath) bool {
survivor, ok := wfs.inodeToPath.RemoveAliasOf(owner, removed)
if ok {
fh.RememberPath(survivor)
wfs.readAuth.TrackHandle(survivor, fh)
@@ -4,8 +4,12 @@ import (
"context"
"net"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
@@ -2234,6 +2238,362 @@ func TestPeerTruncateWaitsForBufferedWrites(t *testing.T) {
}
}
// A peer putting another file (another inode) at the path of a clean handle
// must not hand the handle the newcomer: what the descriptor writes,
// truncates or chmods next would land in it. This mount never looked the
// rename's source up, so nothing reports the handle's inode as replaced. The
// handle's file is gone, and its inode gives the name up.
func TestPeerReplacementDetachesCleanHandle(t *testing.T) {
for _, name := range []string{"renamed-over", "replaced-in-place"} {
t.Run(name, func(t *testing.T) {
wfs := newInvalidateTestWFS(t)
path := util.FullPath("/dir/file")
inode := wfs.inodeToPath.Lookup(path, time.Now().Unix(), false, false, 0, true)
base := flushConditionEntry(1)
wfs.mapPbIdFromFilerToLocal(base)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, base, 0, 0)
replacement := flushConditionEntry(7)
replacement.Attributes.Inode = 99
old := flushConditionEntry(1)
if name == "renamed-over" {
old = proto.Clone(replacement).(*filer_pb.Entry)
old.Name = "file.new"
}
resp := &filer_pb.SubscribeMetadataResponse{
Directory: "/dir",
TsNs: 1500,
EventNotification: &filer_pb.EventNotification{
OldEntry: old,
NewEntry: replacement,
NewParentPath: "/dir",
},
}
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
t.Fatalf("apply: %v", err)
}
wfs.metaCache.WaitForEntryInvalidations()
if !fh.isDeleted {
t.Fatal("handle of the replaced file not marked deleted; its next write would go into the replacement")
}
if got := chunkFileKeys(fh.GetEntry().GetEntry()); len(got) != 1 || got[0] != 1 {
t.Fatalf("handle chunks %v, want its own", got)
}
if got := fh.baseEntry.Load().GetAttributes().GetInode(); got != 42 {
t.Fatalf("base inode %d, want the handle's own 42", got)
}
if got, found := wfs.inodeToPath.GetInode(path); found && got == inode {
t.Fatal("the name still answers to the replaced inode")
}
if runtime.GOOS == "linux" {
if status := wfs.pathlessInodeStatus(inode, fuse.ENOENT); status != fuse.Status(syscall.ESTALE) {
t.Fatalf("replaced inode answers %v, want ESTALE so the kernel walks the path again", status)
}
}
})
}
}
// The worker looks the inode up by name before it takes the handle's lock. A
// rename on this mount can move the inode off that name in between: the file
// lives on under its new name, so the handle is not the replaced file's.
func TestPeerReplacementAfterALocalRenameKeepsTheHandle(t *testing.T) {
wfs := newInvalidateTestWFS(t)
path, renamed := util.FullPath("/dir/file"), util.FullPath("/dir/renamed")
inode := wfs.inodeToPath.Lookup(path, time.Now().Unix(), false, false, 0, true)
base := flushConditionEntry(1)
wfs.mapPbIdFromFilerToLocal(base)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, base, 0, 0)
testLock := wfs.fhLockTable.AcquireLock("test", fh.fh, util.ExclusiveLock)
var releaseOnce sync.Once
release := func() { releaseOnce.Do(func() { wfs.fhLockTable.ReleaseLock(fh.fh, testLock) }) }
t.Cleanup(release)
replacement := flushConditionEntry(7)
replacement.Attributes.Inode = 99
resp := &filer_pb.SubscribeMetadataResponse{
Directory: "/dir",
TsNs: 1500,
EventNotification: &filer_pb.EventNotification{NewEntry: replacement, NewParentPath: "/dir"},
}
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
t.Fatalf("apply: %v", err)
}
waitForHandleLockWaiter(t, "invalidateOpenFileHandle")
wfs.inodeToPath.MovePath(path, renamed)
release()
wfs.metaCache.WaitForEntryInvalidations()
if fh.isDeleted {
t.Fatal("handle marked deleted while its file lives on under the name it was renamed to")
}
if got, found := wfs.inodeToPath.GetInode(renamed); !found || got != inode {
t.Fatalf("renamed name answers to %d (found %v), want %d", got, found, inode)
}
}
// A queued invalidation must not take a surviving name from a different
// hard-linked inode that local renames moved onto the invalidated path.
func TestPeerInvalidationLeavesAnotherInodesHardLinks(t *testing.T) {
for _, event := range []string{"replacement", "delete"} {
t.Run(event, func(t *testing.T) {
wfs := newInvalidateTestWFS(t)
path, renamed := util.FullPath("/dir/file"), util.FullPath("/dir/renamed")
incoming, alias := util.FullPath("/dir/incoming"), util.FullPath("/dir/alias")
inode := wfs.inodeToPath.Lookup(path, 1, false, true, 42, true)
other := wfs.inodeToPath.Lookup(incoming, 1, false, true, 99, true)
wfs.inodeToPath.AddPath(other, alias)
base := flushConditionEntry(1)
base.HardLinkId, base.HardLinkCounter = []byte{7, 7, 7}, 2
wfs.mapPbIdFromFilerToLocal(base)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, base, 0, 0)
testLock := wfs.fhLockTable.AcquireLock("test", fh.fh, util.ExclusiveLock)
var releaseOnce sync.Once
release := func() { releaseOnce.Do(func() { wfs.fhLockTable.ReleaseLock(fh.fh, testLock) }) }
t.Cleanup(release)
message := &filer_pb.EventNotification{OldEntry: proto.Clone(base).(*filer_pb.Entry)}
if event == "replacement" {
message.NewEntry = flushConditionEntry(7)
message.NewEntry.Attributes.Inode = 99
message.NewParentPath = "/dir"
}
resp := &filer_pb.SubscribeMetadataResponse{Directory: "/dir", TsNs: 1500, EventNotification: message}
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
t.Fatalf("apply: %v", err)
}
waitForHandleLockWaiter(t, "invalidateOpenFileHandle")
wfs.inodeToPath.MovePath(path, renamed)
wfs.inodeToPath.MovePath(incoming, path)
fh.RememberPath(renamed)
release()
wfs.metaCache.WaitForEntryInvalidations()
for _, name := range []util.FullPath{path, alias} {
if got, found := wfs.inodeToPath.GetInode(name); !found || got != other {
t.Errorf("%s maps to %d (found %v), want %d", name, got, found, other)
}
}
if paths := wfs.inodeToPath.GetAllPaths(other); len(paths) != 2 {
t.Errorf("other inode's paths %v, want both hard links", paths)
}
if fh.savedDir != "/dir" || fh.savedName != "renamed" || len(fh.linkRefresh) != 0 {
t.Errorf("handle followed another inode's alias: saved path %s/%s, linkRefresh %v", fh.savedDir, fh.savedName, fh.linkRefresh)
}
})
}
}
// waitForHandleLockWaiter returns once a goroutine in caller waits for a
// handle lock.
func waitForHandleLockWaiter(t *testing.T, caller string) {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
buf := make([]byte, 1<<20)
n := runtime.Stack(buf, true)
for _, stack := range strings.Split(string(buf[:n]), "\n\n") {
header, _, _ := strings.Cut(stack, "\n")
if strings.Contains(header, "[sync.Cond.Wait") && strings.Contains(stack, "."+caller+"(") {
return
}
}
runtime.Gosched()
}
t.Fatalf("%s never waited for the handle lock", caller)
}
// A hard-linked file a peer replaced under one of its names lives on under
// the others. The handle stays with it, under a name this mount knows, as
// after a peer's unlink of one name: marking it deleted would drop what the
// descriptor, or a later open of the other name, writes next.
func TestPeerReplacementOfOneHardLinkNameKeepsTheHandle(t *testing.T) {
wfs := newInvalidateTestWFS(t)
file, alias := util.FullPath("/dir/file"), util.FullPath("/dir/alias")
linkId := []byte{7, 7, 7}
inode := wfs.inodeToPath.Lookup(file, time.Now().Unix(), false, true, 42, true)
if got := wfs.inodeToPath.Lookup(alias, time.Now().Unix(), false, true, 42, true); got != inode {
t.Fatalf("alias inode %d, want the file's %d", got, inode)
}
base := flushConditionEntry(1)
base.HardLinkId, base.HardLinkCounter = linkId, 2
wfs.mapPbIdFromFilerToLocal(base)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, base, 0, 0)
replacement := flushConditionEntry(7)
replacement.Attributes.Inode = 99
resp := &filer_pb.SubscribeMetadataResponse{
Directory: "/dir",
TsNs: 1500,
EventNotification: &filer_pb.EventNotification{
OldEntry: flushConditionEntry(1),
NewEntry: replacement,
NewParentPath: "/dir",
},
}
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
t.Fatalf("apply: %v", err)
}
wfs.metaCache.WaitForEntryInvalidations()
if fh.isDeleted {
t.Fatal("handle marked deleted although the file lives on under its other name")
}
if got := chunkFileKeys(fh.GetEntry().GetEntry()); len(got) != 1 || got[0] != 1 {
t.Fatalf("handle chunks %v, want its own", got)
}
if got := fh.FullPath(); got != alias {
t.Fatalf("handle path %q, want the surviving name %q", got, alias)
}
if string(fh.linkRefresh) != string(linkId) {
t.Fatalf("linkRefresh %v, want %v so the next flush reads the survivor's entry", fh.linkRefresh, linkId)
}
if got, found := wfs.inodeToPath.GetInode(file); found && got == inode {
t.Fatal("the replaced name still answers to the hard link's inode")
}
if got, found := wfs.inodeToPath.GetInode(alias); !found || got != inode {
t.Fatalf("the surviving name answers to inode %d (found %v), want %d", got, found, inode)
}
}
// A peer renames the open file away and another file takes the old name. When
// the cache holds both changes before the rename is applied to the handle,
// the handle has already followed its file: what sits at the name it left is
// not a replacement of it, and not its entry either.
func TestRenamedHandleIgnoresWhatTookItsOldName(t *testing.T) {
wfs := newInvalidateTestWFS(t)
dir := util.FullPath("/dir")
wfs.inodeToPath.Lookup(dir, time.Now().Unix(), true, false, 0, true)
wfs.inodeToPath.MarkChildrenCached(dir)
current, archive := dir.Child("current"), dir.Child("archive")
inode := wfs.inodeToPath.Lookup(current, time.Now().Unix(), false, false, 0, true)
base := flushConditionEntry(1)
base.Name = "current"
wfs.mapPbIdFromFilerToLocal(base)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, base, 0, 0)
// hold the worker at its first invalidation until both events are cached
gate := make(chan struct{})
var openGate sync.Once
release := func() { openGate.Do(func() { close(gate) }) }
t.Cleanup(release)
var first atomic.Bool
wfs.SetEntryChangeListener(func(meta_cache.EntryInvalidation) {
if first.CompareAndSwap(false, true) {
<-gate
}
})
moved := flushConditionEntry(1)
moved.Name = "archive"
old := flushConditionEntry(1)
old.Name = "current"
newcomer := flushConditionEntry(7)
newcomer.Name = "current"
newcomer.Attributes.Inode = 99
for _, resp := range []*filer_pb.SubscribeMetadataResponse{
{Directory: "/dir", TsNs: 1500, EventNotification: &filer_pb.EventNotification{OldEntry: old, NewEntry: moved, NewParentPath: "/dir"}},
{Directory: "/dir", TsNs: 1600, EventNotification: &filer_pb.EventNotification{NewEntry: newcomer, NewParentPath: "/dir"}},
} {
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
t.Fatalf("apply: %v", err)
}
}
release()
wfs.metaCache.WaitForEntryInvalidations()
if fh.isDeleted {
t.Fatal("handle marked deleted for the file that took its old name; its writes to the renamed file would be dropped")
}
if got := fh.FullPath(); got != archive {
t.Fatalf("handle path %q, want %q", got, archive)
}
if got := fh.GetEntry().GetEntry().GetAttributes().GetInode(); got != 42 {
t.Fatalf("handle holds the entry of inode %d, want its own 42", got)
}
if got := chunkFileKeys(fh.GetEntry().GetEntry()); len(got) != 1 || got[0] != 1 {
t.Fatalf("handle chunks %v, want its own", got)
}
}
// RemovePathOf drops a name only while it is the inode's: a rename on this
// mount may have handed it to another inode in between.
func TestRemovePathOfLeavesAnotherInodesName(t *testing.T) {
table := NewInodeToPath(util.FullPath("/"), 0)
path := util.FullPath("/dir/file")
inode := table.Lookup(path, time.Now().Unix(), false, false, 0, true)
if table.RemovePathOf(inode+1, path) {
t.Fatal("removed a name that belongs to another inode")
}
if got, found := table.GetInode(path); !found || got != inode {
t.Fatalf("the name answers to %d (found %v), want %d", got, found, inode)
}
if !table.RemovePathOf(inode, path) {
t.Fatal("did not remove the inode's own name")
}
if _, found := table.GetInode(path); found {
t.Fatal("the name is still there")
}
if !table.HasInode(inode) {
t.Fatal("the inode went with its name; its open handle still needs it")
}
}
// An update in place keeps the file's inode, and an entry without an inode
// cannot tell which file it is: a clean handle installs both, as before.
func TestPeerUpdateOfTheSameFileStillInstalls(t *testing.T) {
for _, name := range []string{"same-inode", "event-without-inode", "handle-without-inode"} {
t.Run(name, func(t *testing.T) {
wfs := newInvalidateTestWFS(t)
path := util.FullPath("/dir/file")
inode := wfs.inodeToPath.Lookup(path, time.Now().Unix(), false, false, 0, true)
base := flushConditionEntry(1)
update := flushConditionEntry(7)
switch name {
case "event-without-inode":
update.Attributes.Inode = 0
case "handle-without-inode":
base.Attributes.Inode = 0
update.Attributes.Inode = 99
}
wfs.mapPbIdFromFilerToLocal(base)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, base, 0, 0)
resp := &filer_pb.SubscribeMetadataResponse{
Directory: "/dir",
TsNs: 1500,
EventNotification: &filer_pb.EventNotification{
OldEntry: flushConditionEntry(1),
NewEntry: update,
NewParentPath: "/dir",
},
}
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
t.Fatalf("apply: %v", err)
}
wfs.metaCache.WaitForEntryInvalidations()
if fh.isDeleted {
t.Fatal("handle marked deleted by an update of its own file; later writes would be dropped")
}
if got := chunkFileKeys(fh.GetEntry().GetEntry()); len(got) != 1 || got[0] != 7 {
t.Fatalf("handle chunks %v, want the update's", got)
}
if got, found := wfs.inodeToPath.GetInode(path); !found || got != inode {
t.Fatalf("the name answers to inode %d (found %v), want the handle's %d", got, found, inode)
}
})
}
}
// A peer replacing the file at the handle's path (another inode) leaves the
// dirty handle's writes and base alone instead of installing the newcomer,
// and the handle's flush then fails without touching the replacement.