systemd service details

Posted by jassikundi on Fri, 14 Jan 2022 18:06:02 +0100

1, init process evolution

  1. Development of init
    The main purpose of developing system D is to reduce system boot time and computing overhead. SYSTEMd (system management daemon), which was originally authorized by GNU GPL protocol, has now changed to GNU LGPL protocol. It is the most hotly discussed boot and service management program today. If your Linux system is configured to use the system D boot program, it replaces the traditional SysV init, and the startup process will be handed over to system D.

    CentOS5: SysV init,serial 
    CentOS6: Upstart,Parallel, reference ubantu
    CentOS7: Systemd,Parallel, reference MAC
  2. New features of system D:
    (1) Realize parallel startup of services during system boot: services will be started in parallel without dependencies.
    (2) Activate process on demand: if the service is not used immediately, it will not be activated immediately. It is in a semi active state and starts the service when the port is occupied.
    (3) System state snapshot: rollback to a past state.
    (4) Define service control logic based on dependencies.

2, unit service

  1. unit related configuration files:
    unit is identified, identified and configured by its related configuration files. The file mainly contains system services, monitored socket s, saved snapshots and other init related information.
    Location of unit configuration file:

    /lib/systemd/system          Locally configured system unit
    /run/systemd/system          System unit configured at runtime
    /usr/lib/systemd/system      System unit of third party software(sshd,nginx..)
  2. Common types of unit:

    Serviceunit: File extension is.service,Used to define system services;
    Targetunit: File extension,Used to simulate the implementation of "run level";
    Device unit=: File extension is .device,A device for defining kernel recognition;
    Mount unit: File extension is.mount,Define the file system mount point;
    Socketunit: File extension is .socket,Used to identify the data used for inter process communication socket Documents;
    Snapshotunit: File extension is .snapshot, Management system snapshot;
    Swapunit: File extension is .swap, Used to identify swap Equipment;
    Automountunit:  File extension is.automount,File system automatic point device;
    Pathunit: File extension is .path, Used to define a file or directory in a file system;
  3. unit characteristics:

    1)be based on socket Activation mechanism: socket Separated from the program, the socket is allocated first, but the program itself is not started
    2)be based on bus Activation mechanism: activate the device based on the request of the bus
    3)be based on device Activation mechanism: the device is automatically mounted and activated when the device is inserted, and the mount point does not exist and is automatically created
    4)be based on Path Activation mechanism: monitor whether the directory file exists to activate the service or process
    5)System snapshot: save each unit The current state information of the is stored in the persistent storage device;
    6)Backward compatibility sysv init script;  /etc/init.d/The script under is also compatible

3, syscemctl command

  1. Start / close class

    Start: service NAME start ==>  systemctl start NAME.service
     stop it: service NAME stop ==> systemctl stop NAME.service
     Restart: service NAME restart ==>  systemctl restart NAME.service
     Status: service NAME status ==>  systemctl status NAME.service
     Conditional restart: service NAME condrestart  ==>  systemctl try-restart NAME.service
     Reload or restart the service: systemctl reload-or-restart NAME.servcie
     Overload or conditional restart service: systemctl reload-or-try-restart NAME.service
  2. View service class

    To view the current activation status of a service: systemctl is-active NAME.service
     View all activated services: systemctl list-units --type service
     View all services (activated and inactive):chkconfig --lsit  ==>  systemctl list-units -t service --all
  3. Boot settings class

    Set the service to start automatically: chkconfig NAME on ==>  systemctl enable NAME.service
     Prohibit service startup: chkconfig NAME off ==>  systemctl disable NAME.service
     Check whether a service can be started automatically: chkconfig --list  NAME ==>  systemctl is-enabled NAME.service
     Prohibit a service from being set to start automatically: systemctl mask NAME.service
     Cancel this prohibition: systemctl unmask NAME.servcie
     List all installed services and their status: systemctl list-unit-files
     List the services that failed to start: systemctl --failed
     List a type( service, mount, device, socket, target)Services: systemctl --type=mount
     Will one shell Script set to boot: systemctl enable debug-shell.service
  4. View dependency classes

    To view Service Dependencies: systemctl list-dependencies NAME.service
  5. Manage target units:

    Run level correspondence:
     0  ==>,
     1  ==>,
     2  ==> runlevel2.tartet,
     3  ==> runlevel3.tartet,
     4  ==> runlevel4.tartet,
     5  ==>,
     6  ==>,

    Related commands:

    Level switching: init N ==>  systemctl isolate
     View level: runlevel  ==>  systemctl list-units --type target
     View all levels: systemctl list-units -t target -a
     Get default run level: systemctl get-default 
    Modify the default run level: systemctl set-default
     Switch to emergency rescue mode: systemctl rescue
     Switch to emergency pattern: systemctl emergency
  6. Other common commands:

    Shutdown: systemctl halt, systemctl poweroff
     Restart: systemctl reboot
     Pending: systemctl suspend
     Snapshot: systemctl hibernate
     Snapshot and suspend: systemctl hybrid-sleep

4, Service unit file: service unit file

  1. /usr/lib/systemd/system and / etc/systemd/system relationships
    /etc/systemd/system sets the default running level and the running relationship of the service at startup, and connects the file.
    General administrators can define some service unit file files under / etc/systemd/system.
  2. service unit file format

    [root@ss01 system]# cat firewalld.service
    Description=firewalld - dynamic firewall daemon
    Conflicts=iptables.service ip6tables.service ebtables.service ipset.service
    ExecStart=/usr/sbin/firewalld --nofork --nopid $FIREWALLD_ARGS
    ExecReload=/bin/kill -HUP $MAINPID
    # supress to log debug and error output also to /var/log/messages

    [Unit]: define general options independent of Unit type; It is used to provide Unit description information, Unit behavior and dependency relationship;
    [Service]: special options related to specific types; Here is the Service type;
    [Install]: define the options used by the "systemctl: enable" and "systemctl: disable" commands to enable or disable the service;

    (1) Unit Common options for segments:
     Description: Descriptive information; Meaningful description;
     After: definition unit Start up sequence of; Represents the current unit What should be later unit Start up; Its function and Before contrary;
     Requies: Other dependent units;Strongly dependent units When cannot be activated, the current unit That is, it cannot be activated;
     Wants: Other dependent units;Weak dependence;
     Conflicts: definition units Conflict relationship between;
    (2)Service Common options for segments:
     Type: Used to define the impact ExecStart And related parameters unit Process startup type. Types are:
         simple: Default. from ExecStart The process started by the specified process is the main process
         forking: from ExecStart A child process generated by the started process is the main process, and the parent process exits
         oneshot: One time start, follow-up unit After the process starts, the process exits
         dbus: Only after getting dbus Before it was launched
         notify: Cannot run until notification is sent
         idle: be similar to simple
     EnvironmentFile: Environment profile for ExecStart Provide some variables;
     ExecStart: Indicates start unit To run a command or script; ExecStartPre, ExecStartPost
     ExecStop: Indicate stop unit The command or script to run;
     Restart: If this item is started, the script will be restarted automatically if it is terminated unexpectedly
    (3)Install Common options for segments:
     Alias: current unit Alias for
     RequiredBy: By what units Rely on;
     WantedBy: By what units Rely on;

    Note: for newly created unit files or modified unit files, notify systemd to reload this configuration file;

    [root@ss01 system]# systemctl daemon-reload
  3. Write the unit file and register it with the systemd service

    Step 1: prepare a shell script
    [root@ss01 system]# vim /root/
       echo `hostname`>/tmp/name.log
    Step 2: create unit file
    [root@ss01 system]# vim my.service
       Description=this is my first unit file
       ExecStart=/bin/bash /root/
    [root@ss01 system]# mv my.service /usr/lib/systemd/system
    Step 3: put my unit File registration to systemd in
    [root@ss01 system]# systemctl enable my.service
    Step 4: view the status of the service
    [root@ss01 system]# systemctl status my.service

5, journalctl log:

  1. Common commands:

    Display all logs on the system and its users: journalctl --all
     Monitor system log changes: journalctl -f
     Display logs after system startup: journalctl -b
     Show last(-b -1)Kernel log generated before system startup: journalctl -k -b -1
     Displays the information generated after the system is started“ ERROR"journal: journalctl -b -p err 
    display cron Log printed by the service in a certain period of time: journalctl -u cron.service --since='2022-01-06 07:00' --until='2022-01-06 08:23'
    Show logs with priority less than 2: journalctl -p 2 --since=today
     Copy the binary log file into a text file and save it to the current directory: journalctl > testlog.log
     To view the log of a script for a path: journalctl /usr/bin/bash
     Display the hard disk space occupied by the log: journalctl --disk-usage
     Specify the maximum space occupied by the log file: journalctl --vacuum-size=1G
     Specify how long the log file will be saved: journalctl --vacuum-time=1years
    All log levels are:
    emerg (0), alert (1), crit (2), err (3), warning (4), notice (5), info (6), debug (7)

6, SYSTEMd analyze system startup process:

  1. Analyze the system startup process with systemd:

    Display the time spent in user mode and kernel mode during system startup: systemd-analyze
     Show details of the time spent on each startup item: systemd-analyze blame 
    Print in chronological order UNIT Tree: systemd-analyze critical-chain
     Generate vector diagram for startup process (installation required) graphviz Package: systemd-analyze dot | dot -Tsvg > systemd.svg 
    Generate time chart of startup process: systemd-analyze plot > bootplot.svg

7: grub2 command

  1. grub2 configuration file: / etc/default/grub

    [root@ss01 ~]# cat /etc/default/grub
    # Specify user selection menu timeout
    # Specifies the description name in the menu
     GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)"
    # GRUB specifies which is the default title
    # save means that the current configuration will be saved, which needs to be combined with a built-in variable
    # Disable submenu
    # Specifies that the information during startup is output to the terminal
    # When starting the system, pass parameters to the kernel in the form of command line
     GRUB_CMDLINE_LINUX="crashkernel=auto rhgb "
     # Specifies whether to display startup process information
  2. Customize grub2's configuration file

    Step 1: back up the original grub.cfg
    [root@ss01 ~]# cp /boot/grub2/grub.cfg{,.bak}
    Step 2: modify/etc/default/grub
    Step 3: Regenerate grub.cfg
    [root@ss01 ~]# grub2-mkconfig>/boot/grub2/grub.cfg

8: Change password in single user mode

  1. Enter emergency rescue mode

    Entry mode: when starting the system, edit the kernel options and add rd.break,Then press ctrl+x
     After entering rescue mode:
     a. Root in sysroot lower
     b. Is currently read-only
  2. Operation:

    # mount -o remount,rw /sysroot
    # chroot /sysroot
    # echo '******' | passwd --stdin root
    # exit
    # reboot

Topics: Linux