Systemd
systemd是 一个现代的、SysV-风格的init 以及对 rc Linux系统的替代。 Gentoo 将其作为一个可选的 init系统 。
Switching init systems is a non trivial operation that has implications for how the system is configured, and sometimes for what software can be installed or not. Generally, an init system will be chosen at installation time (i.e. by downloading either a systemd or an openrc stage3 tarball), and only changed if necessary. In true Gentoo style, in addition to systemd and OpenRC, several init systems are supported.
如果systemd 并不想要被作为依赖项引入, 请参见 不使用systemd 的 Gentoo一文。
安装
如果从 <=sys-apps/systemd-203 升级,请查看 子条目:升级。
Linux内核是所有发行版的核心。它介于用户程序和系统硬件之间。Gentoo提供给用户一些可选的内核源码。完整的、带描述的列表在内核概述页面。
对于基于 amd64 的系统,Gentoo 推荐 sys-kernel/gentoo-sources 包.
选择一个合适的内核并使用 emerge 来安装它。
root #
emerge --ask sys-kernel/gentoo-sources
内核
systemd使现代Linux内核的许多特色得以充分发挥。现在,要想支持systemd,内核版本必须高于ebuild 2.6.39。 在最新的版本 sys-kernel/gentoo-sources包中, 有一个快捷的方法,使得systemd成为强制选择或可选的内核选项(请看Kernel/Configuration 来获得进一步的了解):
Gentoo Linux --->
Support for init systems, system and service managers --->
[*] systemd
手动配置内核选项 (这是在不使用sys-kernel/gentoo-sources时,唯一的选择 ), 下面是内核配置选项的要求或建议:
General setup --->
[*] Control Group support --->
[*] Support for eBPF programs attached to cgroup
[ ] Enable deprecated sysfs features to support old userspace tools
[*] Configure standard kernel features (expert users) --->
[*] open by fhandle syscalls
[*] Enable eventpoll support
[*] Enable signalfd() system call
[*] Enable timerfd() system call
[*] Enable bpf() system call
[*] Networking support --->
Device Drivers --->
Generic Driver Options --->
[*] Maintain a devtmpfs filesystem to mount at /dev
File systems --->
[*] Inotify support for userspace
Pseudo filesystems --->
[*] /proc file system support
[*] sysfs file system support
General setup --->
[*] Configure standard kernel features (expert users) --->
[*] Checkpoint/restore support
[*] Namespaces support --->
[*] Network namespace
[*] Enable the block layer --->
[*] Block layer SG support v4
Processor type and features --->
[*] Enable seccomp to safely compute untrusted bytecode
Networking support --->
Networking options --->
<*> The IPv6 protocol
Device Drivers --->
Generic Driver Options --->
() path to uevent helper
[ ] Fallback user-helper invocation for firmware loading
Firmware Drivers --->
[*] Export DMI identification via sysfs to userspace
File systems --->
<*> Kernel automounter version 4 support (also supports v3)
Pseudo filesystems --->
[*] Tmpfs virtual memory file system support (former shm fs)
[*] Tmpfs POSIX Access Control Lists
[*] Tmpfs extended attributes
UEFI系统应该启用下面的选项:
[*] Enable the block layer --->
Partition Types --->
[*] Advanced partition selection
[*] EFI GUID Partition support
Processor type and features --->
[*] EFI runtime service support
Firmware Drivers --->
EFI (Extensible Firmware Interface) Support -->
<*> EFI Variable Support via sysfs
如果你的系统使用BFQ scheduler, 这里推荐使用 BFQ upstream 来启用 "BFQ hierarchical scheduling support" 下的"Enable the block layer -> IO Schedulers".
IO Schedulers --->
<*> BFQ I/O scheduler
[*] BFQ hierarchical scheduling support
要获取最新的列表,请参阅部分上游的“需求”说明:README 文件。
在启动时确保挂载了/usr路径
如果你对/usr进行单独分区,在你运行systemd前,要使用initramfs 来挂载/usr分区 。就目前而言,这直到包 sys-kernel/genkernel可用前,使用sys-kernel/dracut 或 sys-kernel/genkernel-next ,他们支持挂载/usr 。这为的是现在进行安装:
root #
emerge --ask -c sys-kernel/genkernel
root #
emerge --ask sys-kernel/dracut
root #
emerge --ask sys-kernel/genkernel-next
当你使用dracut时,如果它不自动启用/usr模块,请手动安装。
# 添加 Dracut 模块为默认模块
add_dracutmodules+="usrmount"
当你使用genkernel-next时,在重新编译内核之前,一定要在genkernel配置中设置UDEV 变量,使他变成yes
。这将把/usr配置到initramfs中:
# 使用udev而不是把MDEV作为initramfs的默认设备管理器。
#如果systemd或者同时使用LVM,那么必须开启下列选项。
UDEV="yes"
root #
genkernel --install all
参考 Initramfs 向导 来获得更多帮助。
使用LVM和initramfs
当使用 sys-fs/lvm2,且系统通过initramfs 启动时,必须使用sys-kernel/genkernel-next 包来创建initramfs :
root #
genkernel --lvm <target>
这意味着创建一个initramfs genkernel target,使用<target>
或 initramfs
。更多有关信息,请查看genkernel --help的提示:
user $
genkernel --help
USE 标记
USE flags for sys-apps/systemd System and service manager for Linux
+dns-over-tls
|
Enable DNS-over-TLS support |
+gcrypt
|
Enable use of dev-libs/libgcrypt for various features |
+kernel-install
|
Enable kernel-install |
+kmod
|
Enable kernel module loading via sys-apps/kmod |
+lz4
|
Enable lz4 compression for the journal |
+openssl
|
Enable use of dev-libs/openssl for various features |
+resolvconf
|
Install resolvconf symlink for systemd-resolve |
+seccomp
|
Enable seccomp (secure computing mode) to perform system call filtering at runtime to increase security of programs |
+sysv-utils
|
Install sysvinit compatibility symlinks and manpages for init, telinit, halt, poweroff, reboot, runlevel, and shutdown |
+zstd
|
Enable support for ZSTD compression |
acl
|
Add support for Access Control Lists |
apparmor
|
Enable support for the AppArmor application security system |
audit
|
Enable support for sys-process/audit |
boot
|
Enable EFI boot manager and stub loader |
bpf
|
Enable BPF support for sandboxing and firewalling. |
cgroup-hybrid
|
Default to hybrid (legacy) cgroup hierarchy instead of unified (modern). |
cryptsetup
|
Enable cryptsetup tools (includes unit generator for crypttab) |
curl
|
Enable support for uploading journals |
elfutils
|
Enable coredump stacktraces in the journal |
fido2
|
Enable FIDO2 support |
gnutls
|
Prefer net-libs/gnutls as SSL/TLS provider (ineffective with USE=-ssl) |
homed
|
Enable portable home directories |
http
|
Enable embedded HTTP server in journald |
idn
|
Enable support for Internationalized Domain Names |
importd
|
Enable import daemon |
iptables
|
Use libiptc from net-firewall/iptables for NAT support in systemd-networkd; this is used only if the running kernel does not support nftables |
lzma
|
Support for LZMA compression algorithm |
pam
|
Add support for PAM (Pluggable Authentication Modules) - DANGEROUS to arbitrarily flip |
pcre
|
Add support for Perl Compatible Regular Expressions |
pkcs11
|
Enable PKCS#11 support for cryptsetup and homed |
policykit
|
Enable PolicyKit (polkit) authentication support |
pwquality
|
Enable password quality checking in homed |
qrcode
|
Enable qrcode output support in journal |
secureboot
|
Automatically sign efi executables using user specified key |
selinux
|
!!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur |
split-usr
|
Enable behavior to support maintaining /bin, /lib*, /sbin and /usr/sbin separately from /usr/bin and /usr/lib* |
test
|
Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently) |
tpm
|
Enable TPM support |
ukify
|
Enable systemd-ukify |
vanilla
|
Disable Gentoo-specific behavior and compatibility quirks |
xkb
|
Depend on x11-libs/libxkbcommon to allow logind to control the X11 keymap |
Profile
开启 systemd
在全局USE flag 中,(make.conf中)。consolekit
USE flag 也应该被禁用,以防止与systemd-logind服务产生冲突。另外,也可以切换到一个systemd sub profile使用的较好的USE标记的默认值,在这种情况下,没有必要改变make.conf:
root #
eselect profile list
最后,更新系统与 profile:
root #
emerge -avDN @world
Once this command is complete, it is important follow the Configuration steps.
依赖问题
当使用 systemd 替换 OpenRC 时,可能会发生一些依赖问题。
如果 sys-apps/sysvinit 阻止了 sys-apps/systemd,尝试对 sys-apps/systemd 禁用 sysv-utils
USE flag 。如果需要的话,可以之后启用那个 use flag (并且重新安装 sys-apps/systemd )。
root #
emerge --oneshot sys-apps/openrc
root #
emerge --ask --depclean
If sys-apps/sysvinit is still blocking sys-apps/systemd, make sure it and sys-apps/openrc are not contained in the world file:
root #
emerge --deselect sys-apps/openrc sys-apps/sysvinit
如果 sys-fs/udev 阻止了 sys-apps/systemd), sys-fs/udev,这可能是world文件已经被记录。要解决这个问题。试着取消它:
root #
emerge --deselect sys-fs/udev
sys-apps/systemd中包含 udev。一旦安装了sys-apps/systemd ,那么就可以删除 sys-fs/udev,因为systemd将会提供virtual/udev。
If the @system set provides sys-fs/eudev, virtual/udev and virtual/libudev may be preventing systemd. To make portage resolve the problem, after setting the USE flag, try to reinstall the virtuals:
root #
emerge --oneshot virtual/udev virtual/libudev
Bootloader
This is no longer necessary with sys-apps/systemd when the
sysv-utils
USE is enabled. This defaults to on with at least version 239 in Gentoo为了运行systemd,切换init可用内核 (或者 initramfs)使用。
先前被设置的服务管理器服务不会自动启动。这是因为该系统切换到不同的服务管理器。为了获得像网络或登录管理器的这样功能,这些服务需要被重新启用。更多关于这个的信息,在之后本文后面部分的‘‘‘服务’’’章节。
如果在迁移启动引导器中发生了错误,它一般可以通过撤销该INIT变化这一步,来使用回默认的引导服务管理器(OpenRC)。这可以安全返回。本文的最后的故障排除章节,用来解决这些问题以便于可以安全的返回系统。
接下来的部分文档指导你如何切换init 启动管理器或内核。
GRUB Legacy (0.x)
init=/lib/systemd/systemd
这行代码参数应该被添加到内核的代码行。这是一个摘自grub.conf例子,它应该是这样:
title=Gentoo with systemd
root (hd0,0)
kernel /vmlinuz root=/dev/sda2 init=/lib/systemd/systemd
如果要想使用OpenRC系统启动,尝试使用 real_init
替换init
。
GRUB
当grub-mkconfig 被使用时, 增加 init 这一行 GRUB_CMDLINE_LINUX:
这个不需要使用一个initramfs生成dracutsystemd ,因为initramfs内部已经有了systemd。
# Append parameters to the linux kernel command line
GRUB_CMDLINE_LINUX="init=/lib/systemd/systemd"
手动配置GRUB 文件时(仅限有经验的用户), 添加init=
参数到 linux
或 linux16
命令行。
linux /vmlinuz-3.10.9 root=UUID=508868e4-54c6-4e6b-84b0-b3b28b1656b6 init=/lib/systemd/systemd
YABOOT
Yaboot is a boot loader for PowerPC-based hardware running Linux, particularly New World ROM Macintosh systems.
The init=/lib/systemd/systemd
argument should be added directly after the kernel command-line. An example from yaboot.conf:
image=/vmlinux
append="init=/lib/systemd/systemd"
label=Linux
read-only
initrd=/initramfs
initrd-size=8192
For the changes to take effect, the ybin command must be run each time the yaboot.conf file is modified.
内核配置
Init配置也可以在内核配置被固定。请看Processor type and features -> Built-in kernel command line. . 注意:这个方法适用于 GRUB.和 GRUB2
升级
systemd has the ability to update in-place on a running system (no reboot necessary). After an upgrade to systemd has emerged, run the following command:
root #
systemctl daemon-reexec
配置
systemd支持通过几个系统配置文件,来满足系统最基本的运行要求。
After installing systemd, run the following:
root #
systemd-machine-id-setup
root #
systemd-firstboot --prompt
root #
systemctl preset-all
If systemd-firstboot is not ran, it will automatically run on next boot. However, it interrupts the normal boot process, preventing access to the system from users who don't have access to the interactive console - like accessing a server via SSH.
虽然一些系统配置参数可通过修改相应的配置文件而被更新,但大部分设定使用需要systemd才能被系统设置程序管理。在这种情况下,使用systemd重新引导计算机是安全的hostnamectl, localectl, 然而系统设置timedatectl是必需的
Machine ID
创建一个ID来记录工作。这可以通过以下命令进行:
root #
systemd-machine-id-setup
The systemd-machine-id-setup command also has an impact on the
systemd-networkd
service. If this command is not run the system may exhibit strange behavior like network interfaces not coming up or network addresses not being applied.主机名称
要设置主机名称,创建/编辑 /etc/hostname ,然后直接输入所需的主机名。
当使用systemd启动时,一个叫 hostnamectl的工具 ,可以编辑/etc/hostname和/etc/machine-info来达到目的. 要更改主机名,执行:
root #
hostnamectl set-hostname <HOSTNAME>
参考 man hostnamectl 来获得更多选项。
区域设置
通常,区域设置将从OpenRC转换到安装systemd时被很好的设置。在你需要时,可以按照Gentoo手册的说明,设置语言环境/etc/locale.conf :
LANG="en_US.utf8"
如果你通过systemd启动,那么工具localectl可以被使用来设置区域在控制台或X11键盘映射的地区设置。要更改系统区域设置,请运行下列命令:
root #
localectl set-locale LANG=<LOCALE>
更改虚拟控制台键盘映射表:
root #
localectl set-keymap <KEYMAP>
最后,要设置X11布局:
root #
localectl set-x11-keymap <LAYOUT>
如果需要model, 变量和选项也可以被指定:
root #
localectl set-x11-keymap <LAYOUT> <MODEL> <VARIANT> <OPTIONS>
After doing any of the above, update the environment so the changes will take effect:
root #
env-update && source /etc/profile
时间和日期
可以使用timedatectl来设置时间和日期。它也允许用户设置同步,而无需依赖net-misc/ntp 或者其他的systemd自己的工具。
学习如何使用 timedatectl 只需运行:
root #
timedatectl --help
自动加载模块
自动加载模块配置在不同的文件中,或者更确切地说,在目录中的文件中。配置文件存储在/etc/modules-load.d。在启动与模块列表的每个文件将被加载,文件格式是由换行符分隔模块的列表,并且可以使用任何名称,只要它的扩展名是.conf。 加载模块可以由程序、服务或其他方式,取决于符合个人喜好。举个例子——virtualbox.conf。如下表所示:
vboxdrv
vboxnetflt
vboxnetadp
vboxpci
Automatic mounting of partitions at boot
Systemd is capable of automatically mounting various partitions to standardized location via systemd-gpt-auto-generator. This makes it possible to boot and automatically mount essential partitions without an fstab and without a root= paramter on the kernel command line. To use this capability, first systemd must be included in the initramfs, this is the case by default for initramfs images generated with Dracut on systems with systemd installed. And second, each partition must have the correct Partition Type GUID. A list of the most important GUIDs can be found in the systemd-gpt-auto-generator manual, the full list can be found on wikipedia.
To list the current Partition Type GUID of your partitions:
root #
lsblk -o NAME,LABEL,PARTLABEL,PARTTYPE,PARTTYPENAME,MOUNTPOINT
systemd-gpt-auto-generator can auto-mount partitions at the following locations, note that the correct GUID depends on the systems CPU architecture:
- / SD_GPT_ROOT_....
- /boot/ SD_GPT_ESP if no /efi/ and no XBOOTLDR partition, otherwise SD_GPT_XBOOTLDR
- /efi/ SD_GPT_ESP if /efi/ is present on the root, if not then ESP is at /boot/
- /home/ SD_GPT_HOME
- /srv/ SD_GPT_SRV
- /usr/ SD_GPT_USR_....
- /var/ SD_GPT_VAR
- /var/tmp/ SD_GPT_TMP
- Swap SD_GPT_SWAP
Below is an example of the most basic partition layout consisting of one EFI System Partition and one x86-64 root partition.
root #
lsblk -o NAME,LABEL,PARTLABEL,PARTTYPE,PARTTYPENAME,MOUNTPOINT
NAME LABEL PARTLABEL PARTTYPE PARTTYPENAME MOUNTPOINT nvme1n1 ├─nvme1n1p1 ESP EFI System Partition c12a7328-f81f-11d2-ba4b-00a0c93ec93b EFI System /boot └─nvme1n1p2 Gentoo Gentoo 4f68bce3-e8cd-4db1-96e7-fbcaf984b709 Linux root (x86-64) /
The PARTTYPE for an EFI System Partition is c12a7328-f81f-11d2-ba4b-00a0c93ec93b, it will be mounted at either /efi/ or /boot/ depending on which of these mount points is available and on if there is also an Extended Boot Loader Partition (PARTTYPE=bc13c2ff-59e6-4262-a352-b275fd6f7172) present on this disk. The PARTTYPE for an x86-64 root parition is 4f68bce3-e8cd-4db1-96e7-fbcaf984b709.
If the Partition Type GUID is not correct it can be changed without data loss using a partitioning tool such as fdisk. Note that the system must be offline to change the patition types! A system rescue image, or secondary operating system, must be used to complete the following steps.
Open the disk with the to be changed partition types in fdisk, in this exameple /dev/nvme1n1 is used:
root #
fdisk /dev/nvme1n1
Welcome to fdisk (util-linux 2.39.3). Changes will remain in memory only, until you decide to write them. Be careful before using the write command. Command (m for help):
List the current partition layout with the p command:
Command (m for help):
p
Disk /dev/nvme1n1: 1.82 TiB, 2000398934016 bytes, 3907029168 sectors Disk model: Samsung SSD 970 EVO Plus 2TB Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disklabel type: gpt Disk identifier: B25D5B33-4A10-F940-826C-3CB24ADC7D86 Device Start End Sectors Size Type /dev/nvme1n1p1 2048 1052671 1050624 513M EFI System /dev/nvme1n1p2 1052672 3907028991 3905976320 1.8T Linux root (x86-64)
Change the Partition Type GUID of any partition with the t command, followed by the number of the partition to be changed, and finally the alias for the desired partition type:
Command (m for help):
t
Partition number (1,2, default 2): 2 Partition type or alias (type L to list all): L Partition type or alias (type L to list all): 23 Changed type of partition 'Linux root (x86-64)' to 'Linux root (x86-64)'.
Repeat the above steps for any additional partitions of which the Partition Type GUID should be changed. Once completed, save the changes with the w command:
Command (m for help):
w
systemd-gpt-auto-generator will only auto-mount partitions that reside on the same disk as the EFI System Partition that the system is being booted from.
Some tools may become confused if there is no root= parameter on the kernel command line at all. To placate such tools add
root=/dev/gpt-auto-root
to the kernel command line. This trick is also usefull if a swapfile on the root partition is used instead of a swap partition for hibernation, i.e. one may specify the resume target on the kernel command line as resume=/dev/gpt-auto-root resume_offset=xxxxxxxxx
.网络
systemd is compatible with various network management tools.
systemd-networkd系统守护进程管理网络配置
See the systemd/systemd-networkd article for details on setting up a wired network on systemd systems.
systemd-resolved
See the systemd/systemd-resolved article for details on setting up address name resolution (DNS) on systemd systems.
网络管理
通常使用 NetworkManager 配置网络设置。当使用图形桌面时,只需要简单地运行以下命令:
root #
nm-connection-editor
如果情况并非如此,网络需要从终端来配置,nmcli值得试试, 或者遵循配置指导nmtui:
root #
nmtui
nmtui 是一个ncurses的前端,在控制台模式下运行,同时将引导用户的过程中。
For more details see the dedicated article.
处理日志文件
systemd 有自己的方式处理日志文件,而不需要依赖外部日志系统 (比如说app-admin/syslog-ng 或 app-admin/rsyslog)。
If desired, the logging service be configured to pass log messages to external logging utilities such as sysklog or syslog-ng. See man journald.conf to learn how to configure the systemd-journald service to suit situational needs.
systemd's integrated logging service writes log messages in a secure, binary format. The logs are read by using the journalctl command, which is a separate executable from the systemd-journald logging service.
{{{1}}}
一些常用选项journalctl:
Command-line options for journalctl | Result |
---|---|
journalctl without options | 选项显示从最早开始的所有日志条目。 |
-b , --boot |
显示当前引导的所有日志条目。 |
-r , --reverse |
首先显示最新的日志条目(按时间倒序)。 |
-f , --follow |
Show the last few entries and display new log entries as they're being produced. This is similar to running tail -f in text logging utilities. |
-p , --priority= |
Specify (minimum) priority to display messages, with a choice from: "emerg" (0), "alert" (1), "crit" (2), "err" (3), "warning" (4), "notice" (5), "info" (6), "debug" (7). |
-S , --since= , -U , --until= |
Restrict entries by time. Accepts the format "YYYY-MM-DD hh:mm:ss" or the strings "yesterday", "today" and "tomorrow". |
-n , --lines= |
Restrict to a number of entries. |
-k , --dmesg |
Restrict to kernel messages. |
-u , --unit= |
Restrict to a certain systemd unit. |
--system |
View system service and kernel logs. By default, this is only possible as the root user. See man journalctl for how to grant standard users the ability to read the system journal. |
| journalctl without options || Show all log entries, starting with earliest. |-
| -b
, --boot
|| Show all log entries from the current boot.
|-
| -r
, --reverse
|| Show the newest log entries first (reverse chronological order).
|-
| -f
, --follow
|| Show the last few entries and display new log entries as they're being produced. This is similar to running tail -f in text logging utilities.
|-
| -p
, --priority=
|| Specify (minimum) priority to display messages, with a choice from: "emerg" (0), "alert" (1), "crit" (2), "err" (3), "warning" (4), "notice" (5), "info" (6), "debug" (7).
|-
| -S
, --since=
, -U
, --until=
|| Restrict entries by time. Accepts the format "YYYY-MM-DD hh:mm:ss" or the strings "yesterday", "today" and "tomorrow".
|-
| -n
, --lines=
|| Restrict to a number of entries.
|-
| -k
, --dmesg
|| Restrict to kernel messages.
|-
| -u
, --unit=
|| Restrict to a certain systemd unit.
|-
| --system
|| View system service and kernel logs. By default, this is only possible as the root user. See man journalctl for how to grant standard users the ability to read the system journal.
|-
|}
想要获得更多信息和更多的选项,请看 man journalctl.
/tmp现在是在tmpfs
除非明确指定挂载其他的文件系统到/tmp 在 /etc/fstab中配置, systemd将会挂载/tmp 作为tmpfs。 这意味着它在每次启动时被清空,其大小将被限制在系统的RAM(内存)大小的50%。 要知道这是为什么,以及想要的行为和如何对其进行修改,请参考:API File Systems。
配置复杂的引导过程
当迁移到systemd用户通常注意到差异引导过程的时间
- 启动选项
quiet
不仅影响了内核输出,也影响了systemd本身。 再就是,当你为你的系统设置systemd时,可以删除该选项来查看哪些是容易发生的错误。之后,将它添加到一个静默的(和更快的)启动。 - 甚至通过
quiet
启动选项, systemd 仍然可以通过也传递配置以显示其状态systemd.show_status=1
。 - 当不使用
quiet
这个选项时,一些日志信息可能会刷满控制台。这是由内核配置造成的(请参考man 5 proc 并查找/proc/sys/kernel/printk)。要调整它通过loglevel=5
的引导参数内核(以及根据喜好更新值,例如设置成像1的较低值)。
用法
将旧目录转换为systemd 目录
参见systemd/homed 子文章
服务
在某一时刻,系统需要重新启动来让systemd运行(在system模式)。请务必仔细阅读本文,以确保在系统重新启动之前尽可能完整的配置systemd。注意journalctl 在systemd不运行时工作。但 systemctl在systemd不运行时不会做任何工作。登录到正在运行的系统systemd后完成服务配置(启用和启动服务)。
Preset services
Most services are disabled when systemd is first installed. A "preset" file is provided, and may be used to enable a reasonable set of default services.
root #
systemctl preset-all
OpenRC 服务
虽然systemd原本旨在支持运行旧的init.d脚本,支持不适合依赖于基于RC像“openrc”的引导,因此它支持在Gentoo上完全禁止。openrc提供了额外的措施来确保初始化。当openrc不是引导系统器时,init.d不能运行(否则,结果将是不可预知的)。
可用服务列表
列出所有可用服务:list-units
systemctl:
root #
systemctl list-units
UNIT LOAD ACTIVE SUB DESCRIPTION boot.automount loaded active waiting EFI System Partition Automount proc-sys-fs-binfmt_misc.automount loaded active waiting Arbitrary Executable File Formats File System Automount Point ...
下列文件扩展名值得关心:
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.). |
| .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.). |-
|}
作为选择 systemctl工具可用于列出所有服务(包括隐藏的):
root #
systemctl --all --full
最后查看未能运行的服务:
root #
systemctl --failed
启用、禁用、启动和停止服务
使服务可用的一般方法是使用下面的命令:
root #
systemctl enable foo.service
也可以禁用服务:
root #
systemctl disable foo.service
这些命令允许使用默认名称默认目标(包括在服务文件的“安装”部分中指定的服务)。但是,有时服务或者不提供该信息,或你喜欢有另一个名称/目标。
请注意,这些命令只能启用或禁用能够在下次开机启动的服务;要立即启动该服务,请使用:
root #
systemctl start foo.service
同样的服务也可以停止:
root #
systemctl stop foo.service
Services implementing ExecReload=
can be commanded to reload their configuration without restarting itself:
root #
systemctl reload foo.service
安装自定义单元文件
可以放在自定义单元文件/etc/systemd/system,确认在那里他们将运行后,运行systemctl daemon-reload:
root #
systemctl daemon-reload
/lib/systemd/system 被预留给服务包管理器安装的文件。
自定义单元文件
当需要时只有轻微的修改到一个单位时,那里是无需创建 /etc/systemd/system原始的单元文件的完整拷贝。重写包提供的管理单元中的设置可以通过链接文件
- .d 目录在命名原单位之后 (例如 apache2.d) 在/etc/systemd/system/中。
Both the drop-in directory and config file can be created using the systemctl edit utility or manually.
The editing utility can be invoked as:
root #
systemctl edit apache2.service
[Service]
MemoryLimit=1G
重载systemd,需要通知它的变化:
root #
systemctl daemon-reload
然后服务需要重新来启动应用的更改:
root #
systemctl restart apache2
验证更改的变量被应用到服务:
root #
systemctl show --property=MemoryLimit apache2
MemoryLimit=1074000000
{{{1}}}
根据自定义名称启用服务
当提供的名称在组件"[安装]"部分的不符合期望,由"Alias"提供永久的新名字,这为此通过 customization 所需,可以手动在 /etc/systemd/system/*.wants/ 创建一个链接文件。名称
- .wants 目录可以指定一个目标或者将取决于新一的另一项服务。
例如,安装mysqld.service 因为db.service在multi-user.target:
root #
ln -s /lib/systemd/system/mysqld.service /etc/systemd/system/multi-user.target.wants/db.service
要禁用该服务,只删除符号链接即可:
root #
unlink /etc/systemd/system/multi-user.target.wants/db.service
本机服务
Gentoo的安装包已经有systemd组件文件。对于这些服务,这足以使他们开启它。快速的迷你安装组件文件可以在systemd eclass users list看到。
下表列出了与OpenRC一致的服务:
Gentoo package | OpenRC service | systemd unit | Notes |
---|---|---|---|
sys-apps/openrc | bootmisc | systemd-tmpfiles-setup.service | 一直 enabled, uses tmpfiles.d |
consolefont | systemd-vconsole-setup.service | 一直 enabled, uses vconsole.conf | |
devfs | |||
dmesg | |||
fsck | fsck*.service | 被隐含地隐藏 | |
functions.sh | 见附注 | bug #373219 | |
hostname | (builtin) | /etc/hostname | |
hwclock | 见附注 | 作为 systemd 一直开启(i.e. it is baked in and it is not a unit) | |
keymaps | systemd-vconsole-setup.service | 一直 enabled, uses vconsole.conf | |
killprocs | |||
local | |||
localmount | local-fs.target | 实际单位是隐式创建的/etc/fstab | |
modules | systemd-modules-load.service | 一直 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 | 一直 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 | 对于 <networkmanager-0.9.8.4 : 为了dispatcher开启 NetworkManager-dispatcher.service 。 开启 NetworkManager-wait-online.service 以检测系统是否具有可用的互联网连接。 禁用所有其他管理器 (比如 wicd, dhcpcd) 和 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 | 运行 sshd 守护进程 |
sshd.socket | 在inetd-like类基础上运行ssh(对于每个传入连接) | ||
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 | 常用的启动启动服务 |
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 | 仅支持守护程序模式 |
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 | 它的大部分功能由systemd本身完成,因此请考虑禁用它 |
x11-apps/xdm | (xdm) | xdm.service | OpenRC常用的 xdm init.d 被 x11-base/xorg-server所取代。systemd所对应的 DM (gdm.service, kdm.service...) 需要被开启。 |
net-firewall/iptables | iptables | iptables-store.service | |
iptables-restore.service |
! scope="col" | Gentoo package ! scope="col" | OpenRC service ! scope="col" | systemd unit ! scope="col" | Notes |-
! scope="row" rowspan="28" | 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 |-
| scope="row" rowspan="2" | urandom | systemd-random-seed-load.service || |-
| systemd-random-seed-save.service || |-
! scope="row" | app-admin/rsyslog | rsyslog || rsyslog.service || |-
! scope="row" | app-admin/syslog-ng | syslog-ng || syslog-ng.service || |-
! scope="row" rowspan="2" | media-sound/alsa-utils | scope="row" rowspan="2" | alsasound | alsa-store.service || (enabled by default) |-
| alsa-restore.socket || (enabled by default) |-
! scope="row" | net-misc/dhcpcd | dhcpcd || dhcpcd.service || |-
! scope="row" rowspan="5" | net-misc/netifrc | scope="row" rowspan="5" | 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 |-
! scope="row" | net-misc/openntpd | ntpd || ntpd.service || |-
! scope="row" rowspan="2" | net-misc/openssh | scope="row" rowspan="2" | sshd | sshd.service || runs sshd as a daemon |-
| sshd.socket || runs sshd on a inetd-like basis (for each incoming connection) |-
! scope="row" rowspan="2" | net-wireless/wpa_supplicant | scope="row" rowspan="2" | 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) |-
! scope="row" rowspan="3" | net-print/cups | scope="row" rowspan="3" | cupsd | cups.service || classic on-boot start up service |-
| cups.socket | scope="row" rowspan="2" | socket and path activation (cups only started on-demand) |-
| cups.path |-
! scope="row" | net-wireless/bluez | bluetooth || bluetooth.service || |-
! scope="row" rowspan="2" | sys-apps/dbus | scope="row" rowspan="2" | dbus | dbus.service || |-
| dbus.socket || |-
! scope="row" | sys-apps/irqbalance | irqbalance || irqbalance.service || supports daemon mode only |-
! scope="row" | 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. |-
! scope="row" rowspan="4" | sys-fs/udev | udev || udev.service || |-
| udev-mount || (builtin) || /dev is mounted as tmpfs |-
| udev-postmount || udev-trigger.service || |-
| || udev-settle.service || |-
! scope="row" | sys-power/acpid | acpid || acpid.service || Most of its functionality is done by systemd itself, so consider disabling this |-
! scope="row" | 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. |-
! scope="row" rowspan="2" | net-firewall/iptables | scope="row" rowspan="2" | iptables | iptables-store.service || |-
| iptables-restore.service || |-
|}
User services
It is possible to manage services as a per-user systemd instance. This allows users to setup their own services or timers.
User units can be located at multiple places. Users are allowed to place them to $XDG_CONFIG_HOME/systemd/user/. Installed packages place them to /usr/lib/systemd/user/.
User services use --user
systemctl option. For example to start a mpd user service:
user $
systemctl --user start mpd
时间服务
自从197年版本的systemd,支持计时器,cron 没有必要安装到systemd系统上。212年版本以来持续性服务被支持,甚至取代了anacron。持久性计时器在下一次有机会当运行的系统断电后,计时器将列入计划任务。
以下是关于如何使运行在用户的环境下,制作简单定时器的一个例子。如果没有登录用户或会话运行。每一个定时服务需要一个定时器和一个服务文件,该文件是由定时器按如下激活的:
[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
[Unit]
Description=daily backup work
RefuseManualStart=no
RefuseManualStop=yes
[Service]
Type=oneshot
ExecStart=/home/<user>/scripts/backup-work.sh
These unit files can be created either manually or using the systemctl edit utility:
user $
systemctl edit --force --full --user backup-work.timer
When creating the unit files manually, the files are to be placed in the ~/.config/systemd/user directory. It may need to be created for the relevant user:
user $
mkdir -p ~/.config/systemd/user
To have a timer run while the user is not logged in, be sure to enable lingering sessions:
user $
loginctl enable-linger <username>
首先,告诉systemd要重新扫描服务文件:
user $
systemctl --user daemon-reload
可以手动触发备份功能,通过运行下面的命令:
user $
systemctl --user start backup-work.service
手动启动和停止计时器如下:
user $
systemctl --user start backup-work.timer
user $
systemctl --user stop backup-work.timer
最后,激活计时器在每一个系统都启动,运行:
user $
systemctl --user enable backup-work.timer
要检查正在运行的服务的最后结果:
user $
systemctl --user list-timers
电子邮件故障
如果一个定时服务运行和失败可以发送一封电子邮件通知用户或管理员。这是可能的“OnFailure”节,指定如果服务失败时会发生什么。检测到故障时由一个非零的返回代码调用脚本。
为了这个,改变脚本如下:
[Unit]
Description=daily backup work
RefuseManualStart=no
RefuseManualStop=yes
OnFailure=failure-email@%i.service
[Service]
Type=oneshot
ExecStart=/home/<user>/scripts/backup-work.sh
这要求服务failure-email@.service 被安装,它可以在 kylemanna's systemd-utils repository被找到。
替换 cron
上面的计时器和服务文件也可以被添加到/lib/systemd/system 让他们有可用的系统体系。安装部分那时应该说明WantedBy=multi-user.target
来系统启动启用服务。
然而, cron也可以通过位于/etc/cron.daily的脚本运行。以及其他的你希望的,日常运行的路径。这种行为可以通过安装 sys-process/systemd-cron仿真systemd。 然后用以下命令激活新cron替换:
root #
systemctl enable cron.target
root #
systemctl start cron.target
故障排除
Slow shutdowns or reboot times due to running services
- Problem
- Occasionally a systemd system or user service will cause the system to greatly delay poweroff/shutdown or reboot operation due to systemd default wait times for the operation blocking service to time out.
- Solution
- To greatly speed up this operation, the default timeout values can be reduced at the expense of the service (potentially) not cleanly finishing a task. In order to be effective, both of the following configuration changes must be put into effect to shorten the default timeout system and user services.
[Manager]
DefaultTimeoutStopSec=10s
[Manager]
DefaultTimeoutStopSec=10s
/dev/kmsg buffer overrun, some messages lost
- 问题:启动时系统会显示一个无限循环:
/dev/kmsg buffer overrun, some messages lost
。到控制台的登录屏幕永远不会出现这一问题,因为在启动过程中系统永远不会获取点。
- 解决方案 ︰ 大多数情况下,在内核中启用 CONFIG_POWER_SUPPLY_DEBUG 选项时,将会导致此问题。当前的解决方法是在内核中禁用此选项,然后重新编译,安装,并引导新的内核。也可以在Gentoo 论坛上找到解决办法 此线程 。根据一个用户一个论坛,[1] 嵌入式的系统上使用 I2C EEPROM 时,是也会出现此问题。解决办法在这种情况下是禁用 CONFIG_I2C_DEBUG_CORE 内核选项。
在任何地方打开图形会话
默认情况下,当systemd被使用时,它只启动一个getty进程,这会导致一些显示管理器(像GDM)使用剩余Tty来打开图形的会话,这会导致在控制台和图形会话无计划的放置,而这取决于它们的顺序使用。
保持更 "经典" 的行为 (i.e, 控制台将从tty1 到tty6,图形会话使用剩余的tty) 迫使他总是启动getty关于那些:
root #
systemctl enable getty@tty{2,3,4,5,6}.service
LVM
从OpenRC切换到systemd+LVM,你需要正确挂载系统卷并激活LVM服务:
root #
systemctl enable lvm2-monitor.service
虽然这可能并不需要激活根(root)卷(如果LVM集成到initramfs),它可能不适用于其他LVM卷,除非该服务被激活。
systemd-bootchart
确保 CONFIG_DEBUG_KERNEL, CONFIG_SCHED_DEBUG,和var>CONFIG_SCHEDSTATS 可用。
File systems --->
Pseudo filesystems --->
[*] /proc file system support
Kernel hacking --->
[*] Kernel debugging
[*] Collect scheduler debugging info
[*] Collect scheduler statistics
接下来使systemd-bootchart.service开机自启动:
root #
systemctl enable systemd-bootchart
这些变化的结果将生成一份位于/run/log/的SVG格式的bootchart报告。每次开机后,你都可以利用网络浏览器查看。
作为systemd-bootchart的替代,可以用以下命令查看
root #
systemd-analyze plot > plot.svg
syslog-ng关于 systemd 的资源
没有必要添加unix-dgram('/dev/log');
到 /etc/syslog-ng/syslog-ng.conf配置文件。它会造成 syslog-ng 运行错误 (最新版本syslog-ng-3.7.2会发生这个问题),更新 source src { ...; };
在syslog-ng article中提到到命令,如下:
# 默认为openrc配置
#source src { system(); internal(); };
# systemd
source src { systemd-journal(); internal(); };
sys-fs/cryptsetup配置
systemd似乎不遵守/etc/conf.d/dmcrypt (参见bug #429966)因此需要通过配置/etc/crypttab文件:
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.
检查未能启动的部分
检查未能启动的部分
root #
systemctl --failed
开启调式模式
得到更多信息,设置/etc/systemd/system.conf:
LogLevel=debug
或启用调试shell,在 tty9打开一个终端。这有助于在引导过程中调试服务。
root #
systemctl enable debug-shell.service
e4rat usage
请记得编辑/etc/e4rat.conf,设置'init' 到 /lib/systemd/systemd,否则它将继续使用OpenRC引导。
GRSecurity hardening
启用 grsecurity ,systemd-networkd可能记录有下面的错误:
could not find udev device: Permission denied
错误是因为 systemd-networkd 在非root用户环境下工作,对于这样的用户,使用 grsecurity 拒绝访问完成/sys结构。要禁用这个选项,禁用内核选项CONFIG_GRKERNSEC_SYSFS_RESTRICT 。
logind 可能也有些许的权限问题CONFIG_GRKERNSEC_PROC 事件,请看bug #472098.
shutdown -rF 不强制fsck
在需要时运行 fsck 需要启用服务systemd fsck 。它不依赖shutdown 的 -fF
选项,但相反它依赖以下的内核启动参数。
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.
|
! scope="col" width="15%" | Boot parameter ! scope="col" width="15%" | 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.
|-
|}
Optional systemd binaries
Many optional systemd binaries can be built by setting certain use flags. An incomplete mapping of USE flag to binary is below.
USE flag | Additional binary built |
---|---|
curl
|
/lib/systemd/systemd-journal-upload |
http
|
/lib/systemd/systemd-journal-gatewayd /lib/systemd/systemd-journal-remote |
另请参阅
- Comparison of init systems — compares and contrasts init systems for Unix(like) OSs
- Sakaki's EFI Install Guide - Particularly look at the chapter entitled Configuring systemd and installing necessary tools
- Packages that hard depend on systemd
- OpenRC to systemd Cheatsheet — list of commands commonly used in OpenRC and its equivalent systemd command.