Systemd/ru

systemd — это современная замена SysV-подобных init и rc (run command) для Linux-систем. Она поддерживается Gentoo в качестве альтернативной системы инициализации.

Ядро
systemd позволяет использовать многие современные возможности ядра Linux. На данный момент минимальная требуемая версия ядра — 2.6.39. В свежих версиях поддерживается удобный способ включения обязательных и опциональных параметров ядра:

При конфигурации ядра вручную (единственный способ, если вы не используете ) необходимо или рекомендуется включить следующие опции:

Для UEFI систем, активируйте следующие:

Для систем, использующих планировщик BFQ, рекомендуется включить опцию "BFQ hierarchical scheduling support", находящуюся в блоке "Enable the block layer -> IO Schedulers".

Наиболее актуальный список необходимых опций можно найти в разделе "REQUIREMENTS" файла README.

Директория
Директория используется systemd и другими приложениями как временное хранилище для таких данных, как -файлы, сокеты и файлы состояния.

systemd создаст директорию самостоятельно. Однако обратите внимание, что это изменение также инициализирует автоматическое монтирование директории в OpenRC и может спровоцировать использование этой директории различными программными.

Последние версии поддерживают файл только в качестве символьной ссылки на. Отсутствие этой ссылки также может вызвать проблемы, связанные с  и. Раньше некоторые утилиты записывали информацию (вроде опций монтирования) в, и потому предполагалось, что он является обычным файлом; сейчас программное обеспечение не должно иметь проблем, связанных с этим. Последнее: прежде чем сделать символьной ссылкой, взгляните на, чтобы иметь уверенность, что система не подвержена ни одной из описанных проблем.

Чтобы создать символьную ссылку, запустите:

Убедитесь, что /usr доступен во время загрузки
Если расположен на отдельном разделе, используйте initramfs для монтирования  до запуска systemd. Смотрите Руководство по Initramfs в Gentoo.

Использование LVM2 и initramfs
Если система загружена с использованием initramfs, и используется sys-fs/lvm2, initramfs должна быть создана с использованием. Для этого запустите:

— это  или любой другой genkernel target, реализующий создание initramfs. Чтобы получить дополнительную информацию, смотрите :

При использовании LVM должен быть запущен демон. В противном случае systemd не сможет монтировать LVM-разделы. может быть активирован в :

Установка
содержит udev. После установки systemd, пакет может быть удалён, так как systemd разрешает зависимость.

Активируйте USE-флаг  глобально (в файле ). USE-флаг  должен быть отключен, чтобы избежать конфликтов с сервисом. Также можно переключиться на субпрофиль systemd, чтобы использовать стандартный набор флагов (в этом случае отпадает необходимость ручной правки ):

Обновите систему с новыми флагами:

Причиной проблем с зависимостями (например, блокирует ), может быть то, что  зарегистрирован в файле world. Попытка решить эту проблему, отменив его:

Загрузка с systemd
Чтобы загрузиться с systemd, измените, который запускает ядро (или initramfs).

Следующие подсекции показывают, как переключить в некоторых загрузчиках или непосредственно в ядре.

Grub Legacy (0.x)
Необходимо добавить агрумент  в командную строку ядра. Соответствующий отрывок будет выглядеть примерно так:

Если система всё-таки загружается с OpenRC, попробуйте использовать  вместо.

Grub 2
При использовании добавьте опцию init в GRUB_CMDLINE_LINUX :

Если конфигурационный файл GRUB 2 написан вручную (только для опытных пользователей), добавьте параметр  для команды   или.

При использовании initrd, который сгенерирован genkernel-next, используйте  вместо.

В конфигурации ядра
Конфигурация init также может быть жёстко сконфигурирована в ядре. Смотрите. Обратите внимание, что это работает и для, и для.

Установка пароля root
В этом пункте не забудьте установить пароль root. Если что-то пойдет не так, systemd запросит пароль root для входа в режим технического обслуживания.

Настройка после установки
systemd поддерживает несколько конфигурационных файлов для настройки базовых параметров системы.

Имя хоста
To set the hostname, create/edit and simply provide the desired hostname.

When booted using systemd, a tool called exists for editing  and. To change the hostname, run:

Проверьте, если необходима информация о других опциях.

Локаль
Usually, locales will be properly migrated from OpenRC when installing systemd. When required, the locale can be set in as per the Gentoo handbook instructions:

Once booted with systemd, the tool is used to set locale and console or X11 keymaps. To change the system locale, run the following command:

To change the virtual console keymap:

And finally, to set the X11 layout:

If needed the model, variant and options can be specified as well:

Дата и время
Time and date can be set using the utility. That will also allow users to set up synchronization without needing to rely on or other providers than systemd's own implementation.

To learn how to use simply run:

Автоматическая загрузка модулей
Automatic module loading is configured in a different file, or rather directory of files. The configuration files are stored in. On boot every file with a list of modules will be loaded. The file format is a list of modules separated by newlines and can have any name as long as it ends with. The module loading can be separated by program, service or whatever way that fits personal preference. An example is listed below:

systemd-networkd
systemd-networkd is useful for simple configuration of wired network interfaces. It is disabled by default.

To configure systemd-networkd, create a file under. See systemd.network(5) for reference. A simple DHCP configuration is given below:

Note that systemd-networkd does not update by default. To have systemd manage the DNS settings, replace with a symlink and start systemd-resolved.

NetworkManager
Often NetworkManager is used to configure network settings. For that purpose, simply run the following command when using an X11-powered desktop:

If that is not the case and the network needs to be configured from console, give nmcli a try, or follow a guided configuration process through :

nmtui is a curses frontend that will guide the user in the process while running in console mode.

Handling of log files
systemd has its own way of handling log files without needing to rely on any external log system (like or ). Messages can now be read with. It can still be configured to use a preferred external tool for handling them. See to learn how to configure journald to suit personal needs.

Some common options:

For more information and many more options, look at.

/tmp is now in tmpfs
Unless some other filesystem is explicitly mounted to in, systemd will mount  as tmpfs. That means it will be emptied on every boot and its size will be limited to 50% of the system's RAM size. To know why this is the desired behavior and how to modify it, take a look at API File Systems.

Configure verbosity of boot process
When migrating to systemd users usually notice differences regarding verbosity of boot process:


 * The boot option  not only influences the kernel output, but also that of systemd itself. Then, while setting up systemd for the machine, drop the option to see any errors could arise more easily. After that, add it back to get a quiet (and faster) boot.
 * Even passing the  boot option, systemd can still be configured to show its status by also passing.
 * When not using the  boot option, some messages might be overwriting consoles. That is caused by the kernel configuration (see  and look for ). To tweak it pass the   boot parameter to the kernel (and update the value according to preference, for instance set a lower value like 1).

Сервисы
At some point the system will need to be rebooted in order to get systemd running (in system mode). Be sure to read all of this document to ensure systemd is configured as completely as possible before rebooting. Note that works with systemd not running, but that  will not do anything useful without systemd running. Complete the service configuration (enabling and starting of services) after logging in to the system running systemd.

Сервисы OpenRC
Although systemd originally intended to support running old init.d scripts, that support is not suited well for a dependency-based RC like OpenRC and thus is completely disabled on Gentoo. OpenRC provides additional measures to ensure that init.d scripts can't be run when OpenRC was not used to boot the system (otherwise the results would be unpredictable).

Просмотр доступных сервисов
All available service units can be listed using the  argument of :

The following file suffixes are of interest:

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

And finally check for services that failed to start:

Enabling, disabling, starting, and stopping services
The usual way of enabling a service is using the following command:

Services can be disabled likewise:

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 system to be started on a next boot; to start the service right now, use:

Services can be stopped likewise:

Installing custom unit files
Custom unit files can be placed in, where they will be recognized after running :

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. Overriding settings in a package management provided unit can be achieved by drop-in files in a directory named after the original unit (e.g. ) in.

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

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

Verify that the changed property was applied to the service:

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. The name of the directory can either specify a target or another service which will depend on the new one.

For example, to install as  in the :

To disable the service, just remove the symlink:

Нативные сервисы
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:

Сервисы таймеров
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:

Firstly, tell systemd to rescan the service files:

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

Start and stop the timer manually as follows:

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

To check the last results of running the service:

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:

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

Замена cron
The above timer and service files can also be added to to make them available system-wide. The install section should then say  to enable the service at system start.

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

Устранение проблем

 * Upstream debugging guide
 * Upstream debugging guide
 * Upstream debugging guide

Graphical sessions opened in random places
By default systemd only launches a 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 to  and graphical sessions using the remaining TTYs) force it to always launch  on those:

lvm
When switching from OpenRC to systemd and lvm is needed to properly mount the system volumes, activate the lvm 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
As systemd-bootchart attempts to start, reconfigure it to invoke systemd instead:

The result of the bootchart is a report in SVG format located in.

syslog-ng conflicts with systemd
systemd creates as datagram socket  so syslog-ng needs to be told to read from a unix-dgram instead of a unix-stream as otherwise syslog-ng would be using a "wrong" stream:

Настройка sys-fs/cryptsetup
systemd does not seem to respect (see ) so it needs to be configured through the  file:

You may need to create a new service file from your file. To do this, enable the  USE flag for. It will install. Executing it will create a service file in, which you can now copy to , adjust manually and add to the desired runlevel.

Check for units that failed to start
Check for units that failed to start with:

Разрешение режима отладки
To get more informations set the following in :

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

Использование e4rat
Please remember to edit setting 'init' to, otherwise it will keep booting OpenRC.

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

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

Смотрите также

 * Comparison of init systems - An article comparing and contrasting the differences in Gentoo init systems.
 * Sakaki's EFI Install Guide - Particularly look at the chapter entitled Configuring systemd and installing necessary tools
 * OpenRC to Systemd Cheatsheet

Внешние источники

 * FAQ
 * Tips and tricks