Difference between revisions of "Systemd"

From ArchWiki
Jump to: navigation, search
m (The _Arch package_ polkit hasn't been updated since May 13, so I don't know where this information is coming from)
m (Readahead)
Line 571: Line 571:
 
systemd comes with its own readahead implementation, this should in principle improve boot time. However, depending on your kernel version and the type of your hard drive, your mileage may vary (i.e. it might be slower). To enable, do:
 
systemd comes with its own readahead implementation, this should in principle improve boot time. However, depending on your kernel version and the type of your hard drive, your mileage may vary (i.e. it might be slower). To enable, do:
  
{{bc|<nowiki># systemctl enable systemd-readahead-collect.service
+
{{bc|<nowiki># systemctl enable systemd-readahead-collect.service systemd-readahead-replay.service</nowiki>}}
# systemctl enable systemd-readahead-replay.service</nowiki>}}
+
  
 
Remember that in order for the readahead to work its magic, you should reboot a couple of times.
 
Remember that in order for the readahead to work its magic, you should reboot a couple of times.

Revision as of 10:13, 9 July 2012

Summary help replacing me
systemd is a system and service manager for Linux, compatible with SysV and LSB init scripts. systemd provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, offers on-demand starting of daemons, keeps track of processes using Linux cgroups, supports snapshotting and restoring of the system state, maintains mount and automount points and implements an elaborate transactional dependency-based service control logic. It can work as a drop-in replacement for sysvinit.
Related
Systemd/Services

See Lennart's blog story for a longer introduction, the two status updates since then, and the most recent summary. Also see the Wikipedia article and the project web page.

Installation

To try out systemd on Arch you need to:

  • install systemd (and its dependencies) from [core]
  • add init=/bin/systemd to your kernel cmdline in your bootloader

systemd can be installed side-by-side with the regular Arch Linux initscripts, and they can be toggled by adding/removing the init=/bin/systemd kernel parameter. If you want a pure systemd setup you can remove initscripts and install systemd-sysvcompat which provides symlinks for init, reboot etc. You will then not have to specify the init= parameter on your kernel cmdline.

To take advantage of the systemd way of starting services, you might also want to install the systemd-arch-units package.

Warning: udev and many other pieces of software expect /usr to be mounted and available at bootup. If your /usr is on a separate partition, you will need to make accommodations to mount it from the initramfs and unmount it from a pivoted root on shutdown. See the mkinitcpio wiki page and freedesktop.org#separate-usr-is-broken
Note: systemd will not automatically start all services from your old rc.conf/DAEMONS array. For example the Cron daemon will not be started automatically. You need to register it with systemd:
systemctl enable cronie.service #when using cronie, which is the default in Arch

Native systemd configuration files

systemd will use /etc/rc.conf if these files are absent.

Note: You may need to create these files.

Hostname

/etc/hostname
myhostname

Console and keymap

The /etc/vconsole.conf file configures the virtual console, i.e. keyboard mapping and console font.

/etc/vconsole.conf
KEYMAP=us
FONT=lat9w-16
FONT_MAP=8859-1_to_uni

Locale

Read man locale.conf for more options

/etc/locale.conf
LANG=en_US.UTF-8
LC_COLLATE=C

Timezone

Read man 5 timezone for more options

/etc/timezone
Europe/Minsk
Note: This file does not obviate the need for /etc/localtime.

Hardware clock time

Systemd will use UTC for the hardware clock by default and this is recommended. Dealing with daylight saving time is messy. If the DST changes when your computer is off, your clock will be wrong on next boot (there is a lot more to it). Recent kernels set the system time from the RTC directly on boot without using hwclock, the kernel will always assume that the RTC is in UTC. This means that if the RTC is in local time, the the system time will first be set up wrongly and then corrected shortly afterwards on every boot. This is possibly the reason for certain weird bugs (time going backwards is rarely a good thing).

The reason for allowing the RTC to be in local time is to allow dual boot with Windows (who uses localtime). Windows is able to deal with the RTC being in UTC by setting the following DWORD registry key to 1:

HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation\RealTimeIsUniversal
Warning: On recent systems (Windows 7, Vista SP2) this setting prevents Windows from being able to update the system clock at all, and earlier versions do not work correctly when resuming from suspend or hibernate. In addition, recent systems may become unresponsive during Daylight Saving Time (DST) changeover if RealTimeIsUniversal is set.

If you run into issues on dual boot with Windows, you can set the hardware clock to local time. Contrary to popular belief, systemd supports this:

/etc/adjtime
 
0.0 0.0 0.0
0
LOCAL
Note: The other parameters are still needed but are ignored by systemd.
Note: It is generally advised to have a Network Time Protocol daemon running to keep the hardware clock synchronized with the system time.

Kernel modules loaded during boot

systemd uses /etc/modules-load.d/ to configure kernel modules to load during boot in a static list. Each configuration file is named in the style of /etc/modules-load.d/<program>.conf. The configuration files should simply contain a list of kernel module names to load, separated by newlines. Empty lines and lines whose first non-whitespace character is # or ; are ignored. Example:

/etc/modules-load.d/virtio-net.conf
# Load virtio-net.ko at boot
virtio-net

See also Modprobe#Options

Kernel modules blacklist

Module blacklisting works the same way as with initscripts since it is actually handled by kmod, see Module Blacklisting for details.

Temporary files

Systemd-tmpfiles uses the configuration files in /etc/tmpfiles.d/ to describe the creation, cleaning and removal of volatile and temporary files and directories which usually reside in directories such as /run or /tmp. Each configuration file is named in the style of /etc/tmpfiles.d/<program>.conf. This will also override any files in /usr/lib/tmpfiles.d/ with the same name.

tmpfiles are usually provided together with service files to create directories which are expected to exist by certain daemons. For example the Samba daemon expects the directory /var/run/samba to exist and to have the correct permissions. The corresponding tmpfile looks like this:

/usr/lib/tmpfiles.d/samba.conf
D /var/run/samba 0755 root root

However, tmpfiles may also be used to write values into certain files on boot. For example, if you use /etc/rc.local to disable wakeup from USB devices with echo USBE > /proc/acpi/wakeup, you may use the following tmpfile instead:

/etc/tmpfiles.d/disable-usb-wake.conf
w /proc/acpi/wakeup - - - - USBE

The tmpfiles method is recommended in this case since systemd doesn't actually support /etc/rc.local.

See man tmpfiles.d for details.

Remote filesystem mounts

If you have NFS mounts listed in /etc/fstab then systemd will attempt to mount them but will typically do so too early (before networking has been configured). To get the timing correct we need to tell systemd explicitly that the mount depends on networking and rpc.statd. To do this, create the following file:

/etc/systemd/system/<mount-unit-name>.mount
 [Unit]
 Description=<mountpoint>
 Wants=rpc-statd.service
 After=network.target rpc-statd.service 
 
 [Mount]
 What=<server>:<share>
 Where=<mountpoint>
 Type=nfs

In the above:

  • mount-unit-name is the full path to the mountpoint in an escaped format. For example, a mount unit for /usr/local must be named usr-local.mount.
  • mountpoint is the local mountpoint
  • server:share specifies the remote filesystem in the same manner as for /etc/fstab

See systemd.unit(5) and systemd.mount(5) for further details.

A similar approach will probably be required for other remote filesystem types such as nfs4 and cifs.

Alternatively, you can mark these entries in /etc/fstab with the x-systemd.automount and x-systemd.device-timeout=# options (see systemd.mount(5)). Make sure that if you also include defaults as a mount option, that you override the implicit auto with noauto. This will cause the device to be mounted on first access, similar to Autofs.

Systemd commands

  • systemctl: used to introspect and control the state of the systemd system and service manager.
  • systemd-cgls: recursively shows the contents of the selected Linux control group hierarchy in a tree
  • systemadm: a graphical frontend for the systemd system and service manager that allows introspection and control of systemd (avaiable via the systemd-ui-gitAUR package from the AUR).

View the man pages for more details.

Tip: You can use all of the following systemctl commands with the -H <user>@<host> switch to control a systemd instance on a remote machine. This will use SSH to connect to the remote systemd instance.

Analyzing the system state

List running units:

$ systemctl

or:

$ systemctl list-units

List failed units:

$ systemctl --failed

The available unit files can be seen in /usr/lib/systemd/system/ and /etc/systemd/system/ (the latter takes precedence).

Using Units

Units can be services (.service), mount points (.mount) or sockets (.sockets). When using systemctl, you always have to specify the complete name of the unit file, including its suffix, for example netcfg.service. See man systemd.unit for details.

Activate a unit immediately:

# systemctl start <unit>

Deactivate a unit immediately:

# systemctl stop <unit>

Restart a unit:

# systemctl restart <unit>

Ask a unit to reload its configuration:

# systemctl reload <unit>

Show the status of a unit, including whether it is running or not:

$ systemctl status <unit>

Check whether a unit is already enabled or not:

$ systemctl is-enabled <unit>

Enable a unit to be started on bootup:

# systemctl enable <unit>

Disable a unit to not start during bootup:

# systemctl disable <unit>

Power Management

If you are in a local user session and no other session is active, the following commands will work without root privileges. If not, systemd will automatically ask you for the root password.

Shut down and reboot the system:

$ systemctl reboot

Shut down and power-off the system:

$ systemctl poweroff

Shut down and halt the system:

$ systemctl halt

Suspend the system:

$ systemctl suspend

Hibernate the system:

$ systemctl hibernate

Runlevels/targets

Runlevels is a legacy concept in systemd. Systemd uses targets which serve a similar purpose as runlevels but act a little different. Each target is named instead of numbered and is intended to serve a specific purpose with the possibility of having multiple ones active at the same time. Some targets are implemented by inheriting all of the services of another target and adding additional services to it. There are systemd targets that mimic the common SystemVinit runlevels so you can still switch targets using the familiar telinit RUNLEVEL command.

Get current runlevel/targets

The following should be used under systemd instead of runlevel:

# systemctl list-units --type=target

Create custom target

The runlevels that are assigned a specific purpose on vanilla Fedora installs; 0, 1, 3, 5, and 6; have a 1:1 mapping with a specific systemd target. Unfortunately, there is no good way to do the same for the user-defined runlevels like 2 and 4. If you make use of those it is suggested that you make a new named systemd target as /etc/systemd/system/<your target> that takes one of the existing runlevels as a base (you can look at /usr/lib/systemd/system/graphical.target as an example), make a directory /etc/systemd/system/<your target>.wants, and then symlink the additional services from /usr/lib/systemd/system/ that you wish to enable.

Targets table

SysV Runlevel Systemd Target Notes
0 runlevel0.target, poweroff.target Halt the system.
1, s, single runlevel1.target, rescue.target Single user mode.
2, 4 runlevel2.target, runlevel4.target, multi-user.target User-defined/Site-specific runlevels. By default, identical to 3.
3 runlevel3.target, multi-user.target Multi-user, non-graphical. Users can usually login via multiple consoles or via the network.
5 runlevel5.target, graphical.target Multi-user, graphical. Usually has all the services of runlevel 3 plus a graphical login.
6 runlevel6.target, reboot.target Reboot
emergency emergency.target Emergency shell

Change current runlevels

In systemd runlevels are exposed via "target units". You can change them like this:

# systemctl isolate graphical.target

This will only change the current runlevel, and has no effect on the next boot.

Change default runlevel/target to boot into

The standard target is default.target, which is aliased by default to graphical.target (which roughly corresponds to the old runlevel 5). To change the default target at boot-time, append one of the following kernel parameters to your bootloader:

  • systemd.unit=multi-user.target (which roughly corresponds to the old runlevel 3),
  • systemd.unit=rescue.target (which roughly corresponds to the old runlevel 1).

Alternatively, you may leave the bootloader alone and change default.target. This can be done using systemctl:

# systemctl enable multi-user.target

The effect of this command is outputted by systemctl; a symlink to the new default target is made at /etc/systemd/system/default.target. This works if, and only if:

[Install]
Alias=default.target

is in the target's configuration file. Currently, multi-user.target and graphical.target both have it.

Running DEs under systemd

Using display manager

To enable graphical login, run your preferred Display Manager daemon (e.g. KDM). At the moment, service files exist for GDM, KDM, SLiM, XDM and LXDM.

# systemctl enable kdm.service

This should work out of the box. If not, you might have a default.target set manually or from a older install:

# ls -l /etc/systemd/system/default.target
/etc/systemd/system/default.target -> /usr/lib/systemd/system/graphical.target

Simply delete the symlink and systemd will use its stock default.target (i.e. graphical.target).

# rm /etc/systemd/system/default.target

If /etc/locale.conf is used for setting the locale, add an entry to /etc/environment:

/etc/environment
LANG=en_US.utf8

Using service file

Note: Using this method there will be no PAM session created for your user. Therefore ConsoleKit (which gives you access to shutdown/reboot, audio devices etc.) will not work properly. For the recommended way, see: Automatic_login_to_virtual_console#With_systemd.

If you are only looking for a simple way to start X directly without a display manager, you can create a service file similar to this:

/etc/systemd/system/graphical.target.wants/xinit.service
[Unit]
Description=Direct login to X
After=systemd-user-sessions.service

[Service]
ExecStart=/bin/su <username> -l -c "/bin/bash --login -c xinit"

[Install]
WantedBy=graphical.target

Systemd Journal

Since version 38 systemd has an own logging system, the journal.

By default, running a syslog daemon is no longer required. To read the log, use:

# journalctl

The journal writes to /run/systemd/journal, meaning logs will poof on reboot. For non-volatile logs, create /var/log/journal/:

# mkdir /var/log/journal/

journal size limit

If the journal is made non-volatile, its size limit is set to a default value of 10% of the size of the respective file system. E.g. with /var/log/journal located on a 50GiB root partition this would lead to 5GiB of journal data. The maximum size of the persistent journal can be controlled by SystemMaxUse in /etc/systemd/journald.conf, so to limit it for example to 50MiB uncomment and edit the corresponding line to:

SystemMaxUse=50M

Look at man journald.conf for more info.

Journald in conjunction with a classic syslog daemon

Compatibility with classic syslog implementations is provided via a socket /run/systemd/journal/syslog, to which all messages are forwarded. To make the syslog daemon work with the journal, it has to bind to this socket instead of /dev/log (official announcement). For syslog-ng change /etc/syslog-ng/syslog-ng.conf source section to:

source src {
    unix-dgram("/run/systemd/journal/syslog");
    internal();
    file("/proc/kmsg");
};

and enable (or reenable) syslog-ng:

# systemctl enable syslog-ng.service

By default, journald is configured to read from /proc/kmsg, but this will collide with a syslog implementation doing the same (systemd-devel post). Disable reading /proc/kmsg by systemd-journald in /etc/systemd/journald.conf:

ImportKernel=no

Network

Dynamic (DHCP)

If you simply want to use DHCP for your ethernet connection, you can use dhcpcd@.service from the systemd-arch-units package. To enable DHCP for eth0, simply use:

# systemctl start dhcpcd@eth0.service

You can enable the service to automatically start at boot with:

# systemctl enable dhcpcd@.service

Note that this will enable the service for eth0 by default. If you want to use another interface, you have to create the symlink manually, e.g.:

# ln -s '/usr/lib/systemd/system/dhcpcd@.service' '/etc/systemd/system/multi-user.target.wants/dhcpcd@eth1.service'

Other configurations

For static, wireless or advanced network configuration like bridging you can use netcfg or NetworkManager which both provide systemd service files.

If you need a static ethernet configuration, but don't want to use netcfg, there is a custom service file available on the Systemd/Services page.

Arch integration

Integration with Arch's classic configuration is accomplished via the initscripts-systemd package. This is an optional package containing unit files and scripts needed to emulate Arch's initscripts, which can be used to ease the transition from sysVinit to systemd.

/etc/inittab is not used at all.

/etc/rc.local and /etc/rc.local.shutdown can be run at startup and shutdown by enabling rc-local.service and rc-local-shutdown.service.

Warning: Usage of this package is not recommended. In particular, arch-load-modules.service and arch-daemons.target are unsupported as a long-term solution and will be removed in the future. When ever possible, use native systemd configuration files instead.

Most people will not need all (if any) of these units, and they can be easily disabled with:

# systemctl disable <unitfile>

The plan is to remove most of the functionality from this package as soon as it is handled elsewhere (mostly in udev/systemd/kernel).

rc.conf

Some variables in /etc/rc.conf are respected by this glue work. For a pure systemd setup it is recommended to use the native systemd configuration files which will take precedence over /etc/rc.conf.

Supported variables:

  • LOCALE
  • KEYMAP
  • CONSOLEFONT
  • CONSOLEMAP
  • HOSTNAME
  • MODULES
  • DAEMONS: Ordering and blacklisting is respected, if a native systemd service file by the same name as a daemon exists, it will take precedence, this logic can be disabled by systemctl disable arch-daemons.target

Not supported variables and systemd configuration:

  • TIMEZONE: Please symlink /etc/localtime to your zoneinfo file manually.
  • HARDWARECLOCK: See Hardware clock time.
  • USELVM: use lvm.service provided by systemd-arch-units instead.
  • USECOLOR

The following is a brief description of the functionality of each of them. Alternative solutions are provided as a migration plan away from the functionality provided by this package.

rc-local.service / rc-local-shutdown.service

Runs /etc/rc.local (resp., /etc/rc.local.shutdown) on boot (resp., shutdown).

arch-daemons.target

Parses the DAEMONS array in /etc/rc.conf and starts the services. If a native systemd unit exists (by the same name) for a given daemon, this is used; otherwise, the script in /etc/rc.d/ is used to control the unit.

Alternative: use native unit files from the systemd-arch-units package.

arch-modules-load.service

Creates a list of modules to be loaded based on /etc/rc.conf (see /etc/modules-load.d/rc.conf).

Alternative: create a *.conf for your modules in /etc/modules-load.d/.

Helping out

Currently, systemd is mostly at feature parity with Arch's initscripts. However, a lot more testing is needed. If you would like to help out, you can create service files and submit them upstream, or if this fails, directly to the Arch Linux Bugtracker.

FAQ

For an up-to-date list of known issues, look at the upstream TODO.

Template:FAQ

Template:FAQ

Template:FAQ Template:FAQ

Template:FAQ

Template:FAQ

Template:FAQ

Template:FAQ

Optimization

systemd-analyze

Systemd provides a tool called systemd-analyze that allows you to analyze your boot process so you can see which unit files are causing your boot process to slow down. You can then optimize your system accordingly. You have to install python2-dbus to use it.

To see how much time was spent in kernel-/userspace on boot, simply use:

systemd-analyze
Tip: If you add the timestamp hook to your HOOKS array in /etc/mkinitcpio.conf and rebuild your initramfs, systemd-analyze will also be able to show you how much time was spent in the intramfs.

To list the started unit files, sorted by the time each of them took to start up:

systemd-analyze blame

You can also create a SVG file which describes your boot process grapically, similiar to Bootchart:

systemd-analyze plot > plot.svg

Enabling bootchart in conjunction with systemd

You can use a version of bootchart to visualize the boot sequence. Since you are not able to put a second init into the kernel cmdline you won't be able to use any of the standard bootchart setups. However the bootchart2AUR package from AUR comes with an undocumented systemd service. After you've installed bootchart2 do:

# systemctl enable bootchart.service

Read the bootchart documentation for further details on using this version of bootchart.

Replacing acpid with systemd

Systemd can handle some power-related ACPI events. This is configured via the following options in /etc/systemd/logind.conf:

  • HandlePowerKey : Power off the system when the power button is pressed
  • HandleSleepKey : Suspend the system when the sleep key is pressed
  • HandleLidSwitch : Suspend the system when the laptop lid is closed

Depending on the value of these options, these events may for example only be triggered when no user is logged in (no-session) or when only a single user session is active (any-session). See man logind.conf for details.

These options should not be used on desktop environments like Gnome and XFCE since these handle ACPI events by themselves. However, on systems which run no graphical setup or only a simple window manager like i3 or awesome, this may replace the acpid daemon which is usually used to react to these ACPI events.

Shell Shortcuts

Systemd daemon management requires a bit more text entry to accomplish tasks such as start, stopped, enabling, checking status, etc. The following functions can be added one's ~/.bashrc to help streamline interactions with systemd and to improve the overall experience.

if ! systemd-notify --booted; then  # not using systemd
  start() {
    sudo rc.d start $1
  }

  restart() {
    sudo rc.d restart $1
  }

  stop() {
    sudo rc.d stop $1
  }
else
  start() {
    sudo systemctl start $1.service
  }

  restart() {
    sudo systemctl restart $1.service
  }

  stop() {
    sudo systemctl stop $1.service
  }

  enable() {
    sudo systemctl enable $1.service
  }

  status() {
    sudo systemctl status $1.service
  }

  disable() {
    sudo systemctl disable $1.service
  }
fi

Less output

Change verbose to quiet on the kernel line in GRUB. For some systems, particularly those with an SSD, the slow performance of the TTY is actually a bottleneck, and so less output means faster booting.

Early start

One central feature of systemd is dbus and socket activation, this causes services to be started when they are first accessed, and is generally a good thing. However, if you know that a service (like console-kit) will always be started during boot, then the overall boot time might be reduced by starting it as early as possible. This can be achieved (if the service file is set up for it, which in most cases it is) by issuing:

# systemctl enable console-kit-daemon.service

This will cause systemd to start console-kit as soon as possible, without causing races with the socket or dbus activation.

Automount

The default setup will fsck and mount all filesystems before starting most daemons and services. If you have a large /home partition, it might be better to allow services that do not depend on /home to start while /home is being fsck'ed. This can be achieved by adding the following options to the fstab entry of your /home partition:

noauto,x-systemd.automount

This will fsck and mount /home when it is first accessed, and the kernel will buffer all file access to /home until it is ready.

If you have encrypted filesystems with keyfiles, you can also add the noauto parameter to the corresponding entries in /etc/crypttab. systemd will then not open the encrypted device on boot, but instead wait until it is actually accessed and then automatically open it with the specified keyfile before mounting it. This might save a few seconds on boot if you are using an encrypted RAID device for example, because systemd doesn't have to wait for the device to become available. For example:

/etc/crypttab
data /dev/md0 /root/key noauto

Readahead

systemd comes with its own readahead implementation, this should in principle improve boot time. However, depending on your kernel version and the type of your hard drive, your mileage may vary (i.e. it might be slower). To enable, do:

# systemctl enable systemd-readahead-collect.service systemd-readahead-replay.service

Remember that in order for the readahead to work its magic, you should reboot a couple of times.

User sessions

systemd can divide user sessions into cgroups. Add session optional pam_systemd.so to your relevant /etc/pam.d/ files (e.g., login for tty logins, sshd for remote access, kde for password kdm logins, kde-np for automatic kdm logins).

Before:

$ systemd-cgls systemd:/system/getty@.service
systemd:/system/getty@.service:
├ tty5
│ └ 904 /sbin/agetty tty5 38400
├ tty2
│ ├ 13312 /bin/login --
│ └ 15765 -zsh
[…]

After:

$ systemd-cgls systemd:/user/example/
systemd:/user/example/:
├ 4
│ ├   902 /bin/login --
│ └ 16016 -zsh
[…]

Further, you can replace ConsoleKit's functionality with systemd. To do this, polkit needs to be rebuilt from ABS with systemd enabled (--enable-systemd), and stuff like USB automounting will work without consolekit. DBus supports systemd since version 1.6.0, so there's no longer need to build it from Git.

Troubleshooting

Shutdown/Reboot takes terribly long

If the shutdown process takes a very long time (or seems to freeze) most likely a service not exiting is to blame. systemd waits some time for each service to exit before trying to kill it. To find out if you are affected see this article in the fedora wiki.

SLiM and xfce-session

One setup that can produce a shutdown freeze is Xfce in conjunction with SLiM: Shutting down/rebooting using xfce-session will cause slim.service to hang for half a minute until systemd kills it the hard way. One workaround is to create a modified slim.service:

/etc/systemd/system/slim.service
[Unit]
Description=SLiM Simple Login Manager
After=systemd-user-sessions.service

[Service]
Type=forking
PIDFile=/var/lock/slim.lock
ExecStart=/usr/bin/slim -d
ExecStop=/bin/kill -9 $MAINPID
ExecStopPost=/bin/rm /var/lock/slim.lock

[Install]
WantedBy=graphical.target

This causes SLiM to be terminated using SIGKILL. Since the lock file is also removed this does not cause a problem.

See also