CentOS/RHEL 7 中systemd-tmpfiles是如何清理 /tmp/ 或者 /var/tmp 临时文件的

在 CentOS/RHEL 7 中,tmpfiles 通过删除未使用的文件来清理 /tmp 或者 /var/tmp。
这个函数在 CentOS/RHEL 6 中被称为“tmpwatch”,由 crond 调用,但现在在 CentOS/RHEL 7 上由 systemd 的定时器实现。

目前tmpfiles的详细功能在配置文件中有描述:

/usr/lib/systemd/system/systemd-tmpfiles-clean.timer
/usr/lib/systemd/system/systemd-tmpfiles-clean.service
/usr/lib/tmpfiles.d/tmp.conf

简而言之,可用的功能是:

  • 删除 /tmp 中的文件/目录未访问超过 10 天(在 tmp.conf 中定义)
  • 删除 /var/tmp 中的文件/目录未访问超过 30 天(在 tmp.conf 中定义)
  • 有几个文件不会被删除(在 tmp.conf 中定义)
  • 删除命令是“/usr/bin/systemd-tmpfiles -clean”(在 systemd-tmpfiles-clean.service 中定义)

“未访问”是通过检查文件/目录的所有 atime /mtime /ctime 来决定的。
因此,即使 /tmp/ 中文件的 atime/mtime/ctime 之一比 10 天新,该文件也不会被删除。
如果 /tmp/ 中的文件/目录没有被 tmpfiles 删除,即使它看起来已经超过 10 天,可以通过手动运行带有调试选项的命令来检查原因,如下所示:

# SYSTEMD_LOG_TARGET=console SYSTEMD_LOG_LEVEL=debug /usr/bin/systemd-tmpfiles --clean

例如,下面打算将目录“/tmp/latest”由于其时间而无法删除。

# SYSTEMD_LOG_TARGET=console SYSTEMD_LOG_LEVEL=debug /usr/bin/systemd-tmpfiles --clean 2>&1 | grep latest
Directory "/tmp/latest": access time Wed 2017-12-06 16:56:28.771577 IST is too new
www. On IT Road .com

配置文件示例

以下是具有默认设置的 3 个示例配置文件(未编辑)。

# cat /usr/lib/systemd/system/systemd-tmpfiles-clean.timer
[Unit]
Description=Daily Cleanup of Temporary Directories
Documentation=man:tmpfiles.d(5) man:systemd-tmpfiles(8)
[Timer]
OnBootSec=15min
OnUnitActiveSec=1d
# cat /usr/lib/tmpfiles.d/tmp.conf
# Clear tmp directories separately, to make them easier to override
v /tmp 1777 root root 10d
v /var/tmp 1777 root root 30d
# Exclude namespace mountpoints created with PrivateTmp=yes
x /tmp/systemd-private-%b-*
X /tmp/systemd-private-%b-*/tmp
x /var/tmp/systemd-private-%b-*
X /var/tmp/systemd-private-%b-*/tmp
# cat /usr/lib/systemd/system/systemd-tmpfiles-clean.service
[Unit]
Description=Cleanup of Temporary Directories
Documentation=man:tmpfiles.d(5) man:systemd-tmpfiles(8)
DefaultDependencies=no
Conflicts=shutdown.target
After=systemd-readahead-collect.service systemd-readahead-replay.service local-fs.target time-sync.target
Before=shutdown.target
[Service]
Type=oneshot
ExecStart=/usr/bin/systemd-tmpfiles --clean
IOSchedulingClass=idle
日期:2020-09-17 00:12:51 来源:oir作者:oir