Как установить systemd в ubuntu

Обновлено: 06.07.2024

This document compares Upstart and systemd with a view to aiding in the transition to the latter.

First, it is important to note that systemd is only fully supported in Ubuntu 15.04 and later releases. While systemd is available in prior releases through the Ubuntu repositories, there is a deemphasis of support for these releases as noted here. Hence, it is advised to use the default upstart on prior releases.

This has changed as part of the Ubuntu 15.04 devel cycle.

If you are running Ubuntu vivid (15.04), you can easily switch between upstart and systemd at will since both packages are installed at present. As of March 9 2015, vivid was changed to use systemd by default, before that upstart was the default.

Switch to upstart for a single boot

In grub, select "Advanced options for Ubuntu", where you will find an "Ubuntu, with Linux . (upstart)" entry. This will boot with init=/sbin/upstart.

If you have upstart-sysv installed and thus boot with upstart by default, there will be an "Ubuntu, with Linux . (systemd)" entry, which will boot with init=/lib/systemd/systemd.

Permanent switch back to upstart

Install the upstart-sysv package, which will remove ubuntu-standard and systemd-sysv (but should not remove anything else -- if it does, yell!), and run sudo update-initramfs -u. After that, grub's "Advanced options" menu will have a corresponding "Ubuntu, with Linux . (systemd)" entry where you can do an one-time boot with systemd.

If you want to switch back to systemd, install the systemd-sysv and ubuntu-standard packages.

Upstart's model for starting processes (jobs) is "greedy event-based", i. e. all available jobs whose startup events happen are started as early as possible. During boot, upstart synthesizes some initial events like startup or rcS as the "tree root", the early services start on those, and later services start when the former are running. A new job merely needs to install its configuration file into /etc/init/ to become active.

systemd's model for starting processes (units) is "lazy dependency-based", i. e. a unit will only start if and when some other starting unit depends on it. During boot, systemd starts a "root unit" (default.target, can be overridden in grub), which then transitively expands and starts its dependencies. A new unit needs to add itself as a dependency of a unit of the boot sequence (commonly multi-user.target) in order to become active.

This maps the keywords that can occur in an upstart job to the corresponding ones in a systemd unit. Keywords which don't have a direct equivalent are marked with "-".

Как вы уже, наверное, знаете, что Debian после тяжёлых и многочисленных дебатов и голосований перешёл на новую систему инициализации Systemd. Вслед за папой Debian и Ubuntu переходит со своей системы Upstart на Systemd. Мы перейдём на Systemd полностью и бесповоротно!



Ubuntu и Debian. Systemd и Upstart.

Данная статья рассчитана только на опытных пользователей. Мы будем изменять систему инициализации у разрабатываемой Ubuntu 15.04 Vivid Vervet. Стоит напомнить, что система инициализации, известная так же как PID 1, одна из важнейших подсистем в операционной системе. Сбои и баги в ней малоприятны. 7 раз отмерьте - 1 раз отрежьте. Следует знать, что в последних версиях Убунту присутствуют установленные пакеты как upstart, так и systemd. Только главным и единственным является upstart.

В Upstart модель старта процессов (jobs) является "greedy event-based", то есть все доступные сервисы при наступлении события жадно стартуют, как можно быстрее.

В Systemd модель старта процессов (units) является "lazy dependency-based", то есть unit стартует только тогда, когда стартовал unit, от которого он зависит.

Чтобы переключиться на systemd, сначала сделаем себе страхующие вещи:

  • Правим файл sudo -e /etc/default/grub и удаляем quiet и splash из GRUB_CMDLINE_LINUX_DEFAULT. Сохраняем файл и вызываем sudo update-grub
  • Сделайте себе спасительный shell sudo systemctl enable debug-shell.service . Если система не загрузится, то вы можете зайти в консоль по CTRL+ALT+F9.
  • Запишите себе команду или лучше создайте скрипт, который может вам точно показать текущую систему инициализации. Вот волшебная команда идентификации PID1 ps -p1 | grep systemd && echo systemd || echo upstart

До полного перехода, можно и нужно попробовать загрузить систему с помощью systemd однократно. При старте системы успевайте зайти в меню grub и там в Advanced options for Ubuntu там найдите своё последнее ядро с "Ubuntu, with Linux . (systemd)". Вы загрузитесь с параметром init=/lib/systemd/systemd

Полностью перейти на systemd можно, установив пакет sudo apt-get install systemd-sysv . У вас должны удалиться пакеты ubuntu-minimal, ureadahead и upstart.

Кратенько в сравнении, как управляются сервисы в Upstart и Systemd.

Действие Upstart Systemd
Старт сервиса start $job systemctl start $unit
Остановка сервиса stop $job systemctl stop $unit
Рестарт сервиса restart $job systemctl restart $unit
Статус сервиса initctl list systemctl status
Проверка конфигурации init-checkconf /tmp/foo.conf systemd-analyze verify <unit_file>
Показать переменные окружения initctl list-env systemctl show-environment
Установить переменную initctl set-env foo=bar systemctl set-environment foo=bar
Удалить переменную initctl unset-env foo systemctl unset-environment foo
Журнал работы сервиса cat /var/log/upstart/$job.log sudo journalctl -u $unit
Смотреть постоянно журнал tail -f /var/log/upstart/$job.log sudo journalctl -u $unit -f
Показать зависимости сервисов initctl2dot systemctl list-dependencies --all

Всё познаётся в сравнении.


[1] Реализация упреждающего чтения в Upstart доступна в виде отдельного пакета ureadahead и требует наложения патча на ядро
[2] Активация через сокеты в upstart является экспериментальной возможностью, а также не поддерживает сериализацию, поэтому вообще не подходит для этого.
[3] Активация через шину для upstart доступна пока только в виде патча, который в основную ветку разработки ещё не принят.
[4] реализация в upstart не является практичной.
[5] Данная возможность для upstart существует в виде отдельного пакета и работает только для монтирования во время загрузки, плохо поддерживая зависимости.
[6] Некоторые дистрибутивы реализуют эту возможность с помощью shell скриптов.
[7] Скрипты инициализации LSB поддерживают это, в случае если они используются.

От себя лично, хочется сказать о впечатлении о "переходе". Систему инициализации в хорошем смысле не видно, так как работает она под капотом, но меня поразила скорость загрузки. Нельзя сказать, что Upstart как-то медленно загружает систему, но всё же субъективно Systemd влёт грузит сервисы и вот сразу виден вход в систему LightDM. Хотя по мнению Леннарта (автора systemd) высокая скорость systemd - это всего лишь побочный результат правильного дизайна и архитектуры проекта, а не цель. Я не являюсь противником Леннарта Поттеринга (Lennart Poettering) и мне нравится systemd, который в будущем унифицирует во всех дистрибутивах линукс работу с сервисами. Вот только за это, стоит сказать спасибо!

Видео дня! Противостояние режимов Desktop vs Tablet в Unity 8 Ubuntu 15.04.

This topic provides instructions for installing a production-ready Confluent Platform configuration in a multi-node Ubuntu or Debian environment with a replicated ZooKeeper ensemble.

With this installation method, you connect to every node manually to run the Confluent Platform installation commands.

You must complete these steps for each node in your cluster.

Prerequisites Before installing Confluent Platform, your environment must have the following software and hardware requirements .

Get the Software¶

The APT repositories provide packages for Debian-based Linux distributions such as Debian and Ubuntu. You can install individual Confluent Platform packages or the entire platform. For a list of available packages, see the documentation or you can search the repository ( apt-cache search <package-name> ).

You can install the entire platform or the individual component packages. For a listing of packages, see Confluent Platform Packages .

Install the Confluent public key. This key is used to sign the packages in the APT repository.

Add the repository to your /etc/apt/sources.list by running this command:

For the clients repository, you must obtain your Debian distribution’s release “Code Name”, such as buster , focal , etc. You can do this by calling lsb_release -cs . The following example makes this call with $(lsb_release -cs) , which should work in most cases. If it does not, you must pick the closest Debian or Ubuntu code name for your Debian Linux distribution that matches the supported Debian & Ubuntu Operating Systems supported by Confluent Platform.

Update apt-get and install the entire Confluent Platform platform.

Confluent Platform with RBAC :

Confluent Platform using only Confluent Community components:

Configure Confluent Platform¶

You can store passwords and other configuration data securely by using the confluent secret commands. For more information, see Secrets Management .

Configure Confluent Platform with the individual component properties files. By default these are located in <path-to-confluent>/etc/ . You must minimally configure the following components.

ZooKeeper¶

These instructions assume you are running ZooKeeper in replicated mode. A minimum of three servers are required for replicated mode, and you must have an odd number of servers for failover. For more information, see the ZooKeeper documentation.

Navigate to the ZooKeeper properties file ( /etc/kafka/zookeeper.properties ) file and modify as shown.

This configuration is for a three node ensemble. This configuration file should be identical across all nodes in the ensemble. tickTime , dataDir , and clientPort are all set to typical single server values. The initLimit and syncLimit govern how long following ZooKeeper servers can take to initialize with the current leader and how long they can be out of sync with the leader. In this configuration, a follower can take 10000 ms to initialize and can be out of sync for up to 4000 ms based on the tickTime being set to 2000ms.

The server.* properties set the ensemble membership. The format is

  • myid is the server identification number. There are three servers that each have a different myid with values 1 , 2 , and 3 respectively. The myid is set by creating a file named myid in the dataDir that contains a single integer in human readable ASCII text. This value must match one of the myid values from the configuration file. You will see an error if another ensemble member is already started with a conflicting myid value.
  • leaderport is used by followers to connect to the active leader. This port should be open between all ZooKeeper ensemble members.
  • electionport is used to perform leader elections between ensemble members. This port should be open between all ZooKeeper ensemble members.

The autopurge.snapRetainCount and autopurge.purgeInterval have been set to purge all but three snapshots every 24 hours.

Navigate to the ZooKeeper log directory (e.g., /var/lib/zookeeper/ ) and create a file named myid . The myid file consists of a single line that contains the machine ID in the format <machine-id> . When the ZooKeeper server starts up, it knows which server it is by referencing the myid file. For example, server 1 will have a myid value of 1 .

Kafka¶

In a production environment, multiple brokers are required. During startup brokers register themselves in ZooKeeper to become a member of the cluster.

Navigate to the Apache Kafka® properties file ( /etc/kafka/server.properties ) and customize the following:

Connect to the same ZooKeeper ensemble by setting the zookeeper.connect in all nodes to the same value. Replace all instances of localhost to the hostname or FQDN (fully qualified domain name) of your node. For example, if your hostname is zookeeper :

Configure the broker IDs for each node in your cluster using one of these methods.

Dynamically generate the broker IDs: add broker.id.generation.enable=true and comment out broker.id . For example:

Manually set the broker IDs: set a unique value for broker.id on each node.

Configure how other brokers and clients communicate with the broker using listeners , and optionally advertised.listeners .

  • listeners : Comma-separated list of URIs and listener names to listen on.
  • advertised.listeners : Comma-separated list of URIs and listener names for other brokers and clients to use. The advertised.listeners parameter ensures that the broker advertises an address that is accessible from both local and external hosts.

Configure security for your environment.

  • For general security guidance, see Security Overview .
  • For role-based access control (RBAC), see Configure Metadata Service (MDS) .
  • For SSL encryption, SASL authentication, and authorization, see Security Tutorial .

Control Center¶

Navigate to the Control Center properties file ( /etc/confluent-control-center/control-center-production.properties ) and customize the following:

This configuration is for a three node multi-node cluster. For more information, see Control Center configuration details . For information about Confluent Platform licenses, see Managing Confluent Platform Licenses .

Navigate to the Kafka server configuration file ( /etc/kafka/server.properties ) and enable Confluent Metrics Reporter.

Add these lines to the Kafka Connect properties file ( /etc/kafka/connect-distributed.properties ) to add support for the interceptors.

Schema Registry¶

Navigate to the Schema Registry properties file ( /etc/schema-registry/schema-registry.properties ) and specify the following properties:

This configuration is for a three node multi-node cluster. For more information, see Running Schema Registry in Production .

Start Confluent Platform¶

Start Confluent Platform and its components using systemd service unit files. You can start immediately by using the systemctl start command or enable for automatic startup by using the systemctl enable command. These instructions use the syntax for immediate startup.

ZooKeeper, Kafka, and Schema Registry must be started in this specific order, and must be started before any other components.

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."

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