Debian systemd как установить

Обновлено: 02.07.2024

Systemd tasks are organized as units. The most common units are services (.service), mount points (.mount), devices (.device), sockets (.socket), or timers (.timer). For instance, starting the secure shell daemon is done by the unit ssh.service.

Systemd puts every service into a dedicated control group (cgroup) named after the service. Modern kernels support process isolation and resource allocation based on cgroups.

Targets are groups of units. Targets call units to put the system together. For instance, graphical.target calls all units that are necessary to start a workstation with graphical user interface. Targets can build on top of another or depend on other targets. At boot time, systemd activates the target default.target which is an alias for another target such as graphical.target.

Systemd creates and manages the sockets used for communication between system components. For instance, it first creates the socket /dev/log and then starts the syslog daemon. This approach has two advantages: Firstly, processes communicating with syslog via /dev/log can be started in parallel. Secondly, crashed services can be restarted without processes that communicate via sockets with them losing their connection. The kernel will buffer the communication while the process restarts.

Please see the upstream systemd page for more information.

Basic usage

systemctl is the main tool used to introspect and control the state of the "systemd" system and service manager. You can use systemctl for instance to enable/disable services permanently or only for the current session. Refer to the systemctl(1) manpage for more details.

Getting information on system status

Show system status:

List failed units:

List installed unit files:

Managing services

List all running services:

Activates the service "example1" immediately:

Deactivates the service "example1" immediately:

Restarts the service "example1" immediately:

Shows status of the service "example1":

Enables "example1" to be started on bootup:

Disables "example1" to not start during bootup:

Creating or altering services

Units are defined by individual configuration files, called unit files. The type of the unit is recognized by the file name suffix, .mount in case of a mount point. Unit files provided by Debian are located in the /lib/systemd/system directory. If an identically named local unit file exists in the directory /etc/systemd/system, it will take precedence and systemd will ignore the file in the /lib/systemd/system directory. Some units are created by systemd without a unit file existing in the file system.

System administrators should put new or heavily-customized unit files in /etc/systemd/system.

Here's an example:

For information about writing your own services, see systemd/Services.

Installing and Testing

systemd was included in Debian wheezy as a technology preview. Please make sure that you are using Debian jessie or newer to get a recent version of systemd.

Installation

To install systemd run:

This will install the systemd packages but will not configure systemd as your init system.

Configuring for testing

To test systemd before switching to it by default, you can add the following boot parameter to the kernel:

This can be done in the grub menu for a single boot - press "e" in the grub menu and add this to the kernel line. For example, depending on the options required for your particular system, it might look something like:

If PID 1 is systemd then your system is running with systemd.

Configuring as default

In order to use systemd you should also install systemd-sysv which provides the symlinks links for /sbin/init. It is recommended to run this when already running under systemd, as described in the previous section.

In order to boot your system with the newly installed systemd, simply reboot.

If you run a self-compiled kernel, make sure you have 2.6.39 or newer and enable the following options:

For an up-to-date list, see section "REQUIREMENTS" in the upstream README file.

Debugging

Failed units

In some cases units enter a failed state. The statuscommand can be used to find out some details:

Failed units can be manually cleared out:

systemd hangs on startup or shutdown

Sometimes it is necessary to investigate why systemd hangs on startup or on reboot/shutdown.

Of course you can have a "temporary" persistent solution:

HINT: "man systemd" and "man systemd-system.conf"

HINT: Extensive debugging information about systemd is on this FreeDesktop page.

HINT: How to check Kernel command line parameters/options?

"Set log level. As an argument this accepts a numerical log level or the well-known syslog(3) symbolic names (lowercase): emerg, alert, crit, err, warning, notice, info, debug."

HINT: Keep a copy of /sbin/init from sysvinit package in case of rescue (so you can use init=/sbin/init.sysvinit in cmdline)!

Kernel debug without systemd debug in Jessie

Using the old "debug" kernel parameter in Jessie will turn on systemd debug logging as well as kernel debug logging. To get the old behaviour, do not use "debug", instead use the kernel parameter "loglevel=7".

Bugs and Bug-Tracking-Systems

Known Issues and Workarounds

Shared bind mounts

The default behavior of bind mounts changes under systemd. The Linux kernel makes bind mounts of anything below / PRIVATE. Systemd changes this to SHARED.

Thus, when you do this:

then /dev will be unmounted in your base/parent system as well!

What you can do now instead, is to:

this will propagate mount changes (also mount options) in the base/parent system into the $CHROOT but not from the $CHROOT back to the parent.

The rationale for the change of the default behavior can be found in bug 739593, particularly in Lenart's comment therein.

SSH session doesn't cleanly terminate on reboot/shutdown

If you happen to reboot/shutdown remote machine over ssh you may find out that your session isn't terminated properly, leaving you with the non-reacting terminal until long a timeout has been reached. There was bug 751636 about it. A workaround to this problem was to install:

which would terminate the ssh session before the network was dropped. Please note, that that would require PAM to be enabled in sshd.

Missing startup messages on console(tty1) after the boot

With systemd console(tty1) is handled differently and if you used to check it to see how did your boot go now you'll see only couple of non-informative lines.

To be able to get full transcript of the system boot on your console you need to perform two steps.

1. Add to the kernel options systemd.show_status=1 , for example via /etc/default/grub:

and run update-grub2 .

2. Create file /etc/systemd/system/getty@tty1.service.d/noclear.conf with the content:

to disable clearing of the terminal on getty invocation.

Virtual and serial console changes

Those used to change inittab to enable/disable virtual or serial consoles will notice that that file is gone from clean installs. This is all managed through systemd directly now. For example, you can enable a serial console on COM1 with:

However, it is generally preferable to add console=ttyS0 on the kernel commandline, since this also enables kernel output on reboots. This is done by adding the following to /etc/default/grub:

. and running update-grub. This will take effect only on the next reboot, however.

Orphaned processes

Because it manages user sessions (taking over the role of X or other components), systemd may slightly change how processes survive a logoff. By default, when X shuts down all processes should exit and systemd will clean up the session, but there are some corner cases where certain processes don't cleanup after themselves properly.

You can configure how systemd manages leftover processes with the KillUserProcesses= parameter in logind.conf. By setting this to yes, processes will be forcibly killed when the session terminates. Note that this will break tools like screen or tmux, unless they are configured to run under a distinct user@.service unit and if enable-linger is set to yes in loginctl. A simple way to do this on the fly is to run the program in a "transient scope", using systemd-run:

Now, normally sessions should cleanup after themselves, and such issues should be fixed without having to revert to the KillUserProcesses=yes sledgehammer. A good way to list the affected processes is to group them by "control group", with the systemd-cgls command:

systemd представляет собой менеджер системы и сервисов для Linux, совместимый с SysV и LSB сценариями. systemd обеспечивает возможности агрессивного распараллеливания, использует сокет и D-Bus для начала активации сервиса по требованию, запуск демонов в фоновом режиме, отслеживает процессы, использующие Linux cgroups, поддерживает мгновенные снимки и восстановление состояния системы, поддерживает подключения и автоматическое монтирование точек и реализует разработку логики транзакционных зависимостей службы управления. Он может работать как замена для Sysvinit.

Установка

Начиная с версии (20-1) systemd полностью вошло в хранилище testing. Начиная с версии (25-1) systemd имеет поддержку /run.

Чтобы установить systemd запустите:

  • CONFIG_DEVTMPFS=y
  • CONFIG_CGROUPS=y
  • CONFIG_AUTOFS4_FS=[y|m]
  • CONFIG_IPV6=[y|m], опционально, но очень рекомендуется

Начиная с v8 cgroupfs монтируется в /sys/fs/cgroup. Для этого требуется ядро Linux >= 2.6.36 или бэкпортирование этого патча.

Пакеты Debian с родной поддержкой systemd

Пример (для rsyslog: Ручная активация сервиса после инсталляции):

Известные проблемы и способы их решения

Пакет systemd-sysv package имеет в составе /sbin/init (как символьную ссылку на /bin/systemd) и следовательно, конфликтует с пакетом sysvinit .

Имеется проблема с "Essential flag" что необходимо обсудить с сопровождающим ?DebianPkg: Sysvinit .

This issue is only a warning and can be ignored, we have it on TODO (see below "Make /etc/mtab a symlink to /proc/self/mounts. Requires a newer util-linux package which stores user options separately."). (494001)

The full error-message in dmesg:

Workaround: Create required symlink:

The nfs-common / portmap / rpcbind SysV init scripts have a dependency cycle which will cause systemd to drop them. You will get an error message during boot like the following:

Until the portmap / nfs-common / rpcbind init scripts have been fixed, you can get rid of those error messages by uninstalling those packages or fixing their LSB init header manually.

This problem is caused by portmap / nfs-common / rpcbind installing symlinks in both rcS and rc, see 623377

A similar problem as above, but with a worse automatic resolution:

Corresponding bug report: 622394

Родное монтирование

With v12 or later you can use native (means systemd's) mount and fsck facility by making sure it is activated in /etc/systemd/system.conf.

The Debian package enables native mount by default since version 15-1.

If you use Logical-Volume-Manager (LVM) make sure to upgrade your lvm2 package to the latest version available from unstable (>= 2.02.84-1) as it contains important fixes regarding the udev integration. See 603710 for more details. The 19-1 package already does this.

Отладка systemd

Sometimes it is necessary to investigate why systemd hangs on startup or on reboot/shutdown.

Of course you can have a "temporary" persistent solution:

In addition enhance cmdline with "systemd.sysv_console=1" (0: disabled, 1: enabled).

HINT: "man system" and "man systemd.conf" (Note: File is system.conf vs. man-page system*d*.conf)

HINT: How to check Kernel command line parameters/options?

NOTE on ?LogLevel (see systemd(1) and systemd.conf(5)):

"Set log level. As argument this accepts a numerical log level or the well-known syslog(3) symbolic names (lowercase): emerg, alert, crit, err, warning, notice, info, debug."

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

Так как она разрабатывалась для замены sysvinit и использует существующие сценарии инициализации SysV, пакет systemd можно без проблем устанавливать вместе с sysvinit и запускать через параметр ядра init=/bin/systemd. Пакет systemd-sysv предоставляет замену /sbin/init.

Как включить systemd в Debian 7?

Для этого в загрузчике grub нужно добавить параметр init=/bin/systemd. Пример:

linux /vmlinuz-3.13-1-amd64 root=/dev/mapper/root-root init=/bin/systemd ro quiet

Как установить по умолчанию systemd?

apt-get install systemd-sysv
reboot

Выводим список всех сервисов в системе, или список всех запущенных сервисов:

systemctl | grep running

Список запущенных сервисов

Для запуска, остановки, рестарта, статуса одного сервиса ничего не изменилось:

systemctl status ssh

Но конечно верно будет писать так:

systemctl status ssh.service

А вот что очень удобно, так это управление сразу несколькими сервисами:

systemctl restart ssh postfix

То есть просто идет перечень.

Удобная система добавления в автозапуск. Вместо труднозапоминающегося update-rc.d теперь:

systemctl enable ssh

Или наоборот удаление из автозапуска:

systemctl disable ssh

Чтение журнала systemd

Для этого создана утилита journalctl, имеющая удобное и понятное управление.

Чтение всего журнала:

Чтение журнала в обратно порядке:

Чтение последних строк журнала:

Список последних запуском системы (из того что имеется в логе):

Использование диска журналом:

journalctl --until="2016-09-06 14:44:00"

journalctl --since="2016-09-06 14:44:00"

Указание секунд не обязательно.

Выборка по приоритетам ошибок:

Приоритеты можно указывать как цифрой, так и словом: "emerg" (0), "alert" (1), "crit" (2), "err" (3), "warning" (4), "notice" (5), "info" (6), "debug" (7).

Наша компания занимается администрированием веб-серверов на базе CentOS. Довольно часто наши клиенты используют веб-приложения на базе python, ruby или java. Для автозапуска подобных приложений есть готовые шаблоны для написания стартап-скриптов. Но прогресс не стоит на месте, вышел уже второй релиз CentOS 7 и, следуя старой традиции «не ставить dot-zero релизы на продакшен», мы начинаем предлагать клиентам сервера на базе CentOS 7.1 (1503).

В CentOS7, так же как и в его родителе RHEL7, используется systemd — менеджер системы и служб для Linux, совместимый со скриптами инициализации SysV и LSB. systemd обеспечивает возможности агрессивной параллелизации и много всего прочего.

image

Огромный монстр с множеством возможностей, гибкими настройками и мегабайтами документации…

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

Systemd запускает сервисы описанные в его конфигурации.
Конфигурация состоит из множества файлов, которые по-модному называют юнитами.

Все эти юниты разложены в трех каталогах:

/usr/lib/systemd/system/ – юниты из установленных пакетов RPM — всякие nginx, apache, mysql и прочее
/run/systemd/system/ — юниты, созданные в рантайме — тоже, наверное, нужная штука
/etc/systemd/system/ — юниты, созданные системным администратором — а вот сюда мы и положим свой юнит.

Юнит представляет из себя текстовый файл с форматом, похожим на файлы .ini Microsoft Windows.

[Название секции в квадратных скобках]
имя_переменной = значение

Для создания простейшего юнита надо описать три секции: [Unit], [Service], [Install]

В секции Unit описываем, что это за юнит:
Названия переменных достаточно говорящие:

Далее следует блок переменных, которые влияют на порядок загрузки сервисов:

Запускать юнит после какого-либо сервиса или группы сервисов (например network.target):

After=syslog.target
After=network.target
After=nginx.service
After=mysql.service

Для запуска сервиса необходим запущенный сервис mysql:

Для запуска сервиса желателен запущенный сервис redis:

В итоге переменная Wants получается чисто описательной.
Если сервис есть в Requires, но нет в After, то наш сервис будет запущен параллельно с требуемым сервисом, а не после успешной загрузки требуемого сервиса

В секции Service указываем какими командами и под каким пользователем надо запускать сервис:

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

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

Также следует определить PIDFile=, чтобы systemd могла отслеживать основной процесс:


Рабочий каталог, он делается текущим перед запуском стартап команд:

Пользователь и группа, под которым надо стартовать сервис:

Запрет на убийство сервиса вследствие нехватки памяти и срабатывания механизма OOM:
-1000 полный запрет (такой у sshd стоит), -100 понизим вероятность.

Команды на старт/стоп и релоад сервиса

ExecStart=/usr/local/bin/bundle exec service -C /work/www/myunit/shared/config/service.rb --daemon
ExecStop=/usr/local/bin/bundle exec service -S /work/www/myunit/shared/tmp/pids/service.state stop
ExecReload=/usr/local/bin/bundle exec service -S /work/www/myunit/shared/tmp/pids/service.state restart

Тут есть тонкость — systemd настаивает, чтобы команда указывала на конкретный исполняемый файл. Надо указывать полный путь.

Таймаут в секундах, сколько ждать system отработки старт/стоп команд.

Попросим systemd автоматически рестартовать наш сервис, если он вдруг перестанет работать.
Контроль ведется по наличию процесса из PID файла

В секции [Install] опишем, в каком уровне запуска должен стартовать сервис

multi-user.target или runlevel3.target соответствует нашему привычному runlevel=3 «Многопользовательский режим без графики. Пользователи, как правило, входят в систему при помощи множества консолей или через сеть»

Вот и готов простейший стартап скрипт, он же unit для systemd:
myunit.service


Кладем этот файл в каталог /etc/systemd/system/

Смотрим его статус systemctl status myunit


Видим, что он disabled — разрешаем его
systemctl enable myunit
systemctl -l status myunit

Если нет никаких ошибок в юните — то вывод будет вот такой:

Запускаем сервис
systemctl start myunit

Смотрим красивый статус:
systemctl -l status myunit

Если есть ошибки — читаем вывод в статусе, исправляем, не забываем после исправлений в юните перегружать демон systemd

Читайте также: