Ubuntu – Upstart job cannot create directory in /var/run

permissionsupstart

I the following config in /etc/init/foo.conf on Ubuntu 12.04.4:

description "Foo"

start on filesystem or runlevel [2345]
stop on runlevel [!2345]

pre-start script
    mkdir -p -m 0775 /var/run/foo
    chown foo:foo /var/run/foo
end script

setuid foo
setgid foo
exec /usr/local/bin/foo

However when this is run at boot, and when I attempt to run it manually with sudo start foo I get the following error in /var/log/upstart/foo.log:

mkdir: cannot create directory `/var/run/foo': Permission denied

Why is this occurring and how can I fix it?

Best Answer

As Upstart cookbook mentions: Note that all processes (pre-start, post-stop, et cetera) will be run as the user specified.

As a result mkdir outside user's home directory will fail with permission denied results.

One solution is to create as root the directory, chown it for the target user and then run the executable as the user.

description "Foo"

start on filesystem or runlevel [2345]
stop on runlevel [!2345]

pre-start script
    mkdir -p -m 0775 /var/run/foo
    chown foo:foo /var/run/foo
end script

exec sudo -u foo_user /usr/local/bin/foo

where foo_user is the target user which will initiate the executable

Reference on how to run as different user

Related Question