Difference between revisions of "Systemd/User"

From ArchWiki
Jump to: navigation, search
m (+link to the french wiki page)
(Basic setup)
Line 37: Line 37:
  
 
{{Note|Since systemd 206, the mechanism for systemd user instances has changed. Now the {{ic|pam_systemd.so}} module launches a user instance by default. There is no need to launch it manually. {{ic|user-session@.service}} from {{AUR|user-session-units}} is obsolete now. With this change {{ic|systemd --user}} runs outside of a user session, with the consequences this entails.}}
 
{{Note|Since systemd 206, the mechanism for systemd user instances has changed. Now the {{ic|pam_systemd.so}} module launches a user instance by default. There is no need to launch it manually. {{ic|user-session@.service}} from {{AUR|user-session-units}} is obsolete now. With this change {{ic|systemd --user}} runs outside of a user session, with the consequences this entails.}}
 +
 +
{{Note|Ensure that XDG_RUNTIME_DIR environment variable is set, else you may get ''Failed to get D-Bus connection: No such file or directory'' when running systemctl --user }}
  
 
=== D-Bus ===
 
=== D-Bus ===

Revision as of 00:04, 6 August 2014

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements.Tango-edit-clear.png

Reason: Explain from the basic to the specialized, not the other way around (Discuss in Talk:Systemd/User#)
systemd offers users the ability to manage services under the user's control with a per-user systemd instance, enabling users to start, stop, enable, and disable their own units. This is convenient for daemons and other services that are commonly run for a single user, such as mpd, or to perform automated tasks like fetching mail. With some caveats it is even possible to run xorg and the entire window manager from user services.

How it works

On the first login of an user, systemd automatically launches a systemd --user instance, responsible to manage user services. This process will survive as long as there is some session for that user, and will be killed as soon as the last session for the user is closed. By default no user services are run. user services can be used to run daemons or automated tasks, with all the benefits of systemd, like socket activation, timers, dependency system, strict process control via cgroups...

User's units are located in the following directories just as they would with system services (ordered by ascending precedence):

  • /usr/lib/systemd/user/ where services provided by installed packages go.
  • /etc/systemd/user/ where system-wide user services are placed by the system administrator.
  • ~/.config/systemd/user/ where the user puts its own services.

When systemd user instance starts, it brings up the target default.target. After that systemd's user instance can be controlled manually with systemctl --user.

Warning: Be aware that the systemd --user instance is a per-user process, and not per-session. The rationale is that most resources handled by user services, like sockets or state files will be per-user (live on the user's home dir) and not per session. This means that all user services run outside of a session. As a consequence, programs that need to be run inside a session will probably break in user services. The way systemd handles user sessions is pretty much in flow. See [1] and [2] for some hints on where things are going.

Basic setup

Systemd user instance should be started automatically on first login. To check that it is already running you can use systemctl --user status.

Note: If systemd user instance is not started automatically check the file /etc/pam.d/system-login. It should contain a line similar to -session optional pam_systemd.so. Also check if a .pacnew file exists.

All the user services will be placed in ~/.config/systemd/user. If you want to run services on first login, create a directory default.target.wants, and symlink any unit you want to be autostarted in there. This adds them as a Want dependency for the default.target.

Note: Since systemd 206, the mechanism for systemd user instances has changed. Now the pam_systemd.so module launches a user instance by default. There is no need to launch it manually. user-session@.service from user-session-unitsAUR is obsolete now. With this change systemd --user runs outside of a user session, with the consequences this entails.
Note: Ensure that XDG_RUNTIME_DIR environment variable is set, else you may get Failed to get D-Bus connection: No such file or directory when running systemctl --user

D-Bus

Some programs, including systemd itself, will need a dbus user message bus. Traditionally this is started when launching a desktop environment via dbus-launch. However if you are going to use the systemd user instance, it is very desirable to run the dbus server as a systemd service.

Note: With the upcoming transition of systemd to kdbus, systemd will become the manager of system and user message buses anyway.

To set this up, you need to:

1. Add a service and socket units for the dbus server in /etc/systemd/user/

/etc/systemd/user/dbus.socket
[Unit]
Description=D-Bus Message Bus Socket
Before=sockets.target

[Socket]
ListenStream=%t/dbus/user_bus_socket

[Install]
WantedBy=default.target
/etc/systemd/user/dbus.service
[Unit]
Description=D-Bus Message Bus
Requires=dbus.socket

[Service]
ExecStart=/usr/bin/dbus-daemon --session --address=systemd: --nofork --nopidfile --systemd-activation
ExecReload=/usr/bin/dbus-send --print-reply --session --type=method_call --dest=org.freedesktop.DBus / org.freedesktop.DBus.ReloadConfig

2. The environment variable DBUS_SESSION_BUS_ADDRESS must be set. It can be done using a drop-in config file for user@.service, by creating the following file:

/etc/systemd/system/user@.service.d/dbus.conf
[Service]
Environment=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/%I/dbus/user_bus_socket
Note: Before systemd 209 DBUS_SESSION_BUS_ADDRESS was set in upstream's user@.service unit, but not anymore. The reason seems to be that once the transition to kdbus is done, this variable will be set by pam_systemd.so.

3. Activate the socket for all users by running as root:

# systemctl --global enable dbus.socket

Environment variables

The user instance of systemd does not inherit any of the environment variables set in places like .bashrc, etc. There are two ways te set environment variables for the systemd instance:

1. Add a drop-in config file in /etc/systemd/system/user@.service.d as it was done for D-Bus. This makes the variable available for the entire lifetime of the systemd user instance.

2. At any time, use systemctl --user set-environment or systemctl --user import-environment. All units started after that command will get the updated environment variables, but not the units that were already running.

Some variables you probably may want to set are DISPLAY or PATH.

DISPLAY

Display is used by any X application to know which display to use. If you plan on launching X applications from systemd units, you need to set this variable, using the following drop-in config:

/etc/systemd/system/user@.service.d/display.conf
[Service]
Environment=DISPLAY=:0

This hard-codes DISPLAY to :0 which is the usual choice when running a single X server.

Note: It is better to set DISPLAY using a drop-in config file since this way it is available from the beginning. If DISPLAY is set later, dbus.service will most probably not get it, and right now (until kdbus arrives) the dbus-daemon is responsible for launching dbus activated services, and those would never see the DISPLAY variable.

PATH

As any other environment variable you set in .bashrc or .bash_profile, the PATH variable is not available to systemd. If you customize your PATH and plan on launching applications that make use of it from systemd units, you should make sure the modified PATH is set on the systemd environment. Assuming you set your PATH in .bash_profile, the best way to make systemd aware of your modified PATH is by adding the following to .bash_profile after the PATH variable is set:

~/.bash_profile
systemctl --user import-environment PATH

Other variables

If you need other environment variables to be accessible from systemd services, you can set them from .bashrc or .bash_profile, or even a systemd service, using any of the following commands:

$ systemctl --user set-environment VARIABLE=value   # Set VARIABLE to value
$ systemctl --user import-environment VARIABLE      # Import VARIABLE from the calling environment
$ systemctl --user import-environment               # Import all variables from the calling environment

Automatic start-up of systemd user instances

The systemd user instance is started after the first login of a user and killed after the last session of the user is closed. Sometimes it may be useful to start it right after boot, and keep the systemd user instance running after the last session closes, for instance to have some user process running without any open session. Lingering is used to that effect.

Warning: systemd services are not sessions, they run outside of logind. Do not use lingering to enable automatic login as it will break the session.

Use the following command to enable lingering for specific user:

# loginctl enable-linger username

Xorg and systemd

There are several ways to run xorg within systemd units. Below there are two options, either by starting a new user session with an xorg process, or by launching xorg from a systemd user service.

Automatic login into Xorg without display manager

Tango-inaccurate.pngThe factual accuracy of this article or section is disputed.Tango-inaccurate.png

Reason: This setup ends up with two user D-Bus buses, one for the desktop, and an other for systemd. Why can't we use the systemd one alone? (Discuss in Talk:Systemd/User#)

This option will launch a system unit that will start a user session with an xorg server and then run the usual ~/.xinitrc to launch the window manager, etc.

You need to have #D-Bus correctly set up and xlogin-gitAUR installed.

Set up your xinitrc from the skeleton, so that it will source the files in /etc/X11/xinit/xinitrc.d/. Running your ~/.xinitrc should not return, so either have wait as the last command, or add exec to the last command that will be called and which should not return (your window manager, for instance).

The session will use its own dbus daemon, but various systemd utilities need the dbus.service instance. Possible solution to this is to create aliases for such commands:

~/.bashrc
for sd_cmd in systemctl systemd-analyze systemd-run; do
    alias $sd_cmd='DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/dbus/user_bus_socket" '$sd_cmd
done

Finally, enable (as root) the xlogin service for automatic login at boot:

# systemctl enable xlogin@username

The user session lives entirely inside a systemd scope and everything in the user session should work just fine.

Xorg as a systemd user service

Alternatively, xorg can be run from within a systemd user service. This is nice since other X-related units can be made to depend on xorg, etc, but on the other hand, it has some drawbacks explained below.

Since version 1.16 xorg-server provides better integration with systemd in two ways:

Unfortunately, to be able to run xorg in unprivileged mode, it needs to run inside a session. So, right now the handicap of running xorg as user service is that it must be run with root privileges (like before 1.16), and can't take advantage of the unprivileged mode introduced in 1.16.

Note: This is not a fundamental restriction imposed by logind, but the reason seems to be that xorg needs to know which session to take over, and right now it gets this information calling logind's GetSessionByPID using its own pid as argument. See this thread and xorg sources. It seems likely that xorg could be modified to get the session from the tty it is attaching to, and then it could run unprivileged from a user service outside a session.

This is how to launch xorg from a user service:

1. Make xorg run with root privileges and for any user, by editing /etc/X11/Xwrapper.config

/etc/X11/Xwrapper.config
allowed_users=anybody
needs_root_rights=yes

2. Add the following units to ~/.config/systemd/user

~/.config/systemd/user/xorg@.socket
[Unit]
Description=Socket for xorg at display %i

[Socket]
ListenStream=/tmp/.X11-unix/X%i
~/.config/systemd/user/xorg@.service
[Unit]
Description=Xorg server at display %i

Requires=xorg@%i.socket
After=xorg@%i.socket

[Service]
Type=simple
SuccessExitStatus=0 1

ExecStart=/usr/bin/Xorg :%i -nolisten tcp -noreset -verbose 2 "vt${XDG_VTNR}"

where ${XDG_VTNR} is the virtual terminal where xorg will be launched, either hard-coded in the service unit, or set in the systemd environment with

$ systemctl --user set-environment XDG_VTNR=1
Note: xorg should be launched at the same virtual terminal where the user logged in. Otherwise logind will consider the session inactive.

3. Make sure to configure the DISPLAY environment variable as explained above.

4. Then, to enable socket activation for xorg on display 0 and tty 2 one would do:

$ systemctl --user set-environment XDG_VTNR=2     # So that xorg@.service knows which vt use
$ systemctl --user start xorg@0.socket            # Start listening on the socket for display 0

Now running any X application will launch xorg on virtual terminal 2 automatically.

The environment variable XDG_VTNR can be set in the systemd environment from .bash_profile, and then one could start any X application, including a window manager, as a systemd unit that depends on xorg@0.socket.

Warning: Currently running a window manager as a user service means it runs outside of a session with the problems this may bring: break the session. However, it seems that systemd developers intend to make something like this possible. See [3] and [4]

Writing user units

Example

The following is an example of a user version of the mpd service.

~/.config/systemd/user/mpd.service
[Unit]
Description=Music Player Daemon

[Service]
ExecStart=/usr/bin/mpd --no-daemon

[Install]
WantedBy=default.target

Example with variables

The following is an example of a user version of sickbeard.service, which takes into account variable home directories where SickBeard can find certain files:

~/.config/systemd/user/sickbeard.service
[Unit]
Description=SickBeard Daemon

[Service]
ExecStart=/usr/bin/env python2 /opt/sickbeard/SickBeard.py --config %h/.sickbeard/config.ini --datadir %h/.sickbeard

[Install]
WantedBy=default.target

As detailed in man systemd.unit, the %h variable is replaced by the home directory of the user running the service. There are other variables that can be taken into account in the systemd manpages.

Note about X applications

Most X apps need a DISPLAY variable to run (so it's likely the first reason why your service files aren't starting). See #DISPLAY for how to set this variable for the entire systemd user instance. Alternatively, you could set this variable for a single unit as follows:

~/.config/systemd/user/parcellite.service
[Unit]
Description=Parcellite clipboard manager

[Service]
ExecStart=/usr/bin/parcellite
Environment=DISPLAY=:0

[Install]
WantedBy=mystuff.target

Some use cases

Persistent terminal multiplexer

Tango-view-refresh-red.pngThis article or section is out of date.Tango-view-refresh-red.png

Reason: References user-session@.service instead of user@.service; the latter does not contain Conflicts=getty@tty1.service. (Discuss in Talk:Systemd/User#)

You may wish your user session to default to running a terminal multiplexer, such as GNU Screen or Tmux, in the background rather than logging you into a window manager session. Separating login from X login is most likely only useful for those who boot to a TTY instead of to a display manager (in which case you can simply bundle everything you start in with myStuff.target).

To create this type of user session, procede as above, but instead of creating wm.target, create multiplexer.target:

[Unit]
Description=Terminal multiplexer
Documentation=info:screen man:screen(1) man:tmux(1)
After=cruft.target
Wants=cruft.target

[Install]
Alias=default.target

cruft.target, like mystuff.target above, should start anything you think should run before tmux or screen starts (or which you want started at boot regardless of timing), such as a GnuPG daemon session.

You then need to create a service for your multiplexer session. Here is a sample service, using tmux as an example and sourcing a gpg-agent session which wrote its information to /tmp/gpg-agent-info. This sample session, when you start X, will also be able to run X programs, since DISPLAY is set.

[Unit]
Description=tmux: A terminal multiplixer Documentation=man:tmux(1)
After=gpg-agent.service
Wants=gpg-agent.service

[Service]
Type=forking
ExecStart=/usr/bin/tmux start
ExecStop=/usr/bin/tmux kill-server
Environment=DISPLAY=:0
EnvironmentFile=/tmp/gpg-agent-info

[Install]
WantedBy=multiplexer.target

Once this is done, systemctl --user enable tmux.service, multiplexer.target and any services you created to be run by cruft.target and you should be set to go! Activated user-session@.service as described above, but be sure to remove the Conflicts=getty@tty1.service from user-session@.service, since your user session will not be taking over a TTY. Congratulations! You have a running terminal multiplexer and some other useful programs ready to start at boot!

Window manager

To run a window manager as a systemd service, you first need to run #Xorg as a systemd user service. In the following we will use awesome as an example:

~/.config/systemd/user/awesome.service
[Unit]
Description=Awesome window manager
After=xorg.target
Requires=xorg.target

[Service]
ExecStart=/usr/bin/awesome
Restart=always
RestartSec=10
 
[Install]
WantedBy=wm.target
Note: The [Install] section includes a WantedBy part. When using systemctl --user enable it will link this as ~/.config/systemd/user/wm.target.wants/window_manager.service, allowing it to be started at login. Is recommended to enable this service, not to link it manually.

See also