Introduction to systemd tools

1. Background

        systemdIt is a system and service manager dedicated to Linux operating systems. PID=1When running as a startup process ( ), it will run as an initialization system, which starts and maintains various user space services.

2. Order

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

1. systemctl (main command, used to manage the system)

  • systemctl --version: View version.
  • systemctl reboot: Restart the system.
  • systemctl poweroff: Shut down the system and cut off the power supply.
  • systemctl halt:CPU stops working.
  • systemctl suspend: Pause the system.
  • systemctl hibernate: Let the system enter hibernation state.
  • systemctl hybrid-sleep: Put the system into interactive hibernation.
  • systemctl rescue: Start into rescue state (single user state).

2. systemd-analyze (check startup time)

  • systemd-analyze: Check the startup time.
  • systemd-analyze blame: Check the startup time of each service.
  • systemd-analyze critical-chain: Display the waterfall-like startup process flow.
  • systemd-analyze critical-chain 单元.service: Display the startup flow of the specified service.
  • systemd-analyze plot > startup.svg: Flame graph of application and service startup time. like:
    Insert image description here

3. hostnamectl (view/set current host information)

  • hostnamectl: Display current host information.
  • hostnamectl set-hostname 主机名: Set the host name.

4. localectl (view/set localization settings)

  • localectl: View localization settings.
  • localectl set-locale LANG=en_GB.utf8
    localectl set-keymap en_GB
    Set localization parameters.

5. timedatectl (view/set current time zone settings)

  • timedatectl: View the current time zone setting.
  • timedatectl list-timezones: Shows all available time zones.
  • timedatectl set-timezone America/New_York
    timedatectl set-time YYYY-MM-DD
    timedatectl set-time HH:MM:SS
  • timedatectl set-ntp 开关[true, false]: Turn on/off ntp (network time synchronization).

(1) Stop time synchronization service

timedatectl set-ntp false
systemctl stop systemd-timesyncd
systemctl disable systemd-timesyncd

(2) Permanently modify the system time zone

ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

6. loginctl (used to view currently logged in users)

  • loginctl list-sessions: List the current session.
  • loginctl list-users: List currently logged in users.
  • loginctl show-user root: List and display the information of the specified user.

3. Unit

1. Classification

        systemdCan manage all system resources. Different resources are collectively called Units. Units are divided into 12 types:

  • Service Unit : System service.
  • Target Unit : A group composed of multiple Units.
  • Device Unit : Hardware device.
  • Mount Unit : The mount point of the file system.
  • Automount Unit : Automatic mount point.
  • Path Unit : File or path.
  • Scope Unit : External process not started by systemd.
  • Slice Unit : Process group.
  • Snapshot Unit : systemd snapshot, you can switch back to a certain snapshot.
  • Socket Unit : Socket for inter-process communication.
  • Swap Unit : swap file.
  • Timer Unit : timer.

Order

  • systemctl list-units: View all Units in the current system.
  • systemctl list-units --all: List all Units, including those whose configuration files are not found or those that failed to start.
  • systemctl list-units --all --state=inactive: List all Units that are not running.
  • systemctl list-units --failed: List all Units that failed to load.
  • systemctl list-units --type=service: List all running Units of type service.

2. Status

  • systemctl status: Display system status.
  • sysystemctl status 单元.service: Display the status of a single Unit.
  • systemctl -H [email protected] status 单元.service: Display the status of a Unit on the remote host.
  • systemctl is-active 单元.service: Shows whether a Unit is running.
  • systemctl is-failed 单元.service: Displays whether a Unit is in startup failure state.
  • systemctl is-enabled 单元.service: Displays whether a startup link has been established for a Unit.

3. Management

  • systemctl start 单元.service: Start a service immediately.
  • systemctl stop 单元.service: Stop a service immediately.
  • systemctl restart 单元.service: Restart a service.
  • systemctl kill 单元.service: Kill all child processes of a service.
  • systemctl reload 单元.service: Reload a service's configuration file.
  • systemctl show 单元.service: Display all underlying parameters of a Unit.
  • systemctl daemon-reload: Reload all modified configuration files.
  • systemctl show -p CPUShares 单元.service: Display the value of the specified attribute of a Unit.
  • systemctl set-property httpd.service CPUShares=500: Set the specified attributes of a Unit.

4. Dependency

        There is a dependency relationship between Units: A depends on B, which means that systemdwhen A is started, B will be started at the same time.

  • systemctl list-dependencies 单元.service: List all dependencies of a Unit.

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

  • systemctl list-dependencies --all 单元.service

4. Unit configuration file

1 Overview

        Each Unit has a configuration file that tells systemdhow to start the Unit. systemdBy default, /etc/systemd/system/configuration files are read from the directory, but most of the files stored there are symbolic links pointing to the directory /usr/lib/systemd/system/(where the real configuration files are stored). systemctl enableThe command is used to establish a symbolic link relationship between the above two directories.

systemctl enable test.service
等同于
ln -s '/usr/lib/systemd/system/test.service' '/etc/systemd/system/multi-user.target.wants/test.service'

        If startup is set in the configuration file, systemctl enablethe command is equivalent to activating startup. The corresponding systemctl disablecommand is used to cancel the symbolic link relationship between two directories, which is equivalent to canceling the startup.

systemctl disable test.service

        The suffix name of the configuration file is the type of the Unit, for example sshd.socket. If omitted, systemdthe default suffix is .service​​, so sshdit will be understood as sshd.service.

2. Status

  • systemctl list-unit-files: List all configuration files.
  • systemctl list-unit-files --type=service: List configuration files of the specified type.
  • systemctl list-unit-files: Output a list that displays the status of each configuration file. There are 4 types in total:
    • enabled : The startup link has been established.
    • disabled : No startup link is established.
    • static : This configuration file does not have an [Install] part (cannot be executed) and can only be used as a dependency on other configuration files.
    • masked : This configuration file is prohibited from establishing startup links.

        Once the configuration file is modified, the configuration file must be systemdreloaded and then restarted, otherwise the modification will not take effect.

systemctl daemon-reload
systemctl restart 单元.service

3. Format

        Configuration files are ordinary text files that can be opened with a text editor. systemctl cat 单元.servicecommand to view the contents of the configuration file. For example:

root@jaron:/home# systemctl cat sshd
# /lib/systemd/system/ssh.service
[Unit]
Description=OpenBSD Secure Shell server
After=network.target auditd.service
ConditionPathExists=!/etc/ssh/sshd_not_to_be_run

[Service]
EnvironmentFile=-/etc/default/ssh
ExecStartPre=/usr/sbin/sshd -t
ExecStart=/usr/sbin/sshd -D $SSHD_OPTS
ExecReload=/usr/sbin/sshd -t
ExecReload=/bin/kill -HUP $MAINPID
KillMode=control-group
Restart=on-failure
RestartPreventExitStatus=255
Type=notify

[Install]
WantedBy=multi-user.target
Alias=sshd.service
root@jaron:/#

        As you can see from the above output, the configuration file is divided into several chunks. The first line of each block is the distinguished name expressed in square brackets, for example [Unit]. Inside each block are some key-value pairs connected with an equal sign. Note: The block name and field name of the configuration file are case-sensitive , and there must be no spaces on either side of the equal sign in the key-value pair .

3. Block

Complete field list .

(1)[Unit]

        [Unit]The block is usually the first block of the configuration file and 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.
  • DefaultDependencies: Whether to turn off the default dependency, the value is [ yes, no], the default is yes. Note: When the After field is specified as graphical.target(meaning it will start after the interface system starts), this field needs to be set to notake effect.
  • Requires: If other Units that the current Unit depends on are not running, the current Unit will fail to start.
  • Wants: If other Units that cooperate with the current Unit are not running, the current Unit will not fail to start.
  • BindsTo: Similar to Requires, if the Unit specified exits, it will cause the current Unit to stop running.
  • Before: If the Unit specified in this field also wants 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 at the same time as the current Unit.
  • Condition...: The conditions that must be met for the current Unit to run, otherwise it will not run.
  • Assert...: Conditions that must be met for the current Unit to run, otherwise a startup failure will be reported.

(2)[Service]

        [Service]The block is used for Service configuration. Only Service type Units have this block. Its main fields are as follows:

  • Type: Defines process behavior at startup. It has the following values.
    • Type=simple:Default value, execute ExecStartthe specified command and start the main process.
    • Type=forking: forkCreate a child process from the parent process in this way, and the parent process will exit immediately after creation.
    • Type=oneshot: A one-time process that systemdwill wait for the current service to exit before continuing execution.
    • Type=dbus: The current service is D-Busstarted by.
    • Type=notify: When the current service is started, it will be notified systemdand then continue execution.
    • Type=idle: The current service will only run if other tasks have been completed.
  • KillMode: Define systemdhow to stop the service. The values ​​that can be set are as follows.
    • control-group: (Default value) All child processes in the current control group will be killed.
    • process: Only kill the main process.
    • mixed: The main process will receive SIGTERMthe signal and the child process will receive SIGKILLthe signal.
    • none: No process will be killed.
  • ExecStart: Command to start the current service.
  • ExecStartPre: The command executed before starting the current service.
  • ExecStartPost: The command to be executed after starting the current service.
  • ExecReload: Command executed when restarting the current service.
  • ExecStop: The command executed when stopping the current service.
  • ExecStopPost: The command to be executed after stopping the current service.
  • RestartSec: The number of seconds between automatically restarting the current service.
  • Restart: Define under what circumstances systemdthe current service will be automatically restarted. Possible values ​​include always(always restart), on-success, on-failure, on-abnormal, on-abort.on-watchdog
  • TimeoutSec: Defines systemdthe number of seconds to wait before stopping the current service.
  • Environment: Specify environment variables.

(3)[Install]

        [Install]It is usually the last block of the configuration file and is used to define how to start and whether to start at boot. 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 in the /etc/systemd/systemsubdirectory named below Target名.wantsthe directory.
  • RequiredBy: Its value is one or more Targets. When the current Unit is activated, the symbolic link will be placed in the /etc/systemd/systemsubdirectory named below Target名.requiredthe directory.
  • Alias: Aliases that the current Unit can be used to start.
  • Also: When the current Unit is activated (enabled), other Units will be activated at the same time.

5. Target

        When starting the computer, a large number of Units need to be started. It would obviously be very inconvenient if every time you start, you have to specify which Units are needed for this start. systemdThe solution is Target .
        Simply put, Target is a Unit group that contains many related Units. When a Target is started , systemd will start all Units in it. In this sense, the concept of Target is similar to a "state point". Starting a Target is like starting a certain state.
        In the traditional initstartup mode, there is the concept of RunLevel , which is very similar to Target . The difference is that RunLevel is mutually exclusive. It is impossible for multiple RunLevel to be started at the same time, but multiple Targets can be started at the same time.

  • systemctl list-unit-files --type=target: View all Targets in the current system.
  • systemctl list-dependencies multi-user.target: View all Units contained in a Target.
  • systemctl get-default: View the default Target at startup.
  • systemctl set-default multi-user.target: Set the default Target at startup.
  • systemctl isolate multi-user.target: Close all processes in the previous Target that do not belong to the next 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
        Its initmain differences from processes are as follows:
  • The default RunLevel (in the file settings) is now replaced /etc/inittabby the default Target/etc/systemd/system/default.target , which is usually a symbolic link to graphical.target(graphical interface) or multi-user.target(multi-user command line).
  • The location of the startup script used to be /etc/init.da directory, with symbolic links to different RunLevel directories (such as / etc/rc3.d, /etc/rc5.detc.), but now it is stored in /lib/systemd/system和/etc/systemd/systemthe directory.
  • initThe location of the configuration file. The configuration file of the previous process is /etc/inittab, and the configuration files of various services are stored in /etc/sysconfigthe directory. Current configuration files are mainly stored in /lib/systemddirectories, and /etc/systemdmodifications in the directory can overwrite the original settings.

6. Log management

        systemdUnified management of startup logs of all Units. The advantage is that you can journalctlview all logs (kernel logs and application logs) with just one command. The log configuration file is /etc/systemd/journald.conf.

  • journalctl: View all logs (by default, only the logs of this startup are saved).
  • journalctl -k: View kernel logs (do not display application logs).
  • journalctl -b -0: View the log of this system startup.
  • journalctl -b -1: View the log of the last startup of the system.
  • journalctl --since="2012-10-30 18:17:16"
    journalctl --since "20 min ago"
    journalctl --since yesterday
    journalctl --since "2015-01-10" --until "2015-01-11 03:00"
    journalctl --since 09:00 --until "1 hour ago"
    View logs for a specified time.
  • journalctl -n: Display the latest 10 lines of logs at the end.
  • journalctl -n 行数: Display the log with the specified number of lines at the end.
  • journalctl -f: Real-time scrolling display of the latest logs.
  • journalctl _PID=1: View the logs of the specified process.
  • journalctl /usr/bin/bash: View the log of a script in a certain path.
  • journalctl _UID=33 --since today: View the logs of the specified user.
  • journalctl -u 单元.service
    journalctl -u 单元.service --since today
    View the log of a Unit.
  • journalctl -u 单元.service -f: Scroll and display the latest log of a Unit in real time.
  • journalctl -u 单元1.service -u 单元2.service --since today: Combine and display the logs of multiple Units.
  • journalctl -p err -b: View logs with specified priority (and above), there are 8 levels in total:
    • 0: emerg
    • 1: alert
    • 2: crit
    • 3: err
    • 4: warning
    • 5: notice
    • 6: info
    • 7: debug
  • journalctl --no-pager: The default log output is paged, --no-pagerchanged to normal standard output.
  • journalctl -b -u 单元.service -o json: Output in JSON format (single line).
  • journalctl -b -u 单元.serviceqq -o json-pretty: Output in JSON format (multiple lines) for better readability.
  • journalctl --disk-usage: Display the hard disk space occupied by the log.
  • journalctl --vacuum-size=1G: Specify the maximum space occupied by the log file.
  • journalctl --vacuum-time=1years: Specify how long to keep log files.

Guess you like

Origin blog.csdn.net/hezhanran/article/details/123898640