Guide |
The traditional Linux system start-up process is mainly handled by the famous Init process (also known as the SYSV init boot system), and the Init-based boot system is considered an issue of insufficient efficiency, SYSTEMD is another way to start the Linux system machine, Claims to compensate for the shortcomings of the system based on the traditional Linux SysV init; SYSTEMD is used to start the daemon, which has become the standard configuration for most distributions, and after learning the SYSTEMD command, you will find systemd very powerful. |
The SYSTEMD features are:
- Support for parallelization tasks
- At the same time, socket-type and d-bus-bus activation service are adopted.
- Start daemon on demand (daemon);
- Utilize Linux's cgroups monitoring process;
- Support snapshot and system recovery;
- Maintain mount points and automatic mount points;
- Precision control based on dependencies between services.
first, the Origin
Historically, Linux has been started with the Init process, and the following commands are used to start the service.
$ sudo/etc/init.d/apache2 start# or service apache2 start
There are two drawbacks to this approach:
First, the boot time is long. The init process is serial-initiated, and the next process starts only when the previous process starts.
Second, the startup script is complex. The init process simply executes the startup script, no matter what else. Scripts need to handle a variety of situations themselves, which often makes the script very long.
ii. Overview of Systemd
Systemd was born to solve these problems. It is designed to provide a complete set of solutions for system startup and management, according to Linux conventions, the letter D is the abbreviation of the Daemon (daemon), and the meaning of systemd is that it protects the entire system.
(For SYSTEMD author Lennart Poettering)
With SYSTEMD, you don't need to use init again. SYSTEMD replaces INITD as the first process of the system (PID equals 1), and the other processes are its child processes.
$ systemctl--version #命令查看Systemd的版本.
SYSTEMD's advantages are powerful, easy to use, the drawback is the system is huge, very complex. In fact, many people now oppose the use of systemd, on the grounds that it is too complex to be strongly coupled with other parts of the operating system, violating the UNIX philosophy of "keep simple, keep stupid".
(for SYSTEMD architecture diagram)
third, System management
SYSTEMD is not a command, but a set of commands that relate to all aspects of system administration.
3.1 Systemctl is Systemd's main command for managing systems
#重启系统 $ sudo systemctl reboot# shut down system, cut power $ sudo systemctl poweroff#cpu stop working $ sudo systemctl halt# pause system $ sudo systemctl suspend# Let the system enter hibernation state $ sudo systemctl hibernate# let the system enter the interactive hibernation state $ sudo systemctl hybrid-sleep# boot into the rescue state (single user state) $ sudo systemctl rescue
3.2 systemd-analyze command for viewing startup time
#查看启动耗时 $ systemd-analyze #查看每个服务的启动耗时 $ systemd-analyze blame# Show waterfall-like start process flow $ systemd-analyze critical-chain# Displays the start stream for the specified service $ systemd-analyze critical-chain Atd.service
3.3 hostnamectl command to view information for the current host
#显示当前主机的信息 $ hostnamectl# To set the host name. $ sudo hostnamectl set-hostname rhel7
3.4 localectl command to view localization settings
#查看本地化设置 $ localectl# to set localization parameters. $ sudo localectl set-locale lang=en_gb.utf8$ sudo localectl set-keymap en_gb
3.5 timedatectl command to view the current time zone settings
#查看当前时区设置 $ timedatectl# Show all available time zones $ timedatectl list-timezones #设置当前时区 $ sudo timedatectl set-timezone america/new_ york$ sudo timedatectl set-time yyyy-mm-dd$ sudo timedatectl set-time HH:MM:SS
3.6 loginctl command to view the currently logged on user
#列出当前session $ loginctl list-sessions# list the currently logged on user $ loginctl list-users# list displays information for the specified user $ loginctl show-user ruanyf
Iv. Unit
4.1 Meanings
SYSTEMD can manage all system resources, the different resources collectively referred to as Unit (units), the unit is divided into the following 12 kinds.
Service Unit: System Services
Target Unit: A group consisting of multiple units
Device Unit: Hardware Device
Mount Unit: mount point for file system
AutoMount Unit: Auto mount point
Path Unit: File or path
Scope Unit: External process not initiated by SYSTEMD
Slice Unit: Process Group
Snapshot unit:systemd snapshot, can be cut back to a snapshot
Socket unit: Socket for interprocess communication
Swap Unit:swap File
Timer Unit: Timer
The Systemctl list-units command can view all the unit of the current system.
#列出正在运行的Unit $ systemctl list-units# lists all the unit, including no configuration file found, or startup failed $ systemctl list-units--all# lists all unit$ systemctl that are not running List-units--all--state=inactive# Lists all load-failed unit$ systemctl list-units--failed# lists all running, type-service unit$ Systemctl List-units--type=service
4.2 Status of the unit
The SYSTEMCTL status command is used to view the state of the system and the status of a single unit.
#显示系统状态 $ systemctl status# Displays the status of a single unit of $ SYSYSTEMCTL status bluetooth.service# displays the status of a unit of a remote host $ systemctl-h [email Protected] Status Httpd.service
In addition to the status command, SYSTEMCTL provides a simple way to query the state of three, primarily for use within the script's internal judgment statements.
#显示某个Unit是否正在运行 $ systemctl is-active application.service# shows if a unit is in a startup failure state $ systemctl is-failed Application.service #显示某个Unit服务是否建立了启动链接 $ systemctl is-enabled application.service
4.3 Unit Management
For users, the following commands are most commonly used to start and stop the unit (primarily service).
#立即启动一个服务 $ sudo systemctl start apache.service# immediately stop a service $ sudo systemctl stop apache.service# Restart a service $ sudo systemctl Restar T apache.service# kills all child processes of a service $ sudo systemctl kill apache.service# Reload a service profile $ sudo systemctl reload apache.service# Reload all modified profiles $ sudo systemctl daemon-reload# Show all underlying parameters of a unit $ SYSTEMCTL show httpd.service# show value of a unit's specified property $ systemctl sh Ow-p cpushares httpd.service# Setting the specified property of a Unit $ sudo systemctl set-property httpd.service cpushares=500
4.4 Dependencies
There is a dependency between the unit: a depends on B, which means that the systemd starts at a and starts B.
The Systemctl list-dependencies command lists all dependencies for a unit.
$ systemctl list-dependencies Nginx.service
In the output of the above command, some dependencies are target types (see below), which are not displayed by default. If you want to expand target, you need to use the--all parameter.
$ systemctl list-dependencies--all Nginx.service
v. Configuration file for unit
5.1 Overview
Each unit has a configuration file that tells Systemd how to start the unit.
Systemd reads the configuration file from the directory/etc/systemd/system/by default. However, most of the files stored inside are symbolic links, pointing to the directory/usr/lib/systemd/system/, and the real configuration files are stored in that directory.
The Systemctl enable command is used to establish a symbolic link relationship between the above two directories.
$ sudo systemctl enable [email protected] #等同于 $ sudo ln-s '/usr/lib/systemd/system/[email protected] '/etc/systemd/syste M/multi-user.target.wants/[email protected] '
If the configuration file is set to boot, the Systemctl enable command is equivalent to activating boot, corresponding to the Systemctl Disable command is used to remove the symbolic link relationship between two directories, which is equivalent to revoking the boot boot.
$ sudo systemctl disable [email protected]
The suffix name of the configuration file is the type of the unit, such as Sshd.socket; if omitted, the systemd default suffix is. Service, so sshd is interpreted as sshd.service.
5.2 Status of the configuration file
The Systemctl list-unit-files command is used to list all configuration files.
#列出所有配置文件 $ systemctl list-unit-files# lists the profile of the specified type $ systemctl list-unit-files--type=service
This command will output a list.
$ systemctl list-unit-filesunit FILE statechronyd.service enabled[email protected] Static[email Protected] disabled
This list shows the status of each profile, with a total of four.
Enabled: A startup link has been established
Disabled: No startup link established
Static: The configuration file does not have a [Install] section (cannot be executed) and can only be relied upon for other configuration files
Masked: The configuration file is blocked from establishing a startup link
Note that the status of the configuration file cannot be seen whether the Unit is running. This must perform the Systemctl status command mentioned earlier.
$ SYSTEMCTL Status Bluetooth.service
Once the configuration file is modified, let SystemD reload the configuration file and restart it, otherwise the modification will not take effect.
$ sudo systemctl daemon-reload$ sudo systemctl restart Httpd.service
5.3 Format of the configuration file
A configuration file is an ordinary text file that you can open with a text editor.
The Systemctl Cat command can view the contents of a configuration file. $ systemctl cat atd.service[unit]description=atd Daemon[service]type=forkingexecstart=/usr/bin/atd[install] Wantedby=multi-user.target
As you can see from the above output, the configuration file is divided into chunks. The first row of each chunk is a distinguished name in square brackets, such as [Unit]. Note that the chunk name and field name of the configuration file are case-sensitive.
Inside each chunk are key-value pairs that are connected by an equals sign.
[Section] Directive1=valuedirective2=value
Note that a key-value pair cannot have spaces on either side of the equal sign.
5.4 block of configuration files
The [Unit] block is usually the first chunk of the configuration file, which defines the unit's metadata and configures the relationship with the other unit. Its main fields are as follows.
Description: Short Description
Documentation: Document Address
Requires: The other unit on which the unit is currently dependent, if they are not running, the current unit will fail to start
Wants: The other unit that mates with the current unit, if they are not running, the current unit does not start failing
Bindsto: Similar to requires, the unit specified by it exits, causing the current unit to stop running
Before: If the unit specified in this field is to be started, it must be started after the current unit
After: If the unit specified by the field is to be started, it must be started before the current unit
Conflicts: The unit specified here cannot be run concurrently with the current unit
Condition ... : The current unit operation must meet the conditions, otherwise it will not run
Assert... : The current unit operation must meet the conditions, otherwise it will be reported to start failure
Install] is typically the last chunk of a configuration file that defines how to start and whether to boot. Its main fields are as follows.
Wantedby: Its value is one or more target, and the current unit activation (enable) symbolic link is placed under the/etc/systemd/system directory in a subdirectory consisting of the target name +.wants suffix
Requiredby: Its value is one or more target, when the current unit is activated, the symbolic link is placed in a subdirectory of the/etc/systemd/system directory under the target name +. Required suffix
Alias: The current unit can be used to start aliases
Also: When the current unit is active (enable), the other unit that is activated at the same time
The [service] block is used for service configuration and only the service type unit has this chunk. Its main fields are as follows.
Type: Defines the process behavior at startup. It has the following values.
Type=simple: Default value, execute execstart specified command, start main process
Type=forking: Fork to create child process from parent process, create stepfather process exits immediately
Type=oneshot: One-time process, SYSTEMD will wait for the current service to exit, and then continue to execute down
Type=dbus: Current service starts through D-bus
Type=notify: The current service starts, will notify the SYSTEMD, and then continue to execute down
Type=idle: The current service will run if another task is completed
Execstart: command to start the current service
Execstartpre: Command to execute before starting the current service
Execstartpost: Command executed after starting the current service
Execreload: Commands executed when restarting the current service
Execstop: Command executed when stopping the current service
Execstoppost: Stop a command that executes after its service
RESTARTSEC: Automatically restarts the number of seconds in the current service interval
Restart: Defines what happens SYSTEMD automatically restarts the current service, and the possible values include always (never reboot), on-success, On-failure, On-abnormal, On-abort, On-watchdog
TIMEOUTSEC: Defines the number of seconds to wait before Systemd stops the current service
Environment: Specifying environment variables
For a complete list of the unit configuration files, please refer to the official documentation.
VI. Target
When you start the computer, you need to start a large number of unit. If you start each time, it is obviously inconvenient to specify which unit is required for this launch. The SYSTEMD solution is target.
Simply put, Target is a unit group that contains a number of related units. When you start a target, SYSTEMD will start all of the unit inside. In this sense, the concept of target is similar to the "State point", and starting a target is like booting into a state.
In the traditional init startup mode, there is the concept of runlevel, which is similar to the role of target. The difference is that RunLevel is mutually exclusive and it is not possible to start multiple runlevel simultaneously, but multiple target can be started simultaneously.
#查看当前系统的所有Target $ systemctl list-unit-files--type=target# View a target contains all unit$ systemctl list-dependencies multi-user.target# viewing the default target$ at startup Systemctl get-default# setting starts with the default target$ sudo systemctl set-default multi-user.target #切换Target时, the default does not close the previous target startup process, # Systemctl Isolate command changes This behavior, #关闭前一个Target里面所有不属于后一个Target的进程 $ sudo systemctl isolate Multi-user.target
The correspondence between target and the traditional runlevel is as follows.
Traditional RunLevel New target name symbolically linked to ... Runlevel 0 | Runlevel0.target, Poweroff.targetrunlevel 1 | Runlevel1.target, Rescue.targetrunlevel 2 | Runlevel2.target, Multi-user.targetrunlevel 3 | Runlevel3.target, Multi-user.targetrunlevel 4 | Runlevel4.target, multi-user.targetrunlevel 5 | Runlevel5.target, Graphical.targetrunlevel 6 | Runlevel6.target-Reboot.target
The main differences between it and the Init process are as follows.
(1) The default RunLevel (in the/etc/inittab file setting) is now replaced by the default target, and the location is/etc/systemd/system/ Default.target, usually symbolic links to Graphical.target (graphical interface) or Multi-user.target (multi-user command line).
(2) The location of the startup script, formerly the/ETC/INIT.D directory, is linked to a different runlevel directory (such as/ETC/RC3.D,/ETC/RC5.D, etc.) and is now stored in/lib/systemd/system and/etc/ Systemd/system directory.
(3) The location of the configuration file, the configuration file of the previous Init process is/etc/inittab, and the configuration files of various services are stored in the/etc/sysconfig directory. Now the configuration file is mainly stored in the/LIB/SYSTEMD directory, the changes in the/ETC/SYSTEMD directory can overwrite the original settings.
vii. Log Management
SYSTEMD Unified management of all unit startup logs. The benefit is that you can view all logs (kernel logs and application logs) with just one command of Journalctl. The configuration file for the log is/etc/systemd/journald.conf.
Journalctl is powerful and uses a lot.
#查看所有日志 (by default, only the log for this startup is saved) $ sudo journalctl# view kernel log (do not show Application log) $ sudo journalctl-k# view System This startup log $ sudo journalctl-b$ sudo jou Rnalctl-b -0# View last started log (need to change settings) $ sudo journalctl-b -1# view a log of a specified time $ sudo journalctl--since= "2012-10-30 18:17:16" $ sudo jour Nalctl--since "min ago" $ sudo journalctl--since yesterday$ sudo journalctl--since "2015-01-10"--until "2015-01-11 0 "$ sudo journalctl--since--until" 1 hour ago "#显示尾部的最新10行日志 $ sudo journalctl-n# show tail specified number of lines log $ sudo journalctl-n 20# Real-time scrolling show latest log $ sudo journalctl-f# view specified service log $ sudo journalctl/usr/lib/systemd/systemd# view the log of the specified process $ sudo journalctl _pid=1 #查看某个路径的脚本的日志 $ sudo journalctl/usr/bin/bash# view specified user's log $ sudo journalctl _uid=33--since today# View a Unit of logs $ sudo journalc Tl-u nginx.service$ sudo journalctl-u nginx.service--since today# Live scrolling shows the latest log of a Unit $ sudo journalctl-u nginx.service -f# Merge displays logs for multiple Unit $ journalctl-u nginx.service-u php-fpm.service--since today# View the logs for the specified priority (and above levels), total 8 levels # 0:emerg# 1:ale rt# 2:crit# 3:err# 4:warning# 5:notice# 6:info# 7:debug$ sudo journalctl-p err-b# log default paging output,--no-pager changed to normal standard output $ sudo journalctl--no-pager# to JSON format (single line) output $ sudo journalctl-b-u nginx.service-o json# in JSON format (multiline) output, better readability $ sudo journalctl-b-u nginx.serviceqq-o json-pretty# Display log occupies the hard disk space $ sudo journalctl--disk-usage# specifies the maximum space occupied by the log file $ sudo journalctl--vacuum-size=1g# Specify how long the log file is saved sudo journalctl--vacuum-time=1years
Systemd Getting Started Tutorial: Command post