systemd -- Research on linux service

Posted by Garcia on Sun, 06 Mar 2022 15:38:17 +0100

System d (d: daemon) -- Research on linux service

sketch

With The unit file at the end of service is used to encapsulate a process monitored and controlled by systemd

The. service file path is / etc/systemd/system

When starting up, Systemd only executes the configuration files in the / etc/systemd/system directory. This also means that if the modified configuration file is placed in this directory, the effect of overwriting the original configuration can be achieved

Start service

Start service manually

sudo service xxx start

View service status

sudo service xxx status

For example:

sudo service ssh status 
[sudo] password for yyz: 
● ssh.service - OpenBSD Secure Shell server
   Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
   Active: active (running) since III 2021-09-22 08:47:50 CST; 1h 50min ago
  Process: 2984 ExecReload=/bin/kill -HUP $MAINPID (code=exited, status=0/SUCCESS)
  Process: 2978 ExecReload=/usr/sbin/sshd -t (code=exited, status=0/SUCCESS)
  Process: 1103 ExecStartPre=/usr/sbin/sshd -t (code=exited, status=0/SUCCESS)
 Main PID: 1213 (sshd)
    Tasks: 1
   Memory: 12.0M
      CPU: 344ms
   CGroup: /system.slice/ssh.service
           └─1213 /usr/sbin/sshd -D

9 October 22:00:19 yyz sshd[16857]: pam_unix(sshd:session): session opened for user yyz by (uid
9 October 22:00:26 yyz sshd[17168]: Accepted publickey for yyz from 192.168.85.1 port 58879 ssh

Of which:

  • Loaded line: the location of the configuration file and whether it is set to startup
  • Active line: indicates running
  • Main PID line: main process ID
  • Status line: the current status of the software provided by the application itself (ssh here)
  • Cggroup block: all child processes applied
  • Log block: applied log

Stop service manually

sudo service xxx stop

configuration file

How a service starts depends entirely on its configuration file:

[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=process
Restart=on-failure
RestartPreventExitStatus=255
Type=notify

[Install]
WantedBy=multi-user.target
Alias=sshd.service
[Unit] block: startup sequence and dependency
  • After field: indicates if network Target or sshd keygen If the service needs to be started, sshd Services should start after them
  • Accordingly, there is also a Before field that defines sshd Which services should the service start Before

Note that the After and Before fields only involve the startup order, not the dependency. To set the dependency, you need to use the Wants field and the Requires field

  • Wants field: indicates sshd Service and sshd keygen There is a "weak dependency" relationship between services, that is, if sshd keygen If the service fails to start or stops running, it will not affect sshd The service continues to execute
  • The Requires field indicates "strong dependency", that is, if the service fails to start or exits abnormally, sshd The service must also exit

Note that the Wants field and the Requires field only involve dependencies and have nothing to do with the startup order. They are started at the same time by default

[Service] block: start behavior (defines how to start the current Service)
  • Environment file field: Specifies the environment parameter file of the current service. The key=value key value pair inside the file can be obtained in the current configuration file in the form of $key
# /Contents of etc/default/ssh file

$ cat /etc/default/ssh
# Default settings for openssh-server. This file is sourced by /bin/sh from
# /etc/init.d/ssh.

# Options to pass to sshd
SSHD_OPTS=

use

ExecStart=/usr/sbin/sshd -D $SSHD_OPTS
  • ExecStart field: defines the command to execute when starting the process
  • ExecReload field: the command executed when restarting the service
  • ExecStop field: the command executed when the service is stopped
  • ExecStartPre field: the command executed before starting the service
  • ExecStartPost field: the command executed after starting the service
  • ExecStopPost field: the command executed after the service is stopped

Before all startup settings, a hyphen (-) can be added to indicate "suppress error", that is, when an error occurs, it will not affect the execution of other commands

example

[Service]
ExecStart=/bin/echo execstart1
ExecStart=
ExecStart=/bin/echo execstart2
ExecStartPost=/bin/echo post1
ExecStartPost=/bin/echo post2

output

# Setting ExecStart in the second line to null is equivalent to canceling the setting in the first line
execstart2
post1
post2
  • Type field: defines the startup type
    • simple (default): the process started by the ExecStart field is the main process
    • forking: the ExecStart field will be started in the form of fork(). At this time, the parent process will exit and the child process will become the main process
    • oneshot: similar to simple, but executed only once. System D will wait until it is finished before starting other services
    • dbus: similar to simple, but it will start after waiting for the D-Bus signal
    • notify: similar to simple, a notification signal will be sent after startup, and then system D will start other services
    • idle: similar to simple, but the service will not be started until other tasks are completed. One use case is to make the output of this service not mixed with the output of other services
[Service]
Type=oneshot
ExecStart=/usr/bin/touchpad-off start
ExecStop=/usr/bin/touchpad-off stop
RemainAfterExit=yes

If the startup type is set to oneshot, it means that the service only needs to run once and does not need to run for a long time. The RemainAfterExit field is set to yes, which means that the service will still be executed after the process exits

  • KillMode field: defines how system D stops the sshd service

    • Control group (default): all child processes in the current control group will be killed
    • Process: kill only the main process
    • mixed: the main process will receive SIGTERM signal and the sub process will receive SIGKILL signal
    • none: no process will be killed, just execute the stop command of the service
  • RestartSec field: indicates the number of seconds that system D needs to wait before restarting the service. The above example is set to wait 42 seconds

  • Restart field: defines the restart mode of system d after sshd exits

    • no (default): it will not restart after exiting
    • On success: restart only after normal exit (exit status code is 0)
    • On failure: restart only after abnormal exit (exit status code is not 0), including signal termination and timeout
    • On abnormal: restart only after being terminated and timed out by the signal
    • On abort: restart only after receiving the termination signal that is not captured
    • On watchdog: it will restart only after exiting the timeout
    • Always: no matter what the exit reason is, always restart

Restart is set to on failure, which means that sshd will be restarted in case of any unexpected failure. If sshd stops normally (such as executing the systemctl stop command), it will not restart

For daemons, on failure is recommended

[Install] block: define how to Install this configuration file, that is, how to start up
  • WantedBy field: indicates the Target of the service

  • Target means service group and represents a group of services. WantedBy=multi-user.target means that the target of sshd is multi user target.

    This setting is very important because execute systemctl enable sshd When using the service command, sshd A symbolic link of service will be placed in multi-user.com under / etc/systemd/system directory target. In the wants subdirectory

# View multi user All services included in target
$ systemctl list-dependencies multi-user.target

Generally speaking, there are two commonly used targets: one is multi-user Multi line command indicates user status; The other is graphic Target, which represents the status of graphical user, depends on multi-user target

Target's profile

target also has its own configuration file

$ systemctl cat multi-user.target 
# /lib/systemd/system/multi-user.target
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of 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
  • Requires field: basic Run with target
  • Conflicts field: conflict field. If rescue Service or rescue Target is running, multi user Target cannot run, and vice versa
  • After: indicates multi user Target is in basic target , rescue.service, rescue. Start after target, if they start
  • AllowIsolate: allows switching to multi-user using the systemctl isolate command target

Reference articles

Introduction to system D: actual combat

Detailed explanation of Linux | systemd | system Service | parameter analysis

Reference articles

Introduction to system D: actual combat

Detailed explanation of Linux | systemd | system Service | parameter analysis

Topics: Linux IDE