Systemd

From Gentoo Wiki
Jump to: navigation, search
This page is a translated version of the page Systemd and the translation is 5% complete.

Outdated translations are marked like this.
Other languages:
English • ‎español • ‎italiano • ‎português do Brasil • ‎русский • ‎中文(中国大陆)‎ • ‎日本語 • ‎한국어

Warning: Display title "systemd/pt-br" overrides earlier display title "Systemd".

systemd is a modern SysV-style init and rc replacement for Linux systems. It is supported in Gentoo as an alternative init system.

Installation

Note
If updating from <=sys-apps/systemd-203 check the upgrade sub-article.

The core around which all distributions are built is the Linux kernel. It is the layer between the user programs and the system hardware. Gentoo provides its users several possible kernel sources. A full listing with description is available at the Kernel overview page.

For amd64-based systems, Gentoo recommends the sys-kernel/gentoo-sources package.

Choose an appropriate kernel source and install it using emerge:

root #emerge --ask sys-kernel/gentoo-sources

Kernel

systemd utiliza vários recursos das versões mais novas do Kernel Linux. No momento, a menor versão do kernel para utilizar o systemd é 2.6.39. Em versões mais recentes do pacote sys-kernel/gentoo-sources, existe uma forma conveniente para definir as configurações do kernel para utilização do systemd (veja Kernel/Configuration para mais detalhes):

KERNEL Configuração rápida utilizando gentoo-sources
Gentoo Linux --->
  Support for init systems, system and service managers --->
    [*] systemd
</pre>

Para configurar essas opções manualmente (que é a unica solução quando não estiver utilizando sys-kernel/gentoo-sources), as seguintes configurações do kernel são necessarias e recomendadas:

KERNEL Configurações obrigatórias
'"`UNIQ--pre-00000003-QINU`"'

The following file suffixes are of interest:

Suffix Description
.service Plain service files (e.g. ones just running a daemon directly).
.socket Socket listeners (much like inetd).
.path Filesystem triggers for services (running services when files change, etc.).

Alternatively the systemctl tool can be used to list all services (including implicit ones):

root #systemctl --all --full

And finally check for services that failed to start:

root #systemctl --failed

Enabling, disabling, starting, and stopping services

The usual way of enabling a service is using the following command:

root #systemctl enable foo.service

Services can be disabled likewise:

root #systemctl disable foo.service

These commands enable services using their default name in default target (both specified in "Install" section of the service file). However, sometimes services either don't provide that information or users prefer to have another name/target.

Note that these commands only enable or disable the service to be started on a next boot; to start the service right now, use:

root #systemctl start foo.service

Services can be stopped likewise:

root #systemctl stop foo.service

Installing custom unit files

Custom unit files can be placed in /etc/systemd/system, where they will be recognized after running systemctl daemon-reload:

root #systemctl daemon-reload

/lib/systemd/system is reserved for service files installed by the package manager.

Customizing unit files

When only minor changes to a unit are needed, there's no need to create a full copy of the original unit file in /etc/systemd/system. Overriding settings in a package management provided unit can be achieved by drop-in files in a

  • .d directory named after the original unit (e.g. apache2.d) in /etc/systemd/system/.
FILE /etc/systemd/system/apache2.d/mem-limit.confExample of adding/overriding settings in a service file
[Service]
MemoryLimit=1G

A reload of systemd is needed to inform it of the changes:

root #systemctl daemon-reload

Then the service needs to be restarted to apply the changes:

root #systemctl restart apache2

Verify that the changed property was applied to the service:

root #systemctl show --property=MemoryLimit apache2
MemoryLimit=1074000000

Enabling a service under a custom name

When the name provided by "Alias" in the unit's "[Install]" section does not meet the expectations and providing a permanent new value for this through a customization is not desired, a symlink can be created manually in /etc/systemd/system/*.wants/. The name of the

  • .wants directory can either specify a target or another service which will depend on the new one.

For example, to install mysqld.service as db.service in the multi-user.target:

root #ln -s /lib/systemd/system/mysqld.service /etc/systemd/system/multi-user.target.wants/db.service

To disable the service, just remove the symlink:

root #unlink /etc/systemd/system/multi-user.target.wants/db.service

Native services

Some of Gentoo packages already install systemd unit files. For these services, it is enough to enable them. A quick summary of packages installing unit files can be seen on systemd eclass users list.

The following table lists systemd services matching OpenRC ones:

Service migration chart
Gentoo package OpenRC service systemd unit Notes
sys-apps/openrc bootmisc systemd-tmpfiles-setup.service always enabled, uses tmpfiles.d
consolefont systemd-vconsole-setup.service always enabled, uses vconsole.conf
devfs
dmesg
fsck fsck*.service pulled in implicitly by mounts
functions.sh See note bug #373219
hostname (builtin) /etc/hostname
hwclock See note always enabled as part of systemd (i.e. it is baked in and it is not a unit)
keymaps systemd-vconsole-setup.service always enabled, uses vconsole.conf
killprocs
local
localmount local-fs.target actual units are created implicitly from /etc/fstab
modules systemd-modules-load.service always enabled, uses /etc/modules-load.d/*.conf
mount-ro
mtab
netmount remote-fs.target
numlock
procfs (builtin)
root remount-rootfs.service
savecache n/a OpenRC internals
staticroute
swap swap.target actual units are created implicitly from /etc/fstab
swclock
sysctl systemd-sysctl.service sysctl.conf and sysctl.d/
sysfs (builtin)
termencoding systemd-vconsole-setup.service always enabled, uses vconsole.conf
urandom systemd-random-seed-load.service
systemd-random-seed-save.service
app-admin/rsyslog rsyslog rsyslog.service
app-admin/syslog-ng syslog-ng syslog-ng.service
media-sound/alsa-utils alsasound alsa-store.service (enabled by default)
alsa-restore.socket (enabled by default)
net-misc/dhcpcd dhcpcd dhcpcd.service
net-misc/netifrc net.* net@.service systemd wrapper for net.* scripts (comes with net-misc/netifrc)
netctl@.service net-misc/netctl is originally an Arch Linux tool.
NetworkManager.service For <networkmanager-0.9.8.4 : enable NetworkManager-dispatcher.service for dispatcher.d scripts to work.
Enable NetworkManager-wait-online.service to detect that the system has a working internet connection.
Disable all other managers (e.g., wicd, dhcpcd) and wpa_supplicant.
dhcpcd.service Provided by net-misc/dhcpcd
systemd.networkd.service Part of systemd
net-misc/openntpd ntpd ntpd.service
net-misc/openssh sshd sshd.service runs sshd as a daemon
sshd.socket runs sshd on a inetd-like basis (for each incoming connection)
net-wireless/wpa_supplicant wpa-supplicant wpa_supplicant.service D-Bus controlled daemon (e.g. for NetworkManager)
wpa_supplicant@.service interface-specific wpa_supplicant (used like wpa_supplicant@wlan0.service)
net-print/cups cupsd cups.service classic on-boot start up service
cups.socket socket and path activation (cups only started on-demand)
cups.path
net-wireless/bluez bluetooth bluetooth.service
sys-apps/dbus dbus dbus.service
dbus.socket
sys-apps/irqbalance irqbalance irqbalance.service supports daemon mode only
sys-apps/microcode-ctl microcode_ctl Configure microcode as a module to let it load the microcode itself. Go to "Processor type and features" -> "CPU microcode loading support" and remember to add the right option based on the system having an intel or amd processor.
sys-fs/udev udev udev.service
udev-mount (builtin) /dev is mounted as tmpfs
udev-postmount udev-trigger.service
udev-settle.service
sys-power/acpid acpid acpid.service Most of its functionality is done by systemd itself, so consider disabling this
x11-apps/xdm (xdm) xdm.service OpenRC uses common xdm init.d installed by x11-base/xorg-server. With systemd the corresponding unit file for each DM (gdm.service, kdm.service...) needs to be enabled.
net-firewall/iptables iptables iptables-store.service
iptables-restore.service

Timer services

Since version 197 systemd supports timers, making cron unnecessary on a systemd system. Since version 212 persistent services are supported, replacing even anacron. Persistent timers are run at the next opportunity if the system was powered down when the timer was scheduled.

The following is an example on how to make a simple timer that runs in the context of a user. It will even run if the user is not logged in. Every timed service needs a timer and a service file that is activated by the timer as follows:

FILE ~/.local/share/systemd/user/backup-work.timerExample of a timer running every working day
[Unit]
Description=daily backup work
RefuseManualStart=no
RefuseManualStop=no
 
[Timer]
Persistent=false
OnCalendar=Mon-Fri *-*-* 11:30:00
Unit=backup-work.service
 
[Install]
WantedBy=default.target
FILE ~/.local/share/systemd/user/backup-work.serviceExample of a service triggering backup
[Unit]
Description=daily backup work
RefuseManualStart=no
RefuseManualStop=yes
 
[Service]
Type=oneshot
ExecStart=/home/<user>/scripts/backup-work.sh

Firstly, tell systemd to rescan the service files:

user $systemctl --user daemon-reload

It is possible to trigger the backup manually by running the following command:

user $systemctl --user start backup-work.service

Start and stop the timer manually as follows:

user $systemctl --user start backup-work.timer
user $systemctl --user stop backup-work.timer

Finally, to activate the timer at every system start, run:

user $systemctl --user enable backup-work.timer

To check the last results of running the service:

user $systemctl --user list-timers

Emailing failures

If a timed service runs and fails an e-mail can be send out to inform the user or administrator. This is possible with the "OnFailure" stanza which specifies what should happen if a service fails. A failure is detected by a non-zero return code of the invoked script.

For that change the script as follows:

FILE ~/.local/share/systemd/user/backup-work.serviceExample of a service triggering backup
[Unit]
Description=daily backup work
RefuseManualStart=no
RefuseManualStop=yes
OnFailure=failure-email@%i.service
 
[Service]
Type=oneshot
ExecStart=/home/<user>/scripts/backup-work.sh

This requires to have the service failure-email@.service installed, which can be found in kylemanna's systemd-utils repository.

Replacing cron

The above timer and service files can also be added to /lib/systemd/system to make them available system-wide. The install section should then say WantedBy=multi-user.target to enable the service at system start.

However, cron also runs the scripts in /etc/cron.daily and other locations. Several packages place scripts there that they expect to be run daily. This behavior can be emulated with systemd by installing sys-process/systemd-cron. Then activate the new cron replacement with the following commands:

root #systemctl enable cron.target
root #systemctl start cron.target

Troubleshooting

/dev/kmsg buffer overrun, some messages lost

Problem
When booting the system displays an infinite loop of /dev/kmsg buffer overrun, some messages lost. The login screen to console never appears since the system never gets to that point in the boot process.
Solution
Most of the time this issue is caused when the CONFIG_POWER_SUPPLY_DEBUG option is enabled in the kernel. The current workaround is to disable this option in the kernel, then recompile, install, and boot the new kernel. The solution can also be found in this thread on the Gentoo forums. According to one user one the forum, this issue was also seen when using I2C EEPROM on an embedded system[1]. The solution in this case was to disable the CONFIG_I2C_DEBUG_CORE kernel option.

Graphical sessions opened in random places

By default systemd only launches a getty process when it's going to be used. This causes some display managers (like GDM) to use the remaining TTYs for opening graphical sessions on demand, which can result in having consoles and graphical sessions placed randomly depending on the order they were used.

To stick with a more "classical" behavior (i.e, consoles placed from tty1 to tty6 and graphical sessions using the remaining TTYs) force it to always launch getty on those:

root #systemctl enable getty@tty{2,3,4,5,6}.service

LVM

When switching from OpenRC to systemd and LVM is needed to properly mount the system volumes, activate the LVM service:

root #systemctl enable lvm2-monitor.service

While it might not be needed for activation of the root volume (if LVM is integrated into the initramfs) it might not work for other LVM volumes, unless the service is activated.

systemd-bootchart

Make sure that CONFIG_DEBUG_KERNEL, CONFIG_SCHED_DEBUG, and CONFIG_SCHEDSTATS are enabled.

KERNEL Enable systemd-bootchart support
'"`UNIQ--pre-00000010-QINU`"'

Next, enable systemd-bootchart.service:

root #systemctl enable systemd-bootchart

The result of the changes will produce a bootchart report in SVG format located in /run/log/ after each boot. It can be viewed using a modern web browser.

As an alternative to systemd-bootchart the starting of services can be visualized with:

root #systemd-analyze plot > plot.svg

syslog-ng source for systemd

There is no need to add unix-dgram('/dev/log'); to the /etc/syslog-ng/syslog-ng.conf config file. It will cause syslog-ng to fail (at least on version syslog-ng-3.7.2). Update the source src { ...; }; line mentioned in the syslog-ng article as follows:

FILE /etc/syslog-ng/syslog-ng.conf
# default config for openrc
#source src { system(); internal(); };
 
# systemd
source src { systemd-journal(); internal(); };

sys-fs/cryptsetup configuration

systemd does not seem to respect /etc/conf.d/dmcrypt (see bug #429966) so it needs to be configured through the /etc/crypttab file:

FILE /etc/crypttabConfiguration file for encrypted block devices
crypt-home UUID=c25dd0f3-ecdd-420e-99a8-0ff2eaf3f391 -

Make sure to enable the cryptsetup USE flag for sys-apps/systemd. It will install /lib/systemd/system-generators/systemd-cryptsetup-generator that will automatically create a service (cryptsetup@crypt-home.service for above example) for each entry on boot.

Check for units that failed to start

Check for units that failed to start with:

root #systemctl --failed

Enable debug mode

To get more informations set the following in /etc/systemd/system.conf:

FILE /etc/systemd/system.conf
LogLevel=debug

Or enable the debug-shell, that opens a terminal at tty9. This helps to debug services during the boot process.

root #systemctl enable debug-shell.service

e4rat usage

Please remember to edit /etc/e4rat.conf setting 'init' to /lib/systemd/systemd, otherwise it will keep booting OpenRC.

GRSecurity hardening

With grsecurity enabled, systemd-networkd might log the following error:

CODE systemd-networkd error
could not find udev device: Permission denied

The error raises due to systemd-networkd working under a non-root user with grsecurity refusing access to the complete /sys structure for such users. To disable this option, disable the CONFIG_GRKERNSEC_SYSFS_RESTRICT kernel option.

logind may also have subtle permission issues with CONFIG_GRKERNSEC_PROC active, see bug #472098.

shutdown -rF does not force fsck

The systemd-fsck service is responsible of running fsck when needed. It doesn't honor shutdown's -rF option, but instead honors the following kernel boot parameters.

Boot parameter Supported options Description
fsck.mode auto
force
skip
Controls the mode of operation. The default is auto, and ensures that file system checks are done when the file system checker deems them necessary. force unconditionally results in full file system checks. skip skips any file system checks.
fsck.repair preen
yes
no
Controls the mode of operation. The default is preen, and will automatically repair problems that can be safely fixed. yes will answer yes to all questions by fsck and no will answer no to all questions.

See also

External resources

References