检查新创建的文件时如何强制刷新NFS缓存?

howto force refresh NFS cache when checking newly created file?

在 Linux NFS 共享安装上创建文件时,客户端是 Linux 或 mac machines。文件存在与否是下一步做什么的关键,但检查并不总是return正确的结果:

例如我在 perl 中这样做,这仍然不能正常工作,尤其是 mac machines

write_key_file();  # write a file that must be checked before proceeding

当文件确实存在时,以下检查不能总是 return 为真

问题 - Perl 中的这个命令在 NFS 系统中没有 return 正确的状态:

if( -e $file){}

无意中听到的无效解决方案:

 sleep(5);   # wait 5 seconds
 system("ls -ltr"); # force to cache?
 if(-e $file){}

我不打算像这样检查每个文件,但有几个关键位置对于获取正确的文件状态很重要。

我们是否有更好的方法来强制刷新特定目录中特定文件的 nfs 缓存?谢谢。

我不确定这是一个 XY 问题,但有几个最薄弱的点都可以解决。

A -- NFS clients setting

如果现阶段有解决方案就好了!

B -- exit_code or return code of writing function

$exit_code = write_key_file();

它的问题,并不是所有的写法都在代码块的范围内。这只能解决部分问题。

C -- Disable NFS cache for the specific file or directory for file checking

我需要确定这是否可能以及如何实现?如果没有,为什么?

我对所有可能的解决方案持开放态度,没有解决方案或其他可能性。

此解决方案属于 B 类:exit_code 或 return 编写函数的代码

...only open() and fopen() need to guarantee that they get a consistent handle to a particular file for reading and writing. stat and friends are not required to retrieve fresh attributes. Thus, for the sake of close-to-open cache coherence, only open() and fopen() are considered an "open event" where fresh attributes need to be fetched immediately from the server[1].


以下解决方案属于 类别 A:NFS 客户端设置
即如果您不希望将缓存的 file/dir 条目提供给客户端,请禁用缓存。

设置共享缓存

If the file in the NFS mount (whose existence is being checked) is created by another application on the same client (possibly using another mount point to the same NFS export) the consider using a single shared NFS cache on the client.

使用 sharecache 选项在客户端上安装 NFS。

此选项确定在同时安装同一导出不止一次时如何共享客户端的数据缓存和属性缓存。 使用相同的缓存可以减少客户端的内存需求,并在通过不同的挂载点访问相同的远程文件时向应用程序呈现相同的文件内容。


设置不带缓存的 NFS 挂载

Disable attribute caching.

使用 noac 选项在客户端上安装 NFS 共享。

Alternately, disable cached directory attributes from being served.

使用 acdirmin=0,acdirmax=0 将缓存超时设置为 0(有效地禁用缓存)。


设置 NFS 挂载以忽略查找缓存

Use lookupcache=positive OR lookupcache=none

(可用选项:allpositivenone

尝试通过 NFS 安装访问目录条目时,
如果服务器上存在请求的目录条目,则结果称为 positive.
如果请求的目录条目在服务器上不存在,则结果称为 negative

如果未指定 lookupcache 选项,或者指定了 all,则客户端假定两种类型的目录缓存条目均有效,直到其父目录的缓存属性过期。

如果指定了 pospositive,则客户端假定正项在其父目录的缓存属性过期之前有效,但总是在应用程序可以使用它们之前重新验证负项。

如果指定了 none,客户端会在应用程序使用它们之前重新验证这两种类型的目录缓存条目。这允许快速检测由其他客户端创建或删除的文件,但会影响应用程序和服务器性能。


参考文献:
1. Close-To-Open Cache Consistency in the Linux NFS Client
2. NFS - Detecting remotely created files programmatically?
3. NFS cache : file content not updated on client when modified on server
4. NFS man page。特别是 "Data And Metadata Coherence" 部分。