Systemd: permission issue with mkdir & ExecStartPre

permissionssystemd

I've got a problem with this (shortened) systemd service file:

[Unit]
Description=control FOO daemon
After=syslog.target network.target

[Service]
Type=forking
User=FOOd
Group=FOO
ExecStartPre=/bin/mkdir -p /var/run/FOOd/
ExecStartPre=/bin/chown -R FOOd:FOO /var/run/FOOd/
ExecStart=/usr/local/bin/FOOd -P /var/run/FOOd/FOOd.pid
PIDFile=/var/run/FOOd/FOOd.pid

[Install]
WantedBy=multi-user.target

Let FOOd be the user name and FOO the group name, which already exist for my daemon /usr/local/bin/FOOd.

I need to create the directory /var/run/FOOd/ before starting the daemon process /usr/local/bin/FOOd via # systemctl start FOOd.service. This fails, because mkdir can't create the directory due to permissions:

...
Jun 03 16:18:49 PC0515546 mkdir[2469]: /bin/mkdir: cannot create directory /var/run/FOOd/: permission denied
Jun 03 16:18:49 PC0515546 systemd[1]: FOOd.service: control  process exited, code=exited status=1
...

Why does mkdir fail at ExecStartPre and how can I fix it? (And no, I can't use sudo for mkdir…)

Best Answer

You need to add

PermissionsStartOnly=true

to [Service]. Your user FOOd is of course not authorized to create a directory in /var/run. To cite the man page:

Takes a boolean argument. If true, the permission-related execution options, as configured with User= and similar options (see systemd.exec(5) for more information), are only applied to the process started with ExecStart=, and not to the various other ExecStartPre=, ExecStartPost=, ExecReload=, ExecStop=, and ExecStopPost= commands. If false, the setting is applied to all configured commands the same way. Defaults to false.