Command that operation and maintenance must master -- Systemd instruction

Keywords: Programming sudo Nginx Apache JSON

I. origin

Historically, Linux startup Always used 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, it takes a long time to start. 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 other things. Scripts need to deal with a variety of situations on their own, which often makes them very long.

II. Overview of Systemd

Systemd was born to solve these problems. Its design goal is to provide a complete set of solutions for system startup and management.

According to Linux conventions, the letter d is an abbreviation for the daemon. The meaning of Systemd is that it guards the whole system.

With Systemd, init is no longer needed. Instead of initd, Systemd becomes the first process of the system (PID is equal to 1), and other processes are its subprocesses.


$ systemctl --version

The command above looks at the version of Systemd.

The advantage of Systemd is its powerful function and convenient use. The disadvantage of Systemd is its huge and complex system. In fact, there are many people who are against using Systemd, because it is too complex, strongly coupled with other parts of the operating system, in violation of "keep simple, keep stupid" Unix Philosophy.

(above is the system D architecture diagram)

III. system management

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

3.1 systemctl

systemctl is the main command of Systemd to manage the system.

# Restart system
$ sudo systemctl reboot

# Shut down 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 to enter 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

# Display waterfall like 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 information about the current host.

# Display 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

# Show 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 currently logged in users
$ loginctl list-users

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

IV. Unit

4.1 meaning

Systemd can manage all system resources. Different resources are collectively referred to as Unit.

There are 12 types of Unit.

  • Service unit: system service
  • Target unit: a group of multiple units
  • Device Unit: hardware device
  • Mount Unit: mount point for the file system
  • Automount Unit: automount point
  • Path Unit: file or path
  • Scope Unit: external process not started by Systemd
  • Slice Unit: Process Group
  • Snapshot Unit: system D snapshot, which can be switched 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 that do not find the configuration file or fail to start
$ systemctl list-units --all

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

# List 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

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

# Display the status of a Unit of a 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 the judgment statements inside the script.

# Show if a Unit is running
$ systemctl is-active application.service

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

# Shows whether a Unit service has 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 now
$ sudo systemctl stop apache.service

# Restart a service
$ sudo systemctl restart apache.service

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

# Reload a service's configuration file
$ sudo systemctl reload apache.service

# Reload all modified profiles
$ sudo systemctl daemon-reload

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

# Display the value of the specified property 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 dependency

There is A dependency relationship 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 the dependencies of a Unit.

$ systemctl list-dependencies nginx.service

Some of the output results of the above commands depend on the Target type (see below), which will not be expanded by default. If you want to expand Target, you need to use the -- all parameter.

$ systemctl list-dependencies --all nginx.service

V. configuration file of Unit

5.1 general

Each Unit has a configuration file that tells Systemd how to start the Unit.

By default, Systemd reads the configuration file from the directory / etc/systemd/system /. However, most of the files stored in it 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 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 undo the symbolic link relationship between two directories, which is equivalent to undoing 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 Systemd is. Service, so sshd will be interpreted as sshd.service.

5.2 profile status

The systemctl list unit files command lists all configuration files.

# List all profiles
$ systemctl list-unit-files

# List 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: start link established
  • disabled: no start link established
  • static: this configuration file has no [Install] part (cannot be executed), and can only be relied on by other configuration files
  • masked: the profile is forbidden to establish start link

Note that the status of the configuration file does not tell if the Unit is running. This requires executing the systemctl status command mentioned earlier.

$ systemctl status bluetooth.service

Once the configuration file is modified, system D should 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 configuration file

A configuration file is a normal 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 you can see from the output above, the configuration file is divided into several blocks. The first line of each block is a 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 cannot be spaces on either side of the equal sign of a 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 the relationship between the configuration and other units. Its main fields are as follows.

  • Description: short description
  • Documentation: document address
  • Requirements: other units that the current Unit depends on. If they are not running, the current Unit will fail to start
  • Watts: other units matching the current Unit. If they are not running, the current Unit will not fail to start
  • BindsTo: similar to requirements, if the Unit specified by it exits, it will cause the current Unit to stop running
  • Before: if the Unit specified in this field is also to be started, it must be started after the current Unit
  • After: if the Unit specified in this field is also to be started, it must be started before the current Unit
  • Conflicts: the Unit specified here cannot run at the same time as the current Unit
  • Condition...: the condition that the current Unit operation must meet, otherwise it will not run
  • Assert...: the condition that the current Unit operation must meet, otherwise the start 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, the symbolic link will be placed in the subdirectory composed of Target name +. wants suffix under / etc/systemd/system directory
  • RequiredBy: its value is one or more targets. When the current Unit is activated, the symbolic link will be placed in the subdirectory composed of Target name +. required suffix under / etc/systemd/system directory
  • Alias: alias that the current Unit can use to start
  • Also: other units that will be activated at the same time when the current Unit is activated (enable)

The [Service] block is used for Service configuration. Only Unit of Service type has 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, start the main process
  • Type=forking: create a child process from the parent process in fork mode, and the parent process will exit immediately after creation
  • Type=oneshot: a one-time process. Systemd will wait for the current service to exit and continue to execute
  • Type=dbus: the current service is started through D-Bus
  • Type=notify: after the current service is started, system D will be notified to continue to execute
  • Type=idle: if other tasks are completed, the current service will run
  • 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 to be executed when the current service is restarted
  • ExecStop: command executed when the current service is stopped
  • ExecStopPost: stop the command executed after its service
  • RestartSec: the number of seconds between automatic restarts of the current service
  • Restart: define what situation Systemd will automatically restart the current service. Possible values include always, on success, on failure, on abnormal, on abort, on watchdog
  • TimeoutSec: defines the number of seconds system D waits before stopping the current service
  • Environment: specify environment variable

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

Vi. Target

When you start the computer, you need to start a large number of units. If you start every time, you need to write down which units are needed for this startup, which is obviously very inconvenient. Systemd's solution is Target.

In short, Target is a Unit group, which contains many related units. When a Target is started, Systemd will start all the 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 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 start 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 default Target at startup
$ systemctl get-default

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

# When switching Target, the process started by the previous Target will not be 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 the init process are as follows.

(1) the default RunLevel (set in the / etc/inittab file) is now replaced by the default Target. The location is / etc/systemd/system/default.target. Usually, the symbol is linked to graphic.Target (graphical interface) or multi-user.target (multi-user command line).

(2) the location of the startup script, formerly the directory / etc/init.d, is linked to different RunLevel directories (such as / etc/rc3.d, / etc/rc5.d), and now it is stored in the directories / lib/systemd/system and / etc/systemd/system.

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

VII. Log management

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

Journal CTL is powerful and widely used.

# View all logs (by default, only logs started this time are saved)
$ sudo journalctl

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

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

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

# View log for 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"

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

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

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

# View logs for the specified service
$ sudo journalctl /usr/lib/systemd/systemd

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

# View the log of the script 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

# Real time scrolling display of the latest log of a Unit
$ sudo journalctl -u nginx.service -f

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

# View the logs of the specified priority (and above), 8 levels in total
# 0: emerg
# 1: alert
# 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

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

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

# Display the hard disk space occupied by logs
$ sudo journalctl --disk-usage

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

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

Posted by mwkdesign on Wed, 18 Dec 2019 02:23:27 -0800