Tmpfiles.d
Vista general
tmpfiles.d es un servicio para gestionar archivos temporales y directorios de tiempo de ejecución para demonios. En esta guía nos centramos principalmente en cómo se utiliza para rellenar /run y /run/lock. Dado que /run es un sistema de archivos tmpfs, tanto este como su contenido deben recrearse en cada reinicio. Para los archivos que se van a crear allí, esto no debería suponer ningún problema. Sin embargo, a menudo será necesario crear los directorios con antelación. La mejor forma de hacerlo es utilizando el mecanismo tmpfiles.d.
Configuración de tmpfiles.d
Para solicitarle al mecanismo tmpfiles.d que cree directorios, simplemente inserte un archivo en %{_tmpfilesdir}. Necesitará una dependencia de compilación en systemd-rpm-macros para usar esta macro.
Por ejemplo, si el paquete necesita crear algunos directorios en /run para ejecutarse, el empaquetador debe crear un archivo llamado %{name}.conf que se instala como %{_tmpfilesdir}/%{name}.conf. El archivo tiene una o más líneas con el siguiente formato:
d /run/NOMBRE POR GRUPO DE USUARIO -
El formato de la línea es como sigue:
-
despecifica que se creará un directorio si no existe. Puede usar un especificador de tipo diferente si lo necesita. Consulteman tmpfiles.dpara ver los posibles valores. -
/run/NOMBREes la ruta del sistema de archivo a crear. -
PERMson los permisos (en formato octal de 4 dígitos) a aplicar al directorio cuando se crea. -
USERis the name of the owner of the directory. -
GROUPis the name of the group of the directory. -
-specifies that aging should not be applied to the contents of the directory. Aging is a mechanism for automated cleanup of files that were not used for a specified length of time. This is mostly useful for directories such as /tmp and is seldom used by packages. Feel free to use aging if it is appropriate for your directory.
An example:
d /run/mysqld 0755 mysql mysql -
Information on other options is available on the tmpfiles.d man page should you need to do something more advanced.
Ejemplo del archivo spec
In the spec file, the packager needs to install the tmpfiles.d conf file into the %{_tmpfilesdir} directory and also make sure the directory is included in the rpm.
# For the _tmpfilesdir macro.
BuildRequires: systemd-rpm-macros
# tmpfiles.d configuration for the /run directory
Source1: %{name}-tmpfiles.conf
[...]
%install
mkdir -p %{buildroot}%{_tmpfilesdir}
install -m 0644 %{SOURCE1} %{buildroot}%{_tmpfilesdir}/%{name}.conf
# This may not be needed if the upstream's install script creates the directories
# Make sure permissions are correct
install -d -m 0755 %{buildroot}/run/%{name}/
# A bit contrived as most packages will either create a subdirectory or a single file. Not both
# Make sure permissions are correct
touch %{buildroot}/run/%{name}.pid
chmod 0644 %{buildroot}/run/%{name}.pid
[...]
%files
# Use %attr() if needed to change ownership of these two items
%dir /run/%{name}/
%verify(not size mtime md5) /run/%{name}.pid
%{_tmpfilesdir}/%{name}.conf
%{_tmpfilesdir} expands to %{_prefix}/lib/tmpfiles.d which is the location that the package’s default tmpfile creation scripts should install into. %{_tmpfilesdir}/%{name}.conf is not marked as a %config file because it is not supposed to be edited by administrators. Administrators can override the package’s %{name}.conf by placing an identically named file in /etc/tmpfiles.d/, but this should very rarely be needed.
Files (not directories) that the program places directly into /run are listed in the %files section as %verify(not size mtime md5) so that rpm knows the file must exist as part of this package but will not complain when the file contents change. Files placed in the subdirectories may be listed the same way or omitted entirely as the files will be cleaned up on every reboot.
Why not create the directories with XXXXXX instead?
There are multiple ways to try creating the directories but most suffer some disadvantage that tmpfiles.d addresses:
Have the daemon create the directory when it starts up
Many times, daemons run as an unprivileged user who would not be allowed to create new directories directly into /run. If the daemon does not drop privileges, then you can patch it to create the files and directories when the daemon starts and submit the patch upstream.
Tener el script init para crear el directorio cunado arranca el demonio
Dado que el script de inicio lo ejecuta el root, antes de que el demonio pierda los privilegios, ¿por qué no crear los directorios allí?
-
Este código debería implementarse en cada script de inicio empaquetado. Usando tmpfiles.d podemos reducir la cantidad de lugares donde debemos colocar código como este.
-
Añadir mkdir a los archivos de unidad de systemd cuando tmpfiles.d ya está instalado implica ejecutar código de shell para ese script de inicio. Systemd ya no puede gestionar el inicio del demonio por sí mismo, lo que ralentiza el proceso. El código de shell también introduce construcciones imperativas en la estructura, que normalmente sería declarativa, lo cual conviene evitar.
-
El etiquetado apropiado de los directorios creados lo realiza automáticamente por el mecanismo tmpfiles.d, pero debería realizarse manualmente mediante el script init.
Want to help? Learn how to contribute to Fedora Docs ›