Managing Temporary Files RHEL

Managing Temporary Files RHEL

A modern systems requires a large amount of temporary files. Usually these files are located under /run /tmp directories. Before version 7, system administrators used tool tmpwatch to clean /tmp directory and relied on System V scripts that were shipped with daemons.

In RHEL/Centos 7 there is a new functionality provided by systemd. This method called: systemc-tmpfiles. With this method, we can easily create and remove temporary files under /run /tmp just with creating special configuration files.

Each configuration file shall be named in the style of package.conf or package-part.conf. The second variant should be used when it is desirable to make it easy to override just this part of configuration. Files in /etc/tmpfiles.d override files with the same name in /usr/lib/tmpfiles.d and /run/tmpfiles.d. Files in /run/tmpfiles.d override files with the same name in /usr/lib/tmpfiles.d. Packages should install their configuration files in /usr/lib/tmpfiles.d. Files in /etc/tmpfiles.d are reserved for the local administrator, who may use this logic to override the configuration files installed by vendor packages.

Regular Cleanning

Main configuration file:

[root@knesenko-centos7 ~]# cat /usr/lib/systemd/system/systemd-tmpfiles-clean.timer 
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

[Unit]
Description=Daily Cleanup of Temporary Directories
Documentation=man:tmpfiles.d(5) man:systemd-tmpfiles(8)

[Timer]
OnBootSec=15min
OnUnitActiveSec=1d

This indicates that the service will be started 15 minutes after systemd has started and will be executed each 24 hours after.

Example:

[root@knesenko-centos7 ~]# cat /etc/tmpfiles.d/kiril.conf 
d /tmp/kiril 0755 knesenko knesenko 30s 
[root@knesenko-centos7 ~]# systemd-tmpfiles --create kiril.conf
[root@knesenko-centos7 ~]# ls -l /tmp/kiril/
total 0
[root@knesenko-centos7 ~]# touch /tmp/kiril/test && sleep 30
[root@knesenko-centos7 ~]# systemd-tmpfiles --clean kiril.conf
[root@knesenko-centos7 ~]# ls -l /tmp/kiril/
total 0
[root@knesenko-centos7 ~]#

In this example you can see I created configuration file for /tmp/kiril directory. And files under this directory should be purged if their atime,mtime,ctime > 30s.