Systemd Management in CentOS 7
CentOS system startup process:
POST --> Boot Sequence --> Bootloader --> kernel + initramfs (initrd) --> rootfs -->/sbin/init
Innit program:
CentOS 5: SysV init
CetnOS 6: Upstart
CentOS 7: Systemd
New Features of Systemd:
System Sys V init and LSB init scripts are compatible
During system boot, services are started concurrently. socket/D-Bus activation and other technologies are used to start services. To reduce the system startup time, systemd aims to start fewer processes as much as possible; start more processes in parallel as much as possible;
On-demand activation of processes; Systemd can provide on-demand startup capabilities, which can be started only when a service is actually requested. When the service ends, systemd can disable it and wait for it to start again when needed.
Able to take snapshots and restore the system;
Start the management of Mount Points and automatic mount points:
Systemd manages mount points on the system to automatically mount them when the system starts. Compatible with/etc/fstab files;
Implement transaction dependency management:
Systemd maintains a "transaction consistency" concept to ensure that all related services can be started normally without mutual dependency, so that deadlocks occur.
Define Service Control Logic Based on endogenous dependency;
System uses the Linux kernel feature CGroup to complete process tracking tasks. When the service is stopped, you can query the CGroup. systemd can ensure that all related processes are found to stop the service cleanly;
Log Service: systemd comes with the Log Service journald. The log service was designed to overcome the shortcomings of the existing syslog service.
Basic concepts of System
Unit concept:
Many tasks need to be done during system initialization. You need to start background services, such as SSHD services, and configuration work, such as mounting a file system. Every step in this process is abstracted as a Configuration unit by systemd. You can consider a service as a Configuration unit, a mount point as a Configuration unit, and a swap partition as a Configuration unit. Systemd summarizes the configuration units into the following types. However, systemd is developing rapidly and new features are constantly increasing. Therefore, the configuration unit type may continue to increase in the near future.
Service: represents a background service process, such as mysqld. This is a common type;
Socket: This Configuration unit encapsulates a socket in the system and the Internet. Currently, systemd supports stream, packet, and continuous packet AF_INET, AF_INET6, and AF_UNIX socket. Each socket Configuration unit has a corresponding service configuration unit. The corresponding service is started when the first "connection" enters the socket (for example, nscd. socket starts nscd. service after a new connection ).
Device: This type of Configuration unit encapsulates a device that exists in the Linux device Tree. Every device marked with the udev rule will appear as a device configuration unit in systemd.
Mount: This Configuration unit encapsulates a mount point in the file system structure level. Systemd will monitor and manage this mount point. For example, it can be automatically mounted at startup; it can be automatically detached under certain conditions. Systemd converts entries in/etc/fstab to mount points and processes them at startup.
Automount: This type of Configuration unit encapsulates a self-mount point in the system structure level. Each custom Mount Configuration unit corresponds to a mount Configuration unit. When the automatic mount point is accessed, systemd executes the Mount behavior defined in the mount point.
Swap: similar to mounting a Configuration unit, a switch configuration unit is used to manage swap partitions. You can use swap configuration units to define swap partitions in the system so that these swap partitions can be activated at startup.
Target: This type of Configuration unit is another Configuration unit for logical grouping. They do not actually do anything, but reference other configuration units. In this way, the configuration unit can be controlled in a unified manner. In this way, the running level concept that everyone is very familiar with can be implemented. For example, to enable the system to enter the graphical mode, you need to run many services and configuration commands. These operations are represented by configuration units, and all these configuration units are combined into a target ), it means you need to execute all these configuration units to enter the system running status represented by the target. (For example, multi-user.target is equivalent to running level 3 in systems that traditionally use SysV)
Timer: the timer Configuration unit is used to regularly trigger user-defined operations. This type of Configuration unit replaces traditional scheduled services such as atd and crond.
Snapshot: similar to the target Configuration unit, a snapshot is a group of configuration units. It saves the current running status of the system.
Dependency:
Although systemd removes Dependencies from a large number of startup tasks so that they can be started concurrently. However, there are still some tasks that are inherently dependent on each other and cannot be activated using "socket activation) three methods, D-Bus activation and autofs, are used to remove dependencies. (For details about the three methods, see the subsequent descriptions ). For example, the mount point must be created in the file system and the mount point must be ready for the corresponding physical device. To solve such dependency problems, the configuration units of systemd can define dependencies between each other.
Systemd uses keywords in the configuration unit definition file to describe the dependencies between configuration units. For example, unit A depends on unit B, which can be expressed by "require A" in the definition of unit B. In this way, systemd ensures that A is started before B is started.
Systemd transaction:
Systemd can ensure transaction integrity. The transaction concept of Systemd is different from that in databases, mainly to ensure that there is no circular reference between multiple dependent configuration units. If cyclic dependency exists, systemd cannot start any service. In this case, systemd will try to solve this problem, because there are two dependency relationships between configuration units: required is a strong dependency, and want is a weak dependency, systemd removes the dependency specified by the wants keyword to see if the loop can be broken. If it cannot be repaired, systemd reports an error.
Systemd can automatically detect and fix such configuration errors, greatly reducing the burden on administrators.
Target and running level:
Systemd replaces the concept of running level with target, providing greater flexibility. For example, you can inherit an existing target and add other services to create your own target. The following table lists the mappings between targets and common runlevels in systemd:
SystemdConcurrent startup principle
As mentioned above, in Systemd, all services are started concurrently. For example, Avahi, D-Bus, libaid, X11, and HAL can be started simultaneously. At first glance, this seems a bit problematic. For example, Avahi needs the syslog service. Avahi and syslog are started at the same time. If Avahi is started faster, syslog is not ready yet, but does Avahi need to record logs?
Developers of Systemd carefully studied the essential issue of service dependency, and found that the so-called dependency can be divided into three specific types, and each type can actually lift the dependency through the corresponding technology.
The vast majority of service dependencies are socket dependencies. For example, service A provides its own services through A socket port S1, and other services need to connect to S1. Therefore, if service AIS not started, S1 does not exist, and other services will receive startup errors. Therefore, traditionally, You need to first start service A, wait for it to enter the ready state, and then start other services that need it. According to Systemd, As long as S1 is established in advance, all other services can be started at the same time without waiting for service A to create S1. If the service AIS not started, the service requests sent by other processes to S1 will be cached by the Linux operating system, and other processes will wait for the request. Once service A is started, it can process cached requests immediately and everything starts to run normally.
So how does the service use the socket created by the init process?
The Linux operating system has a feature. After a process calls fork or exec to create a sub-process, all the opened file handles (file descriptor) in the parent process are inherited by the process. A socket is also A file handle. process A can create A socket. After that, when process A calls exec to start A new sub-process, make sure that the close_on_exec flag of the socket is cleared, then the new sub-process can inherit the socket. The socket seen by the sub-process and the socket created by the parent process are the same system socket, as if this socket was created by the sub-process itself, there is no difference.
This feature was previously used by a system service called inetd. The Inetd process monitors common socket ports, such as Telnet. When the port has connection requests, inetd starts the telnetd process, and pass the connected socket to the new telnetd process for processing. In this way, you do not need to start the telnetd process when the system does not have a telnet client connection. Inetd can act as a proxy for many network services, which can save a lot of system load and memory resources. Only when there is a real connection request can the corresponding service be started, and pass the socket to the corresponding service process.
Similar to inetd, systemd is the parent process of all other processes. It can first establish all required sockets and then pass the socket to the new service process when exec is called, the new process directly uses this socket for service.
D-Bus is short for desktop-bus. It is a low-latency, low-overhead, and high-availability inter-process communication mechanism. It is increasingly used for communications between applications and the operating system kernel. Many modern service processes use D-Bus instead of socket as the inter-process communication mechanism to provide external services. For example, the NetworkManager service that simplifies Linux network configuration uses D-Bus to interact with other applications or services: the email client software evolution can use D-Bus to obtain network status changes from the NetworkManager service for corresponding processing.
D-Bus supports the so-called "busactivation" function. If service A needs to use the D-Bus service of Service B, and service B does not run, then, D-Bus can automatically start service B when service A requests Service B's D-Bus. The request sent by service A will be cached by D-Bus, and service A will wait for service B to start up. With this feature, services dependent on D-Bus can be started in parallel.
During system startup, file system-related activities are the most time-consuming, such as mounting a file system, checking the file system disk (fsck), and checking the disk quota. The system is idle while waiting for the work to be completed. Services that want to use the file system seem to have to wait until the file system initialization is complete. However, systemd finds that this dependency can also be avoided.
According to The autofs design idea, Systemd enables concurrent work between services dependent on file systems and file system initialization. Autofs can trigger the Mount operation only when a file system mount point is accessed. This is achieved through the support of the kernel automounter module. For example, when an open () system is called for "/misc/cd/file1", the/misc/cd has not been attached, and the open () call is suspended for waiting, the Linux kernel notifies autofs that autofs is mounted. At this time, the control is returned to the open () system call and the file is opened normally.
Systemd integrates the implementation of autofs. For mount points in the system, such as/home, when the system is started, systemd creates a temporary automatic mount point for it. At this moment, the real mount device of/home has not been started, the real Mount operation has not been executed, and the file system detection has not been completed. However, the processes that depend on the directory can be started concurrently. Their open () operations are captured by autofs built in systemd and the open () call is suspended (which can interrupt sleep ). Then, wait for the actual mounting operation to complete. After the file system detection is complete, systemd replaces the automatic mount point with the actual mount point and allows open () to call and return. As a result, services that depend on the file system and the file system itself are started concurrently.
Of course, the dependency on the "/" root directory must be serialized, because systemd itself is also stored under/and must wait for the system root directory mounting check.
However, for mount points like/home, this concurrency can increase the system startup speed, especially when/home is a remote NFS node or encrypted disk, it takes a long time for the system to be ready. Because of the concurrent startup, the system does not have nothing to do during this period of time, instead, you can use this free time to start more processes. In general, the system startup time is shortened.
SystemdUse
The following describes the use of systemd for different roles of technicians. This article will only give a brief description to give you a rough understanding of the use of systemd. There are too many details, that is, they cannot be fully written in a short article. You also need to read the systemd documentation on your own.
UnitFile Compilation
Developers have developed a new service program, such as httpd, and they need to write a configuration single-element file for it so that the service can be managed by systemd, similar to the UpStart work configuration file. In this file, define the command line syntax for Service Startup and dependencies with other services.
In addition, we have learned that systemd has a wide range of functions, not only for service management, but also for managing mount points and defining scheduled tasks. These tasks are completed by editing the corresponding configuration single-element file. Here are several examples of configuring a single-element file.
The following is the configuration meta file of the SSH service. The service configuration meta file is suffixed with. service as the file name.
[root@kalaguiyinsystem]
#cat/usr/lib/systemd/system/sshd.service
[Unit]
Description=OpenSSHserverdaemon
After=network.targetsshd-keygen.service
Wants=sshd-keygen.service
# [Unit], description
[Service]
EnvironmentFile=
/etc/sysconfig/sshd
ExecStart=
/usr/sbin/sshd
-D$OPTIONS
ExecReload=
/bin/kill
-HUP$MAINPID
KillMode=process
Restart=on-failure
RestartSec=42s
# [Service] definition. ExecStartPre defines the commands that should be run before starting the service;
# ExecStart defines the specific command line syntax for starting the service.
[Install]
WantedBy=multi-user.target
# [Install]: WangtedBy indicates that this service is required in multi-user mode.
Let's take a look at Multi user.tar get:
[root@kalaguiyinsystem]
#catmulti-user.target
[Unit]
Description=Multi-UserSystem
Documentation=
man
:systemd.special(7)
Requires=basic.target
Conflicts=rescue.servicerescue.target
After=basic.targetrescue.servicerescue.target
AllowIsolate=
yes
Rollback get must also be stopped. If you connect to your basic.targetfile, you will find that other units, such as sysinit.tar get, must be started. Similarly, sysinit.tar get also contains other units. Using this layer-by-layer link structure, all component services that require multi-user mode are initialized and started.
[Install]
Alias=default.target
# Alias definition: defines the Alias of the current Unit. In this way, you can use this Alias to reference the current unit when running systemctl.
In addition, you can see the directory * in the/etc/systemd/system directory *. the configuration single-element file in the wants directory is equivalent to the wants keyword in the [Unit] section, that is, these units need to be started when the Unit is started. For example, you can simply put the foo.servicefile you wrote in the Multi user.tar get. wants directory so that it will be started by default each time.
[root@kalaguiyinsystem]
#pwd
/etc/systemd/system
[root@kalaguiyinsystem]
#ls
basic.target.wantsdisplay-manager.service
bluetooth.target.wantsgetty.target.wants
dbus-org.bluez.servicegraphical.target.wants
printer.target.wantssockets.target.wants
spice-vdagentd.target.wantsdefault.targetsysinit.target.wantsdefault.target.wants
Let's look at the sys-kernel-debug.mout file, which defines a file mount point:
[root@kalaguiyinsystem]
#cat
sys-kernel-debug.
mount
[Unit]
Description=DebugFileSystem
Documentation=https:
//www
.kernel.org
/doc/Documentation/filesystems/debugfs
.txt
Documentation=http:
//www
.freedesktop.org
/wiki/Software/systemd/APIFileSystems
DefaultDependencies=no
ConditionPathExists=
/sys/kernel/debug
Before=sysinit.target
[Mount]
What=debugfs
Where=
/sys/kernel/debug
Type=debugfs
This configuration Metafile defines a mount point. The Mount configuration single-element file has a [Mount] configuration section, which contains three data items: What, Where, and Type. This is required by the mount command. The configuration in this example is equivalent to the following mount command:
Mount-t debugfs/sys/kernel/debug debugfs
SystemdSystem Management:
The main command line tool of systemd is systemctl.
Most administrators should be familiar with system services and init system management, such as the use of service, chkconfig, and telinit commands. Systemd also completes the same management task, but the syntax of the command tool systemctl is different.
Start the service
Systemctl start httpd. service1:
Stop Service
Systemctl stop httpd. service2:
Restart service
Systemctl restarthttpd. service3:
Heavy Load Service
systemctlreloadhttpd.service
Conditional restart
systemctlcondrestarthttpd.service
View status
systemctlstatushttpd.service
Lists services that can be started or stopped.
systemctllist-unit-files–
type
=service
Set the service to start at startup
chkconfighttpdon
systemctlenablehttpd.service
Cancel service startup;
systemctldisablehttpd.service
Check whether a service is enabled or disabled in the current environment.
systemctlis-enabledhttpd.service;
echo
$?
Enable and disable services at various running levels
systemctllist-unit-files–
type
=service
Lists the running levels at which a service is enabled or disabled.
ls
/etc/lib/systemd/system/
*.wants
/httpd
.service
Change the user running level:
systemctlisolatemulti-user.target
Multi-user.target = 3rd run level
Graphical.tar get = 5th running level
Runlevel3.targetsymbol link, pointing to multi user.tar get
Runlevel5.targetsymbol link, pointing to graphical.tar get
Change the default running level:
[root@kalaguiyinsystem]
#systemctlset-defaultmulti-user.target
rm
'/etc/systemd/system/default.target'
ln
-s
'/usr/lib/systemd/system/multi-user.target'
'/etc/systemd/system/default.target'
The essence of the above operations is to delete/usr/lib/systemd/system/default.tar get, and then link the target file at the target level to the/etc/systemd/system/default.tar get file;
Systemd is more than just an initialization system:
SystemdAlso responsible for other management configurations of the system, such as configuring the network,LocaleManagement, management system kernel module loading, etc.
Systemd is an excellent replacement for all functions of sysvinit, but it is not complacent. Because the init process is the parent process of all processes in the system, systemd is very suitable for providing functions that were previously provided by other services, such as scheduled tasks (previously completed by crond ); session management (previously managed by ConsoleKit/PolKit ). Just as described in this article, Systemd has been managed a lot, but it is still evolving. It will gradually become a multi-functional system environment, able to handle a lot of system management tasks, some people even regard it as an operating system. This helps standardize Linux management!