Linux – How to setup a systemd service to be started by a non root user as a user daemon

arch linuxrtorrentsystemduser

I just finished the install and setup process of systemd on my arch-linux system (2012.09.07). I uninstalled initscripts (and removed the configuration files).

What I want to do is create a service that can be started and stopped by a non-root user. The service is to start a detached screen session running rtorrent. However I want every user on the system who has set this service to start (enabled) to have a particular instance started for them specifically. How would one go about doing this?

I remember reading that systemd supports user instances of services, however I have been unable to find any information on how to set this up, or whether it relates to what I am looking for.

Service file that I have used for system:

[Unit]
Description=rTorrent

[Service]
Type=forking
ExecStart=/usr/bin/screen -d -m -S rtorrent /usr/bin/rtorrent
ExecStop=/usr/bin/killall -w -s 2 /usr/bin/rtorrent

UPDATE#1:

After reading through the man pages here and here, I understand how systemd works a bit better. Specifically that using the User= and WorkingDirectory= options allow for the service to be started in a user's session. However the issue still remains that the user themselves can not start, stop, enable, or disable the service. An Access is denied error is given by systemctl.

UPDATE#2:

First off, for simplification and for better use of systemd's user session (still somewhat incomplete) feature, I used sofar's user-session-units and followed his config advice.

It seems that there is a bug in the current version of DBus (1.6.4-1) in which it does not set the environment variable DBUS_SESSION_BUS_ADDRESS meaning using the systemctl --user command errors out with:

Failed to get D-Bus connection: Unable to autolaunch a dbus-daemon without a $DISPLAY for X11

The variable should look like this:

DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/USERUID/dbus/user_bus_socket"

where USERUID needs to be the UID of the given user.

Best Answer

systemd normally does not allow ordinary users to start system services. While it does support giving access via polkit, that part is still somewhat lacking, and you cannot yet allow only one specific service.

(Edit: Later systemd versions do support it, but only with polkit v106 or later.)

Since rtorrent is not actually a system service, and because you want every user to have their own instance of rtorrent, experiment with systemd's "user" mode.

When you log in, the system will start a user@<uid>.service system unit for you, which will launch a separate "--user" instance of systemd. The new user-systemd will read unit files (starting with default.target) from ~/.config/systemd/user/, /etc/systemd/user/ and /usr/lib/systemd/user/.

Related Question