Linux basic study notes-understanding system services (daemon)

Understanding system services (daemon)

1. What is a daemon and service (service)

Service: A program that is resident in memory and can provide some system or network functions, that is, service . The program that achieves this service is called a daemon.


1.1. The main classification of daemon in the early System V init management behavior (Optional)

In the early system, the way we started the system service management was called the init script processing way of Sys V! That is, the first program called by the system kernel is init, and then init invokes all the services required by the system, whether it is a local service or a network service. Basically, the init management mechanism has several characteristics as follows:

  • How to start, close and observe the service :

    All service startup scripts are placed under /etc/init.d/ . Basically, they are scripts written in bash shell script. When you need to start, shut down, restart, and observe the status, you can use the following methods:

    • Start: /etc/init.d/daemon start
    • Shut down: /etc/init.d/daemon stop
    • Restart: /etc/init.d/daemon restart
    • Observe the status: /etc/init.d/daemon status
  • Classification of service startup :

    In the classification of init services, the services are divided into two categories based on whether they are started independently or managed by a supervisor program:

    • Stand alone mode (stand alone) : the service starts independently, the service directly resides in the memory, provides the service behavior of the machine or the user, and the response speed is fast ;
    • Super daemon (super daemon) : special xinetd or inetd these two programs provide socket correspondence or port correspondence management. When there is no user requesting socket or port, the required service will not be started. If the user requests, the xinetd manager will wake up the corresponding service. When the request ends, the service will also be ended .
  • Service dependency

  • Class classification performed :

    The init mentioned above is actively called by the kernel after booting, and then init can wake up different services according to the user-defined execution level (runlevel) to enter different operation interfaces . Basically, Linux provides 7 execution levels, which are 0, 1,..., 6. The more important ones are (1) single maintenance mode, (3) plain text mode, and (5) text plus graphical interface . The startup script of each execution level is linked to /etc/init.d/daemon through: /etc/rc.d/rc[0-6]/SXXdaemon, the function of the link file is: S is to start the service, XX is The numbers are the order of startup. Due to the SXX setting, all required services can be “executed in sequence” when booting, and the problem of dependency can also be solved.

  • Define the services to be started by default at the execution level :

    If you want to create the SXXdaemon mentioned above, you don’t need the administrator to manually create a connection file. Use the following commands to handle the default activation, default non-activation, and observe whether the preset is activated or not:

    • Start by default: chkconfig daemon on
    • Not activated by default: chkconfig daemon off
    • Observe that the default is to start or not: chkconfig --list daemon
  • Perform level switching :

    When you want to switch from the plain text interface (lrunevel 3) to the graphical interface (runlevel 5), you don't need to manually start and close the related services of the execution level, just "init 5" to switch .

1.2, the unit classification used by systemd

After CentOS 7.x, the systemd startup service management mechanism should be used:

  • All programs are processed in parallel to speed up the boot process :

    The old init startup script was a "task-by-task startup" model, so non-adjacent services also have to wait one by one. The current hardware architecture and operating system support multi-core architecture, so parallel startup is supported.

  • The on-demand startup method that responds upon request :

    Systemd is all that there is only one systemd service with systemctl command to process, no other additional command support is needed. In addition, because systemd is resident in memory, any request (on-demand) can immediately handle subsequent daemon startup tasks.

  • Self-check of service dependency :

    Since systemd can customize the service dependency check, if service B is started on service A, then when you only start service B manually without starting service A, systemd will automatically start service A for you .

  • Classified by daemon function :

    Systemd manages a lot of services. In order to clarify all service functions, first systemd first defines all services as a service unit (unit), and classifies the unit into different service types (types). systemd divides service units into different types such as service, socket, target, path, and timer.

  • Collect multiple daemons into a group :

  • Backward compatible with init service script .

Even so, there are some places where systemd cannot completely replace init! include:

  • In the correspondence of runlevel, probably only runlevel 1, 3, 5 have corresponding target types of systemd, not all of them correspond;
  • All systemd is managed by the management program systemctl, and the syntax supported by systemctl is limited. Unlike /etc/init.d/daemon, which is a pure script that can customize parameters, systemctl cannot customize parameters;
  • If a certain service is started by the administrator himself, instead of using systemctl to start, then systemd will not be able to detect the service, and thus cannot be further managed;
  • During the systemd startup process, it is not possible to communicate with the administrator through standard input! Therefore, when writing systemd startup settings, you must cancel the interactive mechanism.

1.2.1. Placement of systemd configuration files

Basically, systemd refers to the so-called daemon execution script in the past as a service unit (unit), and when each service unit is distinguished by function, it is classified into different types (type). The basic types include system services , data monitoring and exchange of slot file services (socket) , storage system state snapshot types , **providing different operating environments (targets) of similar execution levels** and so on.

/usr/lib/systemd/system/	#每个服务最主要的启动脚本设定,有点类似于以前的/etc/init.d底下的文件;
/run/systemd/system/		#系统执行过程中所产生的服务脚本,这些脚本优先级要比/usr/lib/systemd/system/高;
/etc/systemd/system/	#管理员依据主机系统的需求所建立的执行脚本,其实这个目录优点类似于以前的/etc/rc.d/rc5.d/Sxx,执行优先级比/run/systemd/system/高!

That is to say, the fact that the system will not execute certain services when it is turned on is actually based on the settings under /etc/systemd/system/ , so there are a lot of link files under this directory . The actual systemd startup script configuration files are all under /usr/lib/systemd/system/ . /etc/systemd/system/ is just a link to the configuration file to execute the script correctly. So if you want to see the execution script settings, you should check it under /usr/lib/systemd/system/!

1.2.2, systemd's unit type classification description

How do the data below /usr/lib/systemd/system/ distinguish the so-called different types mentioned above? Just look at the extension.

[root@li ~]# ll /usr/lib/systemd/system/ | grep -E '(vsftpd|multi|cron)'
-rw-r--r--. 1 root root  318 8月   9 2019 crond.service
-rw-r--r--. 1 root root  492 8月   7 01:30 multi-user.target
drwxr-xr-x. 2 root root  258 8月  17 10:27 multi-user.target.wants
lrwxrwxrwx. 1 root root   17 8月  17 10:27 runlevel2.target -> multi-user.target
lrwxrwxrwx. 1 root root   17 8月  17 10:27 runlevel3.target -> multi-user.target
lrwxrwxrwx. 1 root root   17 8月  17 10:27 runlevel4.target -> multi-user.target

Several common systemd service types are as follows:

extension name Main service function
.service General service types: mainly system services, including local services and network services required by the server itself!
.socket Slot service for internal program data exchange
.target Execution environment type: actually a collection of a group of units
.mount
.automount
File system mounting related services
.path Detect specific file or directory type
.timer Cyclic service

2. Manage services through systemctl

2.1. Manage the startup/startup and observation status of a single service through systemctl

[root@li ~]# systemctl [command] [unit]
command主要有:
	start			:立刻启动后面的 unit
	stop			:立刻关闭后面的 unit
	restart			:立刻关闭后启动后面的 unit
	reload			:不关闭后面的 unit 的情况下,重载配置文件,让设定生效
	enable			:开机自启
	disable			:取消开机自启
	status			:显示 unit 的状态
	is-active		:目前有没有正在运行
	is-enable		:开机时有没有预设要启动 unit
#1、查看 crond 这个服务的状态信息
[root@li ~]# systemctl status crond.service
● crond.service - Command Scheduler
   Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
   Active: active (running) since 三 2020-08-19 15:58:41 CST; 9min ago
 Main PID: 664 (crond)
   CGroup: /system.slice/crond.service
           └─664 /usr/sbin/crond -n

8月 19 15:58:41 li.erver systemd[1]: Started Command Scheduler.
8月 19 15:58:41 li.erver crond[664]: (CRON) INFO (RANDOM_DELAY will be scaled with factor 1...d.)
8月 19 15:58:42 li.erver crond[664]: (CRON) INFO (running with inotify support)
Hint: Some lines were ellipsized, use -l to show in full.
#重点在第 2,3 行
#Loaded:说明开机的时候这个 unit 会不会自启,enabled 为开机自启,disabled 为开机不会自启
#Active:现在这个 unit 的状态是正在执行(running)或没有执行(dead)

#2、正常关闭这个服务
[root@li ~]# systemctl stop crond
[root@li ~]# systemctl status crond.service
● crond.service - Command Scheduler
   Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since 三 2020-08-19 16:11:52 CST; 2s ago
  Process: 664 ExecStart=/usr/sbin/crond -n $CRONDARGS (code=exited, status=0/SUCCESS)
 Main PID: 664 (code=exited, status=0/SUCCESS)

8月 19 15:58:41 li.erver systemd[1]: Started Command Scheduler.
8月 19 15:58:41 li.erver crond[664]: (CRON) INFO (RANDOM_DELAY will be scaled with factor 1...d.)

Back to the third line of systemctl status crond.service, isn't there an Active daemon's current status code? Apart from running and dead, are there other states? Basically, the common states are as follows:

  • active (running): execute
  • active (exited): A service that ends normally after being executed only once, and no program is currently being executed in the system
  • active (waiting): is being executed, but it has to wait for other events to continue processing
  • inactive (dead): not executing

In addition to enable/disable for the default state of the daemon, are there other situations?

  • enabled: boot is executed
  • disabled: not executed when booting
  • static: It cannot be started by itself, but may be awakened by other programs
  • masked: Can't start anyway

2.1.1, practice of service startup/shutdown and observation

Because this server does not have a printer, I want to turn off the cups service. Is it okay?

#1、先看看 cups 的服务是开的还是关的?
[root@li ~]# systemctl status cups.service
● cups.service - CUPS Printing Service
   Loaded: loaded (/usr/lib/systemd/system/cups.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since 三 2020-08-19 16:24:19 CST; 1s ago
  Process: 10391 ExecStart=/usr/sbin/cupsd -f (code=exited, status=0/SUCCESS)
 Main PID: 10391 (code=exited, status=0/SUCCESS)
 #有趣的是,竟然是 enable 但还却是 head
 
 #2、那就直接关闭,同时确认没有启动
 [root@li ~]# systemctl stop cups.service
[root@li ~]# systemctl disable cups.service
Removed symlink /etc/systemd/system/multi-user.target.wants/cups.path.
Removed symlink /etc/systemd/system/multi-user.target.wants/cups.service.
Removed symlink /etc/systemd/system/sockets.target.wants/cups.socket.
Removed symlink /etc/systemd/system/printer.target.wants/cups.service.
#一口气关掉了 4 个连接文件,说明这 4 个文件有相依赖的关系

[root@li ~]# netstat -tulnp | grep cups
#不会产生任何数据

#3、尝试启动 cups.socket 监听客户端的需求
[root@li ~]# systemctl start cups.socket
[root@li ~]# systemctl status cups.socket cups.service cups.path
● cups.socket - CUPS Printing Service Sockets
   Loaded: loaded (/usr/lib/systemd/system/cups.socket; disabled; vendor preset: enabled)
   Active: active (listening) since 三 2020-08-19 16:28:35 CST; 22s ago
   Listen: /var/run/cups/cups.sock (Stream)

8月 19 16:28:35 li.erver systemd[1]: Listening on CUPS Printing Service Sockets.

● cups.service - CUPS Printing Service
   Loaded: loaded (/usr/lib/systemd/system/cups.service; disabled; vendor preset: enabled)
   Active: inactive (dead)

8月 19 16:23:32 li.erver systemd[1]: Started CUPS Printing Service.
8月 19 16:24:19 li.erver systemd[1]: Stopping CUPS Printing Service...
8月 19 16:24:19 li.erver systemd[1]: Stopped CUPS Printing Service.

● cups.path - CUPS Printer Service Spool
   Loaded: loaded (/usr/lib/systemd/system/cups.path; disabled; vendor preset: enabled)
   Active: inactive (dead)
#仅有 cups.socket 在启动

#4、尝试使用 lp 这个指令打印看看
[root@li ~]# echo "testing" | lp
lp: Error - no default destination available.
#实际上就是没有打印机,显示错误也没关系

[root@li ~]# systemctl status cups.service
● cups.service - CUPS Printing Service
   Loaded: loaded (/usr/lib/systemd/system/cups.service; disabled; vendor preset: enabled)
   Active: active (running) since 三 2020-08-19 16:30:17 CST; 38s ago
[root@li ~]# netstat -tulnp | grep cups
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      12876/cupsd       
tcp6       0      0 ::1:631                 :::*                    LISTEN      12876/cupsd
#竟然自己启动了,我们并没有启动它

As can be seen from the above case, many services are interdependent. cups is a printing service, this service will start port 631 to provide the printing function of the network printer. But in fact, we don't need to enable port 631 all the time. Therefore, there is an extra cups.socket service. This service can only wake up cups.service when users have printing needs. Therefore, if you just disable/stop cups.service and forget the other two services, then when the user makes a request to the other two cups.path and cups.socket, cups.service will be awakened!

2.1.2. Practice for forced service cancellation (mask)

The more formal way is to close cups.service, together with the other two will wake up cups.socket and cups.path are all closed, then it's fine. The more informal approach is to force cups.service to log off.

[root@li ~]# systemctl stop cups.service
Warning: Stopping cups.service, but it can still be activated by:
  cups.socket	#警告就说明了,cups.service 就算是关闭了还是会被唤醒
[root@li ~]# systemctl mask cups.service
Created symlink from /etc/systemd/system/cups.service to /dev/null.

[root@li ~]# systemctl status cups.service
● cups.service
   Loaded: masked (/dev/null; bad)
   Active: inactive (dead) since 三 2020-08-19 16:37:35 CST; 1min 23s ago
 Main PID: 12876 (code=exited, status=0/SUCCESS)
 
 [root@li ~]# systemctl start cups.service
Failed to start cups.service: Unit is masked.	#再也无法唤醒

How to cancel logout? Of course, it is unmask:

[root@li ~]# systemctl unmask cups.service
Removed symlink /etc/systemd/system/cups.service.

[root@li ~]# systemctl status cups.service
● cups.service - CUPS Printing Service
   Loaded: loaded (/usr/lib/systemd/system/cups.service; disabled; vendor preset: enabled)
   Active: inactive (dead) since 三 2020-08-19 16:37:35 CST; 3min 21s ago
 Main PID: 12876 (code=exited, status=0/SUCCESS)

2.2. Observe all services on the system through systemctl

[root@li ~]# systemctl [command] [--type=TYPE] [--all]
command:
	list-units			:依据 unit 列出目前启动的 unit。若加上 --all 才会列出没启动的
	list-unit-files		:依据 /usr/lib/systemd/system 内的文件,将所有文件列表说明
#1、列出系统上所启动的 unit
[root@li ~]# systemctl
  UNIT                                LOAD   ACTIVE SUB       DESCRIPTION
  -.mount                             loaded active mounted   /
  boot.mount                          loaded active mounted   /boot
  dev-hugepages.mount                 loaded active mounted   Huge Pages File System
  dev-mqueue.mount                    loaded active mounted   POSIX Message Queue File System
  run-user-0.mount                    loaded active mounted   /run/user/0
  ...

#2、列出所有已经安装的 unit 有哪些
[root@li ~]# systemctl list-unit-files
UNIT FILE                                     STATE
proc-sys-fs-binfmt_misc.automount             static
dev-hugepages.mount                           static
dev-mqueue.mount                              static
...

If I don't want to know so many unit projects, I only want to know the daemon of the service type, and list them all regardless of whether they have been started:

[root@li ~]# systemctl list-units --type=service --all
  UNIT                                LOAD      ACTIVE   SUB     DESCRIPTION
  auditd.service                      loaded    active   running Security Auditing Service
● cloud-init-local.service            not-found inactive dead    cloud-init-local.service
  cpupower.service                    loaded    inactive dead    Configure CPU power related setti
  crond.service                       loaded    active   running Command Scheduler
...

#查询系统上是否有以 cpu 为名的服务
[root@li ~]# systemctl list-units --type=service --all | grep cpu
  cpupower.service       loaded    inactive dead    Configure CPU power related settings

2.3. Manage different operating environments (target unit) through systemctl

How to list the target items related to the operation interface comparison?

[root@li ~]# systemctl list-units --type=target --all
  UNIT                      LOAD      ACTIVE   SUB    DESCRIPTION
  basic.target              loaded    active   active Basic System
  cryptsetup.target         loaded    active   active Local Encrypted Volumes
  emergency.target          loaded    inactive dead   Emergency Mode
  ...
LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

32 loaded units listed.
To show all installed unit files use 'systemctl list-unit-files'.

There are 32 target units by default, and the targets that are more relevant to the operation interface mainly include the following:

  • graphical.target : It is text plus a graphical interface. This project includes the multi-user.target project below!
  • multi-user.target : Plain text mode!
  • rescue.target : In the case that root login is not possible, systemd will add an extra temporary system when booting, which has nothing to do with your original system. At this time you can obtain root authority to maintain your system. But at this time additional system, so you may need to move to chroot to get your original system.
  • emergency.target : To deal with system errors urgently, or you need to log in with root. If you cannot use rescue.target, you can try this mode.
  • shutdown.target : is the process of shutdown.
  • getty.target : You can set how many ttys you need. If you want to lower the tty items, you can modify the configuration file of this thing.
[root@li ~]# systemctl [conmand] [unit.target]
选项与参数:
command:
	get-default:取得目前的 target
	set-default:设定后面的 target 为默认的操作模式
	isolate:切换到后面的模式
#我们没有安装图形界面,应该是纯文本模式
[root@li ~]# systemctl get-default
multi-user.target	#纯文本模式

Under normal switching conditions, use the isolate method described above. However, for convenience, systemd also provides several simple commands for us to switch the operating mode:

[root@li ~]# systemctl poweroff	#关机
[root@li ~]# systemctl reboot	#重启
[root@li ~]# systemctl suspend	#暂停模式
[root@li ~]# systemctl hibernate	#休眠模式
[root@li ~]# systemctl rescue	#救援模式
[root@li ~]# systemctl emergency	#紧急模式
  • suspend: The suspend mode saves the state of the system to the memory, and then shuts down most of the system hardware, of course, there is no actual shutdown. When the user presses the button to wake up the machine, the system data will be restored from the memory and then re-drive most of the hardware. Wake up faster.
  • hibernate: Hibernate mode saves the system state to the hard disk. After saving, shut down the computer. When the user wakes up the system, the system will start to work normally, and then restore the system state saved to the hard disk. Because it is read from the hard disk, the speed is slower.

3. Analyze the dependencies between services through systemctl

[root@li ~]# systemctl list-dependencies [unit] [--reverse]
选项与参数:
--reverse:反向追踪谁在使用这个 unit 的意思!
#1、列出目前的 target 环境下,用到什么特别的 unit
[root@li ~]# systemctl get-default
multi-user.target
[root@li ~]# systemctl list-dependencies
default.target
● ├─auditd.service
● ├─crond.service
● ├─dbus.service
● ├─firewalld.service
● ├─irqbalance.service
● ├─kdump.service
● ├─network.service
● ├─NetworkManager.service
...

Default.target will use the three major projects basic.target + getty.target + remote-fs.target. So how to find out who uses multi-user.target?

[root@li ~]# systemctl list-dependencies --reverse
default.target
● └─graphical.target

4. Directory introduction related to systemd daemon operation process

  • /usr/lib/systemd/system/

    After installing with the official software provided by CentOS, the default startup script configuration files are placed here. Try not to modify the files here. If you want to modify, please go to /etc/systemd/system/ to modify.

  • /run/systemd/system/

    Scripts generated during system execution have higher execution priority than /usr/lib/systemd/system/!

  • /etc/systemd/system/

    The execution script created by the administrator based on the host system's requirements is actually a bit like the previous /etc/rc.d/rc5.d/Sxx and other functions. The priority is higher than /run/systemd/system/!

  • /etc/sysconfig/*:

    Almost all services will write some initial option settings into this directory. For example, the network settings are written in the /etc/sysconfig/network-srcipts/ directory.

  • / var / lib /

    Some services that generate data will write its data to the /var/lib/ directory. For example, the database of the database management system MySQL is written to the directory /var/lib/mysql by default.

  • /run/

    A lot of temporary files of daemon are placed, including lock file and PID file.

Guess you like

Origin blog.csdn.net/qq_36879493/article/details/108108174