The systemd of CentOS 7 replaces SysV's init with the great change

Source: Internet
Author: User
Tags call back change settings openssh server

1 Systemd is what first systmed is a user-space program, belongs to the application, is not part of the Linux kernel category, the main features of the Linux kernel are unified in all distributions, and the vendor can freely change the user-space application. After the Linux kernel load is started, the first process of user space is the initialization process, the physical file contract of this program is located in/sbin/init, of course, you can also pass the kernel parameters to let the kernel start the specified program. This process is characterized by a process number of 1, which represents the first user-space process to run. Different release versions adopt different startup programs, mainly have the following main choices: (1) The Linux distribution with Ubuntu as the representative upstart. (2) System V init represented by CentOS prior to version 7.0. (3) CentOS7.0 version of Systemd. The following is information about the initialization process for the CentOS6.5 and CentOS7 two versions. CentOS6.5 uses the SYSTEMV init CentOS7 is a systemd2 systemd physical file composition Systemd is a complete package, after the installation is completed there are many physical files, roughly distributed as, configuration files located in/etc/ Systemd This directory, the configuration Tools command is located in/bin, and/sbin, the pre-prepared standby configuration files are located in the/lib/systemd directory, as well as library files and help manuals, and so on. This is a huge package. Details can be viewed using RPM-QL systemd. Let's take a look at the contents of the current system/etc/inittab this file, which is a standard configuration file for Systme V Init, and now becomes:
# Inittab isNo longer used whenusingsystemd.## ADDING CONFIGURATION here would have NO EFFECT on YOUR system.## Ctrl-alt-delete isHandled by/etc/systemd/system/ctrl-alt-del.target## Systemd uses'Targets'Instead of Runlevels. Bydefault, there is the main targets:## multi-user.target:analogous to RunLevel3# graphical.target:analogous to RunLevel5# # toSetAdefaultTarget, run:## ln-sf/lib/systemd/system/<target name>.target/etc/systemd/system/default. Target

This shows that after systemd in power, Inittab no longer works, and there is no concept of "run-level". The configuration file that works now is/etc/systemd/system/default.target this file. The contents of this file are as follows:

# this file isPart of Systemd. # # SYSTEMD is  FreeSoftware; You can redistribute it and/or modify it # under the terms of the GNU Lesser general public License aspublished by # the free software Foundation; either version2.1of the License, or # (at your option) any later version.  [Unit] Description=multi-User System Documentation=man:systemd.special (7) Requires=Basic.target Conflicts=Rescue.service Rescue.target after=basic.target rescue.service rescue.target allowisolate=Yes [Install] Alias=default. Target
The systemd configuration file suffix differs depending on the hive type, mainly in. service,.target. 3 SYSTEMD Operation principle 3.1 The basic concept of SYSTEMD (1) Hive Unit system initialization to do a lot of work, such as hanging in the file system, start the SSHD service, configure the swap partition, which can be seen as a hive, SYSTEMD installation features separate the hive into multiple types.
    • Service descendant services processes, such as HTTPD,MYSQLD, etc.
    • Soket corresponds to a socket, which then corresponds to a service, similar to the XINETD function
    • A device that corresponds to a udev rule tag
    • A mount point in the Mount system, which is automatically mounted on the SYSTEMD, is now systemd automatically processed/etc/fstab and converted to mount for compatibility with SYSTEMV
    • AutoMount Automatic mount point
    • Swap configuration swap partition
    • The logical grouping of the target hive, which contains several related hive units, can be used as the run level in SYSTEMV.
    • Timer timers. Used to trigger user-defined actions on a timed basis, which can be used to replace traditional atd,crond.
    • Snapshot, similar to target, indicates the current running state
Each hive has a corresponding configuration file, and the system Administrator's task is to write and maintain a different configuration file, such as a MySQL service corresponding to a mysql.service file. (2) Dependency systemd does not completely disassociate dependencies between units, such as the impossibility of executing a mount unit until the physical device unit is ready. To do this, you define the dependencies between the individual cells. Where there is a dependency, there is the possibility of a dead loop, such as a dependent on b,b dependent on the c,c dependent on a, which leads to deadlock. Systemd This provides two different degrees of dependency, one is require, one is want, when there is a dead loop, SYSTEMD will try to ignore the want type of dependency, such as still cannot unlock, then systemd error. (3) Target and RunLevel said earlier that Systemd used target instead of SYSTEMV's run-level concept. Table 1. Sysvinit the corresponding table for the RunLevel and SYSTEMD targets
Sysvinit Run Level Systemd Target Notes
0 Runlevel0.target, Poweroff.target Shut down the system.
1, S, single Runlevel1.target, Rescue.target Single-user mode.
2, 4 Runlevel2.target, Runlevel4.target, Multi-user.target User-defined/domain-specific runlevel. The default is equal to 3.
3 Runlevel3.target, Multi-user.target Multi-user, non-graphical. Users can log on through multiple consoles or networks.
5 Runlevel5.target, Graphical.target Multi-user, graphical. Typically, all run Level 3 services plus graphical logins.
6 Runlevel6.target, Reboot.target Restart
Emergency Emergency.target Emergency Shell
3.2 Systemd Parallel Start principle

As mentioned earlier, in SYSTEMD, all services are started concurrently, such as Avahi, D-bus, LIVIRTD, X11, and HAL can start at the same time. At first glance, this seems to be a bit of a problem, such as Avahi need syslog service, Avahi and syslog start simultaneously, assuming Avahi start relatively fast, so the syslog is not ready, but Avahi need to log, this will not be a problem?

SYSTEMD's developers carefully examined the nature of the interdependencies between services, and found that the so-called dependencies can be divided into three specific types, each of which can actually be removed from the dependency by the appropriate technology.

One of the concurrent startup principles: Resolving socket dependencies

The overwhelming majority of service dependencies are socket dependent. For example, service a provides its own service through a socket port S1, and other services need to connect S1 if service A is required. Therefore, if service A is not started, S1 does not exist, and other services will get a startup error. So traditionally, people need to start service A, wait for it to go into a ready state, and start other services that need it. Systemd that as long as we set up S1 in advance, all other services can be started at the same time without waiting for service A to create the S1. If service A is not yet started, the service requests sent to S1 by other processes are actually cached by the Linux operating system, and other processes wait at the request. Once service A is ready, the cached request can be processed immediately, and everything starts to run normally.

So how does the service use sockets created by the INIT process?

The Linux operating system has a feature that when a process calls fork or exec creates a child process, all file descriptor that are opened in the parent process are inherited by the quilt process. A socket is also a file handle, and process a can create a socket, and then when process a calls exec to start a new child process, the new child process can inherit the socket as long as the CLOSE_ON_EXEC flag bit is cleared. The socket that the child process sees and the socket created by the parent process are the same system socket, as if the socket was created by the child process itself, without any distinction.

This feature was previously used by a system service called inetd. The INETD process is responsible for monitoring some common socket ports, such as Telnet, when the port has a connection request, INETD starts the telnetd process and passes the connected socket to the new telnetd process for processing. This way, you do not need to start the telnetd process when the system does not have a Telnet client connection. INETD can proxy a lot of network services, so that it can save a lot of system load and memory resources, only when there is a real connection request to start the corresponding service, and to pass the socket to the corresponding service process.

Similar to inetd, SYSTEMD is the parent process for all other processes, which can first establish all the required sockets and then pass the socket to the new service process when exec is called, while the new process uses the socket directly for service.

The second principle of concurrent booting: Resolving D-bus dependencies

D-bus is the abbreviation for Desktop-bus, which is a low-latency, low-overhead, high-availability interprocess communication mechanism. It is increasingly used for communication between applications, and also for communication between applications and operating system cores. Many modern service processes use D-bus instead of sockets as inter-process communication mechanisms to provide services externally. For example, the NetworkManager service that simplifies the Linux network configuration interacts with D-bus and other applications or services: The mail client software evolution can obtain changes to the network state through D-bus from the NetworkManager service in order to The corresponding processing.

D-bus supports the so-called "Bus Activation" feature. If service a needs to use service B's D-bus service, and service B is not running, D-bus can start service B automatically when service a requests service B's D-bus. The request from service A is D-bus cached and service a waits for service B to start ready. With this feature, D-bus-dependent services can be used to enable parallel booting.

The third principle of concurrent booting: Resolving file System Dependencies

During system startup, file system-related activity is the most time consuming, such as mounting the file system, disk checking on the file system (FSCK), disk quota checking, and so on are very time-consuming operations. While waiting for these jobs to complete, the system is in an idle state. Services that want to use the file system seem to have to wait for the file system to initialize before it can be started. But Systemd found that this kind of dependence can also be avoided.

SYSTEMD reference to the design of AutoFS, so that the dependent file system services and the file system itself initialization can work concurrently. AutoFS can monitor that a file system mount point is actually accessed to trigger a mount operation, which is implemented through the support of the kernel Automounter module. For example, when an open () system call is in "/misc/cd/file1",/MISC/CD has not yet performed a mount operation, when the open () call is pending, the Linux kernel notifies autofs,autofs to perform the mount. At this point, control is returned to the open () system call, and the file is opened normally.

SYSTEMD integrates the implementation of AutoFS, and for mount points in the system, such as/home, when the system starts, SYSTEMD creates a temporary automatic mount point for it. At this time/home real Mount device has not been started well, the real mount operation has not been executed, file system detection has not been completed. However, the processes that depend on the directory can already be started concurrently, and their open () operations are captured by AutoFS built into SYSTEMD, suspending the open () call (sleep state can be interrupted). Then wait for the real mount operation to complete, and after file system detection is complete, SYSTEMD replaces the automatic mount point with the true mount point and makes the open () call back. As a result, services that rely on the file system and the file system itself are implemented concurrently to start.

Of course, the "/" root of the dependency must still be serially executed, because the SYSTEMD itself is also stored in/under, you have to wait for the system root mount check.

However, similar to the home/home mount point, this concurrency can improve the system startup speed, especially when/home is a remote NFS node, or encryption disk, and so on, it takes a long time to be ready, because of the concurrent start, during this time, the system is not completely nothing to do, Instead, you can use this free time to do more of the startup process, which in general shortens the system startup time.

4 SYSTEMD configuration using 4.1 for system developers

Developers need to know more details about the SYSTEMD. For example, if you are going to develop a new system service, you must know how to make the service managed by SYSTEMD. This requires your attention to the following points:

    • The background service process code does not need to perform two derivation to implement the background daemon process, only the main loop of the service itself is implemented.
    • Do not call Setsid (), give SYSTEMD handle
    • It is no longer necessary to maintain PID files.
    • SYSTEMD provides logging capabilities, and the service process only needs to be output to stderr, without the use of syslog.
    • Processing signal SIGTERM, the only correct function of this signal is to stop the current service, do not do other things.
    • The function of the SIGHUP signal is to restart the service.
    • Services that require sockets, do not create sockets on their own and let Systemd pass in sockets.
    • Use the Sd_notify () function to notify the SYSTEMD service of its own state change. In general, it can be called when the service initialization is complete and enters the service-ready state.

For developers, the biggest part of the effort should be to write hive files that define the required units.

For example, a developer who developed a new service program, such as httpd, needs to write a hive file for it so that the service can be systemd managed, similar to upstart's work profile. In this file, you define the command-line syntax for the service to start, as well as dependencies on other services.

In addition, we have learned that Systemd has a wide range of functions, not only for managing services, but also for managing mount points, defining timed tasks, and more. The work is done by editing the corresponding hive file. Here's an example of a few hive files I'm giving you here.

The following is the configuration unit file for the SSH service, the service hive file with the. Service as the file name suffix.

  #cat/etc/system/system/sshd.service  [Unit]  description=openssh Server daemon  [service]  Environmentfile=/etc/sysconfig/sshd  Execstartpre=/usr/sbin/sshd-keygen  execstart=/usrsbin/sshd–d $ OPTIONS  execreload=/bin/kill–hup $MAINPID  killmode=process  restart=on-failure  restartsec=42s  [Install]  Wantedby=multi-user.target

The file is divided into three sections. The first one is the [Unit] section, where there is only one descriptive message. The second part is the service definition, where Execstartpre defines the commands that should be run before starting the service; Execstart defines the specific command-line syntax for starting the service. The third part is [Install],wangtedby indicates that the service is required in multi-user mode.

Let's take a look at the Multi-user.target:

  #cat multi-user.target  [Unit]  description=multi-user System  documentation=man.systemd.special (7)  Requires=basic.target  Conflicts=rescue.service rescure.target  after=basic.target rescue.service rescue.target  AllowIsolate=yes  [Install]  Alias=default.target

The Requires definition in the first section indicates that Basic.target must also be started when Multi-user.target is started, and Multi-user.target must stop when Basic.target is stopped. If you continue to view the Basic.target file, you will find that it also specifies that other cells such as Sysinit.target must be started with it. The same sysinit.target will also contain other units. With such a layer-by-layer link structure, all Component Services that need to support multi-user mode will eventually be initialized.

In the [Install] section there is an alias definition, which defines the alias of this unit so that you can use this alias to refer to this unit when you run SYSTEMCTL. The alias here is Default.target, more simple than multi-user.target ...

Also in the/etc/systemd/system directory you can see directories such as *.wants, where the hive file is equivalent to the wants keyword in the [unit] subsection, which is required to start the unit when it starts. For example, you can simply put your own foo.service files into the multi-user.target.wants directory, so that each time it will be started by default.

Finally, let's take a look at the Sys-kernel-debug.mout file, which defines a file mount point:

#cat Sys-kernel-debug.mount[unit]description=debug File systedefaultdependencies=noconditionpathexists=/sys/ Kernel/debugbefore=sysinit.target[mount]what=debugfswhere=/sys/kernel/debugtype=debugfs

This hive file defines a mount point. The Mount hive file has a [Mount] configuration section, which is configured with What,where and Type three data items. This is all necessary to mount the command, and the configuration in the example is equivalent to the following Mount command:

Mount–t Debugfs/sys/kernel/debug Debugfs

The preparation of the hive file requires a lot of learning, and you must refer to the man document included with SYSTEMD for further study. I hope that through the above few small examples, you already understand the role of the hive file and the general wording.

4.2 The primary tool for system Administrator system administrators is systemctl.

Most administrators should already be familiar with the management of system services and INIT systems, such as service, Chkconfig, and Telinit commands. SYSTEMD also accomplishes the same management tasks, except that the syntax of the command tool Systemctl is different, so it is clear to use tables to compare SYSTEMCTL and traditional system administration commands.

Table 2. Comparison of Systemd command and Sysvinit command
sysvinit Command Systemd Command Notes
Service Foo Start Systemctl Start Foo.service Used to start a service (does not restart the existing one)
Service Foo Stop Systemctl Stop Foo.service Used to stop a service (and not restart the existing one).
Service Foo Restart Systemctl Restart Foo.service Used to stop and start a service.
Service Foo Reload Systemctl Reload Foo.service When supported, remount the configuration file without interrupting the wait operation.
Service Foo Condrestart Systemctl Condrestart Foo.service If the service is running then restart it.
Service Foo Status Systemctl Status Foo.service Reports whether the service is running.
ls/etc/rc.d/init.d/ Systemctl List-unit-files--type=service Used to list the services that can be started or stopped.
Chkconfig foo on Systemctl Enable Foo.service Setting the service to Enabled at the next startup or when other trigger conditions are met
Chkconfig foo off Systemctl Disable Foo.service Setting the service to disabled at the next startup or when other trigger conditions are met
Chkconfig Foo Systemctl is-enabled Foo.service Used to check whether a service is configured to be enabled or disabled in the current environment.
Chkconfig–list Systemctl List-unit-files--type=service Output enabled and disabled for the service under each run level
Chkconfig foo–list Ls/etc/systemd/system/*.wants/foo.service Use to list which run levels the service is enabled and disabled under.
Chkconfig Foo–add Systemctl Daemon-reload Used when you create a new service file or change settings.
Telinit 3 Systemctl isolate Multi-user.target (or Systemctl isolate Runlevel3.target OR telinit 3) Change the maximum user run level.

In addition to the common uses listed in table 2, system administrators need to be aware of other changes in system configuration and management tasks.

First we understand how SYSTEMD handles power management, and the command is shown in the following table:

Table 3,SYSTEMD Power Management commands
Command Operation
Systemctl reboot Restarting the machine
Systemctl Poweroff Shutdown
Systemctl suspend Standby
Systemctl Hibernate Dormancy
Systemctl Hybrid-sleep Mixed sleep mode (simultaneously hibernate to hard drive and standby)

The shutdown is not performed by every logged-on user under any circumstances, and is generally only available to administrators. Under normal circumstances, the system should not allow SSH Telnet users to perform shutdown commands. Otherwise, other users are working, and a user shutting down the system is not good. To solve this problem, traditional Linux systems use Consolekit to track user logins and decide whether to give them permission to shut down. Now Consolekit has been replaced by Systemd's logind.

Logind is not a pid-1 init process. Its role is similar to the upstart session INIT, but it is much more versatile, and it manages almost all user sessions (session) related things. Logind is not only an alternative to Consolekit, it can:

    • Maintain, track sessions and user logins. As mentioned above, in order to determine whether the shutdown command is feasible, the system needs to know the current user logon situation, if the user logged in from SSH, do not allow the shutdown command, if the ordinary user logged on locally, and the user is the only session in the system, it is allowed to execute the shutdown command; these judgments all require logind Maintains all user sessions and logon situations.
    • Logind is also responsible for counting user sessions for a long time without action, and can perform actions such as hibernation/shutdown.
    • Create CGroup for all processes of the user session. This not only facilitates the statistics of all user sessions related processes, but also enables session-level system resource control.
    • Responsible for the power management of the combination of key processing, such as the user to press the power button to switch the system to sleep state.
    • Multi-seat (multi-seat) management. Today's computers, even a laptop, can provide the computing power that many people use at the same time. Multi-seat is a computer host to manage multiple peripherals, such as two screens and two mouse/keyboard. Seat one uses screen 1 and keyboard 1; seats two use screen 2 and keyboard 2, but they all share a single host. User sessions are free to switch between multiple seats. or when inserting a new keyboard, screen and other physical peripherals, automatically start the GDM user login interface and so on. All of these are multi-seat management content. Consolekit has never implemented this feature, SYSTEMD's logind can support multiple seats.
These management functions described above are only part of the SYSTEMD function, in addition, SYSTEMD is also responsible for other system management configuration, such as configuration network, Locale management, management system kernel module loading and so on. 5 Summary

In the author's view, as a system initialization system, SYSTEMD has the greatest features of two:

    • Surprisingly aggressive concurrent start-up capability, greatly improving the system boot speed;
    • Tracking sub-process with CGroup statistics, clean and reliable.

Moreover, unlike its predecessor, SYSTEMD is more than just an initialization system.

SYSTEMD is an excellent substitute for all the features of Sysvinit, but it is not complacent. Because the init process is so specific to the parent process of all processes in the system, SYSTEMD is well suited to provide functionality that was once provided by other services, such as timed tasks (previously completed by Crond), Session Management (formerly managed by Consolekit/polkit, etc.). Just from the fur of the introduction of this article, SYSTEMD has been a lot of control, 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.

The good thing is, this is very helpful for standardizing Linux management! In the past, different Linux distributions used different methods to manage the system and never compromised each other. For example, how to put the system into hibernation, different systems have different solutions, even the same Linux system, there are different methods, such as an interesting discussion: How to hibernate the Ubuntu system, you can use the underlying/sys/power/state interface, you can also use such as Pm-utility and other high-level interfaces. There are so many different ways to do something that is not an interesting thing for a normal user like me. SYSTEMD provides a unified power Management command interface, the meaning of this thing is similar to people all over the world speak unified language, we no longer need to learn a foreign language, how beautiful!

If all Linux distributions incorporate SYSTEMD, system administration tasks can be standardized to a large extent. In addition, SYSTEMD has a great commitment: the interface remains stable and will not be easily altered. For software developers, this is a very thoughtful and moving commitment Ah!

The systemd of CentOS 7 replaces SysV's init with the great change

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.