Overall understanding of system D instructions

systemctl understanding

There are two ways of Linux service management: service and systemctl

systemd is the latest initialization system (init) of Linux system. Its function is to improve the startup speed of the system, start fewer processes as much as possible and start more processes concurrently as much as possible.

The process management command corresponding to systemd is systemctl

1, Origin

historically, Linux startup Always use init Process.

The following command is used to start the service.

$ sudo /etc/init.d/apache2 start
# perhaps
$ service apache2 start

This method has two disadvantages.

First, the start-up time is long. init process is started serially. The next process will be started only after the previous process is started.

Second, the startup script is complex. The init process just executes the startup script, regardless of anything else. Scripts need to handle various situations by themselves, which often makes scripts very long.

2, Systemd overview

System D was born to solve these problems. Its design goal is to provide a complete solution for system startup and management.

According to Linux convention, the letter d is the abbreviation of daemon. The meaning of the name system d is to protect the whole system.

If you use Systemd, you don't need init anymore. System D replaces initd and becomes the first process of the system (PID equals 1). Other processes are its child processes.

$ systemctl --version

The above command checks the version of system D.

The advantage of system D is powerful and easy to use. The disadvantage is that the system is huge and very complex. In fact, there are still many people who oppose the use of system D because it is too complex and strongly coupled with other parts of the operating system, which violates the principle of "keep simple, keep stub ID" Unix Philosophy.

(the above figure shows the architecture of system d)

3, System management

System D is not a command, but a set of commands, involving all aspects of system management.

3.1 systemctl

systemctl is the main command of system D, which is used to manage the system.

# Restart the system
$ sudo systemctl reboot

# Turn off the system and cut off the power supply
$ sudo systemctl poweroff

# CPU stops working
$ sudo systemctl halt

# Pause system
$ sudo systemctl suspend

# Put the system into hibernation
$ sudo systemctl hibernate

# Put the system into interactive sleep
$ sudo systemctl hybrid-sleep

# Start and enter the rescue state (single user state)
$ sudo systemctl rescue

3.2 systemd-analyze

The SYSTEMd analyze command is used to view the startup time.

# View startup time
$ systemd-analyze                                                                                       

# View the startup time of each service
$ systemd-analyze blame

# Show waterfall startup process flow
$ systemd-analyze critical-chain

# Displays the startup flow for the specified service
$ systemd-analyze critical-chain atd.service

3.3 hostnamectl

The hostnamectl command is used to view the information of the current host.

# Displays information about the current host
$ hostnamectl

# Set the host name.
$ sudo hostnamectl set-hostname rhel7

3.4 localectl

The localectl command is used to view localization settings.

# View localization settings
$ localectl

# Set localization parameters.
$ sudo localectl set-locale LANG=en_GB.utf8
$ sudo localectl set-keymap en_GB

3.5 timedatectl

The timedatectl command is used to view the current time zone settings.

# View current time zone settings
$ timedatectl

# Displays all available time zones
$ timedatectl list-timezones                                                                                   

# Set current time zone
$ sudo timedatectl set-timezone America/New_York
$ sudo timedatectl set-time YYYY-MM-DD
$ sudo timedatectl set-time HH:MM:SS

3.6 loginctl

The loginctl command is used to view the currently logged in user.

# List current session
$ loginctl list-sessions

# List the currently logged in users
$ loginctl list-users

# Lists and displays information for the specified user
$ loginctl show-user ruanyf

4, Unit

4.1 meaning

System D can manage all system resources. Different resources are collectively referred to as units.

Unit is divided into 12 types.

  • Service unit: system service
  • Target unit: a group composed of multiple units
  • Device Unit: hardware device
  • Mount Unit: mount point of file system
  • Automount Unit: auto mount point
  • Path Unit: file or path
  • Scope Unit: not an external process started by system D
  • Slice Unit: Process Group
  • Snapshot Unit: system snapshot. You can switch back to a snapshot
  • Socket Unit: socket for inter process communication
  • Swap Unit: swap file
  • Timer Unit: timer

The systemctl list units command can view all units of the current system.

# List running units
$ systemctl list-units

# List all units, including those with no configuration file found or failed to start
$ systemctl list-units --all

# List all units that are not running
$ systemctl list-units --all --state=inactive

# Lists all units that failed to load
$ systemctl list-units --failed

# List all running units of type service
$ systemctl list-units --type=service

4.2 status of unit

The systemctl status command is used to view the system status and the status of a single Unit.

# Display system status
$ systemctl status

# Displays the status of a single Unit
$ sysystemctl status bluetooth.service

# Displays the status of a Unit of the remote host
$ systemctl -H root@rhel7.example.com status httpd.service

In addition to the status command, systemctl also provides three simple methods to query the status, which are mainly used for judgment statements inside the script.

# Displays whether a Unit is running
$ systemctl is-active application.service

# Displays whether a Unit is in the state of startup failure
$ systemctl is-failed application.service

# Displays whether a Unit service has established a startup link
$ systemctl is-enabled application.service

4.3 Unit management

For users, the following commands are most commonly used to start and stop Unit (mainly service).

# Start a service now
$ sudo systemctl start apache.service

# Stop a service immediately
$ sudo systemctl stop apache.service

# Restart a service
$ sudo systemctl restart apache.service

# Kill all child processes of a service
$ sudo systemctl kill apache.service

# Reload the configuration file of a service
$ sudo systemctl reload apache.service

# Reload all modified configuration files
$ sudo systemctl daemon-reload

# Displays all the underlying parameters of a Unit
$ systemctl show httpd.service

# Displays the value of the specified attribute of a Unit
$ systemctl show -p CPUShares httpd.service

# Set the specified property of a Unit
$ sudo systemctl set-property httpd.service CPUShares=500

4.4 dependencies

There is A dependency between units: A depends on B, which means that when system d starts A, it will start B at the same time.

The systemctl list dependencies command lists all dependencies of a Unit.

$ systemctl list-dependencies nginx.service

Among the output results of the above commands, some dependencies are of Target type (see below), which will not be expanded and displayed by default. If you want to expand the Target, you need to use the -- all parameter.

$ systemctl list-dependencies --all nginx.service

5, Configuration file for Unit

5.1 general

Each Unit has a configuration file that tells system d 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 /, where the real configuration files are stored.

The systemctl enable command is used to establish a symbolic link relationship between the above two directories.

$ sudo systemctl enable clamd@scan.service
# Equivalent to
$ sudo ln -s '/usr/lib/systemd/system/clamd@scan.service' '/etc/systemd/system/multi-user.target.wants/clamd@scan.service'

If boot is set in the configuration file, the systemctl enable command is equivalent to activating boot.

Correspondingly, the systemctl disable command is used to cancel the symbolic link relationship between two directories, which is equivalent to canceling the startup.

$ sudo systemctl disable clamd@scan.service

The suffix of the configuration file is the type of the Unit, such as sshd socket. If omitted, the default suffix of system D is Service, so sshd will be understood as sshd service.

5.2 status of configuration file

The systemctl list unit files command lists all configuration files.

# List all profiles
$ systemctl list-unit-files

# Lists profiles of the specified type
$ systemctl list-unit-files --type=service

This command will output a list.

$ systemctl list-unit-files

UNIT FILE              STATE
chronyd.service        enabled
clamd@.service         static
clamd@scan.service     disabled

This list shows the status of each configuration file. There are four types.

  • enabled: the startup link has been established
  • disabled: the startup link is not established
  • static: this configuration file has no [Install] part (cannot be executed), and can only be used as a dependency of other configuration files
  • masked: this profile is prohibited from establishing a startup link

Note that it is impossible to see whether the Unit is running from the status of the configuration file. This requires the execution of the systemctl status command mentioned earlier.

$ systemctl status bluetooth.service

Once the configuration file is modified, system d must reload the configuration file and restart, otherwise the modification will not take effect.

$ sudo systemctl daemon-reload
$ sudo systemctl restart httpd.service

5.3 format of configuration file

A configuration file is an ordinary text file that can be opened with a text editor.

The systemctl cat command can view the contents of the configuration file.

$ systemctl cat atd.service

[Unit]
Description=ATD daemon

[Service]
Type=forking
ExecStart=/usr/bin/atd

[Install]
WantedBy=multi-user.target

As can be seen from the above output, the configuration file is divided into several blocks. The first line of each block is the distinguished name in square brackets, such as [Unit]. Note that the block name and field name of the configuration file are case sensitive.

Inside each block are some key value pairs connected by equal signs.

[Section]
Directive1=value
Directive2=value
. . .

Note that there should be no spaces on both sides of the equal sign of the key value pair.

5.4 block of configuration file

The [Unit] block is usually the first block of the configuration file, which is used to define the metadata of the Unit and configure the relationship with other units. Its main fields are as follows.

  • Description: short description
  • Documentation: document address
  • Requires: other units that the current Unit depends on. If they are not running, the current Unit will fail to start
  • Wants: other units matched with the current Unit. If they are not running, the current Unit will not fail to start
  • BindsTo: similar to requirements, if the specified Unit exits, the current Unit will stop running
  • Before: if the Unit specified in this field also needs to be started, it must be started after the current Unit
  • After: if the Unit specified in this field also needs to be started, it must be started before the current Unit
  • Conflicts: the Unit specified here cannot run simultaneously with the current Unit
  • Condition...: The conditions that must be met for the current Unit to run, otherwise it will not run
  • Assert...: The conditions that must be met by the current Unit operation, otherwise the startup failure will be reported

[Install] is usually the last block of the configuration file, which is used to define how to start and whether to start. Its main fields are as follows.

  • WantedBy: its value is one or more targets. When the current Unit is activated (enable), the symbolic link will be placed under the / etc/systemd/system directory with the name of Target + In the subdirectory composed of wants suffix
  • RequiredBy: its value is one or more targets. When the current Unit is activated, the symbolic link will be placed under the / etc/systemd/system directory with the name of Target + In the subdirectory composed of the required suffix
  • Alias: alias that the current Unit can use to launch
  • Also: other units that will be activated at the same time when the current Unit is activated

The [Service] block is used to configure the Service. Only units of Service type have this block. Its main fields are as follows.

  • Type: defines the process behavior at startup. It has the following values.
  • Type=simple: default value: execute the command specified by ExecStart to start the main process
  • Type=forking: create a child process from the parent process in the form of fork. After creation, the parent process will exit immediately
  • Type=oneshot: a one-time process. System D will wait for the current service to exit before continuing
  • Type=dbus: the current service is started through D-Bus
  • Type=notify: after the current service is started, Systemd will be notified, and then continue to execute
  • Type=idle: the current service will not run until other tasks are completed
  • ExecStart: command to start the current service
  • ExecStartPre: command executed before starting the current service
  • ExecStartPost: command executed after starting the current service
  • ExecReload: command executed when restarting the current service
  • ExecStop: command executed when stopping the current service
  • ExecStopPost: command executed after stopping its service
  • RestartSec: the number of seconds between automatic restart of the current service
  • Restart: defines when system D will automatically restart the current service. Possible values include always, on success, on failure, on abnormal, on abort, and on watchdog
  • TimeoutSec: defines the number of seconds that Systemd waits before stopping the current service
  • Environment: Specifies the environment variable

For a complete list of fields in the Unit configuration file, please refer to Official documents.

6, Target

When starting the computer, you need to start a large number of units. It is obviously inconvenient to specify which units are required for each startup. System D's solution is Target.

Simply put, a Target is a Unit group that contains many related units. When a Target is started, system D will start all units in it. In this sense, the concept of Target is similar to "state point". Starting a Target is like starting to a certain state.

In the traditional init startup mode, there is the concept of RunLevel, which is very similar to the function of Target. The difference is that runlevels are mutually exclusive. It is impossible to start multiple runlevels at the same time, but multiple targets can be started at the same time.

# View all targets of the current system
$ systemctl list-unit-files --type=target

# View all units contained in a Target
$ systemctl list-dependencies multi-user.target

# View the default Target at startup
$ systemctl get-default

# Set the default Target at startup
$ sudo systemctl set-default multi-user.target

# When switching a Target, the process started by the previous Target is not closed by default,
# The systemctl isolate command changes this behavior,
# Close all processes in the previous Target that do not belong to the next Target
$ sudo systemctl isolate multi-user.target

The corresponding relationship between Target and traditional RunLevel is as follows.

Traditional runlevel      New target name     Symbolically linked to...

Runlevel 0           |    runlevel0.target -> poweroff.target
Runlevel 1           |    runlevel1.target -> rescue.target
Runlevel 2           |    runlevel2.target -> multi-user.target
Runlevel 3           |    runlevel3.target -> multi-user.target
Runlevel 4           |    runlevel4.target -> multi-user.target
Runlevel 5           |    runlevel5.target -> graphical.target
Runlevel 6           |    runlevel6.target -> reboot.target

The main differences between it and init process are as follows.

(1) The default RunLevel (set in the / etc/inittab file) is now replaced by the default target at / etc / SYSTEMd / system / default Target, usually symbolic link to graphical Target (graphical interface) or multi-user Target (multi-user command line).

(2) The location of the startup script, formerly / etc / init D directory, symbolic links to different RunLevel directories (such as / etc/rc3.d, / etc/rc5.d, etc.), which are now stored in / lib/systemd/system and / etc/systemd/system directories.

(3) The location of the configuration file. Previously, the configuration file of the init process was / etc/inittab, and the configuration files of various services were stored in the / etc/sysconfig directory. The current configuration files are mainly stored in the / lib/systemd directory. The modifications in the / etc/systemd directory can overwrite the original settings.

7, Log management

System D uniformly manages the startup logs of all units. The advantage is that you can view all logs (kernel log and application log) with only one command of journalctl. The log configuration file is / etc / Systemd / journald conf.

journalctl is powerful and has many uses.

# View all logs (by default, only the logs of this startup are saved)
$ sudo journalctl

# View kernel log (do not display application log)
$ sudo journalctl -k

# View the log of this system startup
$ sudo journalctl -b
$ sudo journalctl -b -0

# View the log of the last startup (need to change the settings)
$ sudo journalctl -b -1

# View the log at the specified time
$ sudo journalctl --since="2012-10-30 18:17:16"
$ sudo journalctl --since "20 min ago"
$ sudo journalctl --since yesterday
$ sudo journalctl --since "2015-01-10" --until "2015-01-11 03:00"
$ sudo journalctl --since 09:00 --until "1 hour ago"

# Displays the latest 10 lines of logs at the end
$ sudo journalctl -n

# Displays the log with the specified number of lines at the end
$ sudo journalctl -n 20

# Real time scrolling display of the latest log
$ sudo journalctl -f

# View the log of the specified service
$ sudo journalctl /usr/lib/systemd/systemd

# View the log of the specified process
$ sudo journalctl _PID=1

# View the log of scripts for a path
$ sudo journalctl /usr/bin/bash

# View the log of the specified user
$ sudo journalctl _UID=33 --since today

# View the log of a Unit
$ sudo journalctl -u nginx.service
$ sudo journalctl -u nginx.service --since today

# Scroll and display the latest log of a Unit in real time
$ sudo journalctl -u nginx.service -f

# Merge and display logs of multiple units
$ journalctl -u nginx.service -u php-fpm.service --since today

# View the logs of the specified priority (and above), with a total of 8 levels
# 0: emerg
# 1: alert
# 2: crit
# 3: err
# 4: warning
# 5: notice
# 6: info
# 7: debug
$ sudo journalctl -p err -b

# The default paging output of log, - no pager is changed to normal standard output
$ sudo journalctl --no-pager

# Output in JSON format (single line)
$ sudo journalctl -b -u nginx.service -o json

# Output in JSON format (multiple lines) for better readability
$ sudo journalctl -b -u nginx.serviceqq
 -o json-pretty

# Displays the hard disk space occupied by the log
$ sudo journalctl --disk-usage

# Specifies the maximum space occupied by the log file
$ sudo journalctl --vacuum-size=1G

# Specify how long the log file will be saved
$ sudo journalctl --vacuum-time=1years

(end)

Tags: Linux Operation & Maintenance systemd

Posted by bluesoul on Sun, 08 May 2022 21:57:21 +0300