The backup check that says fresh because it could not read the directory
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
A backup checker I wrote printed this, on a backup target that no longer existed in any readable sense: ok | last newest entry 0.0 h old chmod 000 on that directory. os.listdir raised PermissionError for the user the check runs as. And the report said the newest backup was written just now, with no hedge of any kind, along with eleven other green lines and the summary All backup targets are fresh. The directory was, at that moment, the only thing the check had actually looked at.
我编写的一个备份检查程序在某个已无法读取的备份目标上输出了以下内容:ok | last newest entry 0.0 h old。该目录的权限被设置为 000,导致 os.listdir 对运行检查的用户抛出了 PermissionError。然而,报告却称最新的备份刚刚写入,没有任何保留意见,并伴随着另外十一条绿色的行,总结显示“所有备份目标均为最新”。在那一刻,该目录实际上是检查程序唯一查看过的对象。
The eight lines responsible: newest = None for root, dirs, files in os.walk(path, onerror=lambda _e: None): for name in files: try: m = os.stat(os.path.join(root, name)).st_mtime except OSError: continue # every file unreadable -> skip if newest is None or m > newest: newest = m if newest is None: newest = os.stat(path).st_mtime # <- the fallback that lies return (time.time() - newest) / 3600.0
导致问题的八行代码如下: newest = None for root, dirs, files in os.walk(path, onerror=lambda _e: None): for name in files: try: m = os.stat(os.path.join(root, name)).st_mtime except OSError: continue # 每个文件都不可读 -> 跳过 if newest is None or m > newest: newest = m if newest is None: newest = os.stat(path).st_mtime # <- 撒谎的后备方案 return (time.time() - newest) / 3600.0
Two lines carry the bug. The onerror handler is the first: os.walk ignores scandir errors by default, so onerror=lambda _e: None is a no-op wearing the costume of error handling. It looks like somebody thought about failure. Nothing is signaled either way — a walk over an unreadable directory yields nothing, exactly like a walk over an empty one. The fallback is the second: when the walk found no files, the code asks the directory for its own mtime and treats that as the age of the newest artifact. That fallback is not a reasonable guess. It answers a different question, and it answers it with a number that is always plausible.
有两个地方存在缺陷。首先是 onerror 处理程序:os.walk 默认会忽略 scandir 错误,因此 onerror=lambda _e: None 只是一个披着错误处理外衣的空操作。看起来有人考虑过失败的情况,但实际上没有任何信号被发出——遍历一个不可读的目录和遍历一个空目录的结果完全一样,什么也得不到。第二个缺陷是后备方案:当遍历没有发现文件时,代码会询问目录自身的 mtime,并将其视为最新工件的存活时间。这种后备方案并非合理的猜测。它回答了一个完全不同的问题,并且给出的数字总是看起来很合理。
What the permission bits actually gate: I reproduced it on a plain Linux box today, dropping to nobody before measuring, because as root every case below just works and proves nothing: stat(execonly dir) [0111] ok stat(execonly/db.dump) [0111] ok listdir(execonly) [0111] PermissionError stat(noperm dir) [0000] ok stat(noperm/db.dump) [0000] PermissionError listdir(noperm) [0000] PermissionError os.walk(noperm) files: default=0 onerror=lambda:None=0
权限位实际控制的内容:我今天在一台普通的 Linux 机器上重现了这个问题,在测量前切换到了 nobody 用户,因为以 root 身份运行以下所有情况都会成功,从而无法证明任何问题: stat(execonly dir) [0111] ok stat(execonly/db.dump) [0111] ok listdir(execonly) [0111] PermissionError stat(noperm dir) [0000] ok stat(noperm/db.dump) [0000] PermissionError listdir(noperm) [0000] PermissionError os.walk(noperm) files: default=0 onerror=lambda:None=0
Read it in order, because the four lines tell the whole story: os.stat on a directory needs execute permission on its parent and nothing else. Mode 0000 on the directory itself does not stop it. os.stat on a file inside a directory needs execute on that directory — you can stat a known name through an execute-only parent, and 0111 is enough. os.listdir needs the read bit. That is the one operation that fails. os.walk swallows it either way, so “unreadable” and “empty” arrive at the caller as the same value: zero files. So the fallback was guaranteed to succeed precisely in the case it was written for — the case where the walk had nothing to report. The failure mode is not “the code crashed on an edge case”. The code takes the branch that cannot fail, and produces a fresh timestamp from a directory it could not open.
请按顺序阅读,因为这四行说明了全部事实:对目录执行 os.stat 只需要其父目录的执行权限,除此之外别无他求。目录本身的 0000 模式并不会阻止该操作。对目录内的文件执行 os.stat 需要该目录的执行权限——你可以通过一个仅有执行权限的父目录来 stat 一个已知名称的文件,0111 权限就足够了。os.listdir 需要读取权限,这是唯一会失败的操作。os.walk 无论如何都会吞掉这个错误,因此“不可读”和“空”在调用者看来是同一个值:零个文件。所以,该后备方案恰好在它被编写的目的场景下——即遍历没有报告任何内容时——保证会成功。这种失败模式并非“代码在边界情况下崩溃”,而是代码进入了不会失败的分支,并从一个它根本无法打开的目录中生成了一个“最新”的时间戳。
A directory’s mtime is not a backup timestamp. Even with a readable directory, the fallback is answering the wrong question. Measured on the same box: after create file dir mtime moved; after rewrite content dir mtime unchanged, file mtime moved; after rename dir mtime moved. A directory’s mtime tracks changes to its entry list — create, unlink, rename. It does not move when a file’s contents are rewritten in place. Which is the normal shape of nightly backups: pg_dump —file /backup/db.dump overwrites the same name every night, rsync into a fixed target, tar czf onto the same path. In that workload the directory mtime is the date the target was created, not the date of the last successful write.
目录的 mtime 并不是备份时间戳。即使目录可读,该后备方案回答的也是错误的问题。在同一台机器上测量发现:创建文件后目录 mtime 改变;重写内容后目录 mtime 不变,文件 mtime 改变;重命名后目录 mtime 改变。目录的 mtime 跟踪的是其条目列表的变化——创建、删除、重命名。当文件内容被原地重写时,它不会改变。而这正是夜间备份的常态:pg_dump —file /backup/db.dump 每晚覆盖同一个文件名,rsync 到固定目标,tar czf 到同一路径。在这种工作负载下,目录的 mtime 是目标创建的日期,而不是最后一次成功写入的日期。
Three of the four cases I measured were wrong, and they were wrong in opposite directions — all from the same branch: Case | Reported | Truth directory unreadable, mtime recent | ok, 0.0 h | unknown — a green nobody earned directory readable but empty | ok, 0.0 h | no backup exists directory unreadable, mtime 240 h old | STALE, 240 h | unknown — a red that skipped the investigation
我测量的四种情况中有三种是错误的,而且它们以相反的方向出错——全部来自同一个分支: 情况 | 报告结果 | 事实 目录不可读,mtime 最近 | ok, 0.0 h | 未知 — 一个不该出现的绿色 目录可读但为空 | ok, 0.0 h | 无备份存在 目录不可读,mtime 240 小时前 | STALE, 240 h | 未知 — 一个跳过调查的红色
The third row is the one that gets missed. A false red costs an argument with the on-call engineer, who will usually be right, and after the second argument the check gets muted — which is why a checker that lies in both directions ends up trusted in neither.
第三行的情况最容易被忽略。一次错误的红色警报会导致与值班工程师的争论,而工程师通常是对的。在第二次争论之后,检查程序就会被静音——这就是为什么一个在两个方向上都撒谎的检查程序最终谁也不会信任它。
Three answers, not one. The fix is not a better fallback. It is refusing to compress three states into one:
cannot read directory -> CRIT “cannot read
三个答案,而不是一个。修复方法不是寻找更好的后备方案,而是拒绝将三种状态压缩为一种:
无法读取目录 -> CRIT “cannot read
The test that holds it in place is three directories and one assertion per state, run as a non-root user: mkdir -p /tmp/vc/{fresh,empty,locked} touch /tmp/vc/fresh/db.dump chmod 000 /tmp/vc/locked su nobody -s /bin/sh -c ‘your-check /tmp/vc/fresh /tmp/vc/empty /tmp/vc/locked’ /tmp/vc/locked must exit non-zero with an error naming the errno, not a freshness verdict. /tmp/vc/empty must exit non-zero saying nothing was found. /tmp/vc/fresh must be ok, and only that one. If your checker runs as root in a container, run that last command as nobody or your test proves nothing at all — root ignores every permission bit you set. That mistake costs more audits than it should, including one of mine.
确保其正确性的测试是针对每种状态设置三个目录并进行一次断言,以非 root 用户身份运行: mkdir -p /tmp/vc/{fresh,empty,locked} touch /tmp/vc/fresh/db.dump chmod 000 /tmp/vc/locked su nobody -s /bin/sh -c ‘your-check /tmp/vc/fresh /tmp/vc/empty /tmp/vc/locked’ /tmp/vc/locked 必须以非零状态退出,并报错指出错误号,而不是给出新鲜度结论。/tmp/vc/empty 必须以非零状态退出,并说明未找到任何内容。/tmp/vc/fresh 必须为 ok,且仅有这一个为 ok。如果你的检查程序在容器中以 root 身份运行,请务必以 nobody 用户运行最后一条命令,否则你的测试将毫无意义——root 会忽略你设置的所有权限位。这个错误导致的审计成本比应有的要高,其中也包括我的一次。
What this is not: It is not a story about a typo. Every line was written by someone trying to avoid a crash, and the result was a checker whose green light meant “I have no idea” in three different situations. A monitoring system earns its keep on the day something breaks, and the only thing that breaks it irreparably is a green tick that was never earned — because the tick is what stops the human from walking over to look. That specific check is what I sell now, and the reason the tool exists is that this exact path exists in a lot of home-grown backup scripts: https://vaultche
这不是什么:这不是一个关于拼写错误的故事。每一行代码都是某人为了避免崩溃而编写的,结果却产生了一个在三种不同情况下,绿灯都意味着“我不知道”的检查程序。监控系统的价值体现在系统崩溃的那一天,而唯一能使其彻底失效的,就是那个从未赢得的绿色勾选——因为正是这个勾选阻止了人类走过去查看真相。我目前销售的正是这种特定的检查工具,而该工具存在的原因是,许多自制的备份脚本中都存在这条完全相同的路径:https://vaultche