The SYSTEMD mechanism of Linux initialization

Source: Internet
Author: User
Tags locale arch linux

SYSTEMD is an init software under Linux, developed by Lennart Poettering, whose development goal is to provide a better framework to represent the dependencies between system services, and to implement parallel start-up of services when the system is initialized. At the same time, the effect of reducing the overhead of the shell is finally replaced by the System V and BSD style init programs that are commonly used today. Traditional sysvinit use Inittab to decide which shell scripts to run, and a large number of shell scripts are thought to be the reason why inefficiencies cannot be parallelized. SYSTEMD uses proprietary Linux technology and no longer takes into account POSIX compatibility.

Design concept

Compared to the System V style init used in most distributions, SYSTEMD uses the following new technologies:

Using socket-activated and d-bus-activated services to improve the performance of parallel operation of each dependent service;

Use cgroups instead of PID to track the process so that the daemons generated even after two fork are not out of systemd control.

From the design concept, because SYSTEMD uses components such as cgroup and fanotify to achieve its characteristics, it is only applicable to Linux. In view of this, Debian developers try to avoid the inclusion of SYSTEMD, considering that the KFREEBSD branch's software source cannot be incorporated into the SYSTEMD and is consistent with other branches.

Application scope

SYSTEMD has been included in the software sources for many Linux distributions, the following summary:

The default init program is the release version of SYSTEMD

Fedora 15 and subsequent versions

Mageia 2[10]

Mandriva 2011[11]

OpenSUSE 12.1 and later [12]

Arch Linux incorporated Systemd-sysvcompat into the base software group on October 13, 2012, with SYSTEMD as the INIT program since the default installation of Arch Linux [13]. It also provides a SYSTEMD startup script package that is compatible with the Arch self-starter script to make it easy for users to "out of the Box" [14]

Chakra Gnu/linux, SYSTEMD is used by default after 2012.10 of disc image files are published. [15]

You can use the release version of SYSTEMD

Debian Gnu/linux, available in the "testing" branch source [16], and in the 2014 Technical Committee's INIT system poll, decided to convert the Linux-centric version to systemd[17 in the Debian 8 "Jessie".

Gentoo, with OPENRC by Gentoo official support [18][19][20]

In addition, SYSTEMD has been drawn by Lennart Poettering into the list of external dependencies for GNOME 3.2 [21], which means that all distributions using GNOME should use SYSTEMD, which at least must be used as one of the configuration options.

Some other distributions include it as a substitute for upstart and Sysvinit.

systemd features

SYSTEMD opening and overseeing the entire system is based on the concept of unit. Unit is made up of a name and type corresponding to the configuration file . ( For example: theavahi.service unit has a configuration file with the same name, which is A package unit of the daemon Avahi ). the unit has several types:

Service: The boot, stop, restart, and reload of the daemon are some of the most obvious types of such a unit.

Socket: This type of unit package system and a socket in the Internet. Now, SYSTEMD supports Af_inet, AF_INET6, Af_unix sockets for streaming, datagram, and sequential packets. The traditional FIFOs transmission mode is also supported. Each socket unit has a corresponding service unit. The corresponding service starts when the first "connection" enters the socket or FIFO (for example: Nscd.socket starts nscd.service after a new connection).

Device: This class unit encapsulates a device that exists in the Linux device tree. Each device marked with Udev rules will appear as a device unit in SYSTEMD. Udev's property settings can be used as a configuration source for configuring device unit dependencies.

Mount: This type of unit encapsulates a mount point in the system hierarchy.

AutoMount: A self-mounting point in the structure hierarchy of this unit encapsulation system. Each self-mounted unit corresponds to a mounted unit (which needs to be mounted as soon as the self-mounted directory can be accessed).

Target: This class of unit logically groups other unit. They don't actually do anything themselves, they just cite other unit. This allows for a unified control of the unit. (For example: Multi-user.target is equivalent to running level 5 in a system that traditionally uses SysV); Bluetooth.target calls Bluetooth-related services only if the Bluetooth adapter is available, such as: Bluetooth daemon, Obex Daemon, etc.)

Snapshot: Similar to target unit, the snapshot itself does nothing and the only purpose is to refer to the other unit.

systemd the Tools

    • Systemctl: Used as a state for introspection and control of SYSTEMD systems and service managers.
    • Systemd-cgls: Displays the hierarchical hierarchy of selected Linux control groups in a tree-shaped recursion.
    • Systemadm: A graphical front end for the SYSTEMD system and service Manager. is part of the SYSTEMD-GTK software package. This is only a previous version, still needs to be perfected. Unless you are a developer, do not use it.

SYSTEMD contains its own configuration and diagnostic tools, and the techniques used to handle system startup problems are different from sysvinit. Due to its compatibility with upstart and sysvinit, our familiar commands and tricks in the release version of these two initialization tools also apply to SYSTEMD.

a Systemctl Command

The main command to view and control Systemd is systemctl. This command can be used to view system status and manage systems and services. See Man 1 Systemctl. The tool requires root privileges to change the configuration file or restart the daemon, but even non-root users can release some diagnostic commands. If you do not add any parameters when you start the command, you will see a "unit" list that performs the task when the system starts, including mounting and detecting disks, starting the background service, and configuring the hardware.

1 ) outputs the active unit :

$ systemctl

The following commands are equivalent:

$ systemctl List-units

Outputs the unit that failed to run:

$ systemctl--failed

all available unit files are stored in the /usr/lib/systemd/system/ and the /etc/systemd/system/ directory (the latter has a higher priority). to view all installed services:

$ systemctl List-unit-files

2 ) using the unit

A unit configuration file can describe one of the following: System service (. Service), Mount Point (. Mount), sockets (. Sockets, System device, swap partition/file, boot target, file system path, timer managed by SYSTEMD). See man 5 systemd.unit for details.

When using the Systemctl control unit, you typically need to use the full name of the cell file, including the extension (for example, Sshd.service). However, some units can use shorthand in Systemctl.

    • If there is no extension, systemctl defaults to the extension as. Service. For example Netcfg and Netcfg.service are equivalent.
    • The mount point is automatically converted to the corresponding. Mount unit. For example,/home is equivalent to Home.mount.
    • The device is automatically converted to the corresponding. Device unit, so/dev/sda2 is equivalent to Dev-sda2.device.

Activate the unit now:

# Systemctl Start < units >

To stop the unit immediately:

# Systemctl Stop < unit >

Restart Unit:

# Systemctl Restart < units >

The command unit re-reads the configuration:

# Systemctl Reload < units >

Output Unit Run Status:

$ SYSTEMCTL Status < units >

Check whether the unit is configured to start automatically:

$ systemctl is-enabled < units >

Automatic activation Unit:

# Systemctl Enable < units >

Note : If the service does not have an install paragraph, it generally means that it should be called automatically through other services. If you really need to install manually, you can connect directly to the service as follows (replace Foo with the real service name):

# ln-s/usr/lib/systemd/system/foo.service/etc/systemd/system/graphical.target.wants/

To cancel the power-on auto-activation unit:

# Systemctl Disable < units >

The manual page of the display unit (must be provided by the unit file):

# Systemctl Help < units >

Reload the SYSTEMD to scan for new or changed units:

# Systemctl Daemon-reload

3 ) Service

Service units are one of the most important units because they manage back-end services, and in the release version of Sysvinit, they are typically started using initialization scripts. Mount (Mount) and Auto Mount (automount) units are used to mount the file system.

Socket (socket) units are used to create sockets and, immediately after the socket is accessed, start another unit indirectly with a dependency. You can use parameters to let Systemctl list only one type of unit, such as all service units: Systemctl--type=service

The SYSTEMD automatically submits its output to the less display; you can scroll up and down not only with the arrow keys, but also to the right because sometimes more information is occasionally "hidden" there.

The first column in the list is the name of the unit,

The second column indicates whether the definition of the unit has been correctly loaded by SYSTEMD.

The third column tells us if the unit is running. If you use the-a parameter, the program displays only the units that are not running, that is, the units that were installed but not used at startup, and also contains the unit files that the boot system did not load properly (the reason is likely to be an error for that unit file).

Column four gives the current status: "Exited" indicates that the process has been completed without any errors, which applies to a situation such as a process that does not continue to run in the background after startup, for example, when the system starts due to the compatibility factors that are commonly used in Sysvinit/etc/rc.d/ The service unit for the rc.local file. "Running" represents services that are running in the background, such as Cron, Dbus, sshd, and Udev.

Column Five is a description of the unit. Units labeled "LSB" or "SYSV" have been automatically created by SYSTEMD to manage traditional startup scripts.

Services that fail to start or crash after startup are labeled "Failed" in red in the fourth column (if the terminal can display color). You can look at the following commands to see when the service crashed and what error code was provided after the service program ended:

Systemctl Status Ntpd.service

For a newly installed Linux Deepin 12.06,systemctl will list about 50 service units, including the text terminal login process (agetty). Because Systemd is different from Sysvinit, it manages these processes in the form of service units as well as managing normal back-office services.

4) Unit files and targets (target)

One unit of processing

The system configuration file used to create the unit is located in/lib/systemd/system/, but the file with the same name in the/etc/systemd/system directory takes precedence over the former.

The definition of a unit file is usually much shorter than the traditional sysvinit script. For example, a service that synchronizes network time through NTP has just a few lines:

[Unit]

Description=network Time Service

[Service]

Execstart=/usr/bin/ntpd-n-U ntp:ntp-g

[Install]

Wantedby=multi-user.target

1) All unit files contain a section beginning with [unit], which contains general settings and simplified

2) The [Service] section contains the specified settings for the tasks to be performed for the service-for NTP, only the command line to start the service is required. If you need to terminate the program with a specified command, you can use execstop= to set it up. This step is not necessary for the NTP daemon because it can be ended with a simple "SIGTERM" signal based on the Unix tradition. If no other command is specified, this command tells SYSTEMD to end the task.

3) The [Install] section contains the instructions to be interpreted by the SYSTEMD at (anti) installation; In the case of NTP here, the content means that the time should be synchronized when the multi-user target is activated.

Two goals

The concept of the "target" unit is similar to that of sysvinit; in fact, to consider compatibility, SYSTEMD even recognizes the name of the runlevel that corresponds to the target. Therefore, you can add single to the kernel line in the bootloader, and Systemd activates the rescue.target, providing a minimal interface equivalent to one-user mode.

In Systemd, multi-user mode (that is, the mode of fully booting the system without using the graphical login interface) is represented by Multi-user.target and can be set as the default startup target by this link:

Ln-sf/lib/systemd/system/multi-user.target/etc/systemd/system/default.target

If you do need to start the graphical login interface by default, you can set the Graphical.target as the default target in the same way. This equates to the run level 5 of the traditional initialization tool. You can also specify the target units you want to start in the boot loader for kernel:

Systemd.unit=multi-user.target

If you want to activate a different target unit during the operation, you can use the Systemctl isolate command (Root permission required):

Systemctl Isolate Rescue.target

Switching to a rescue target is useful for administrative tasks, and Systemd stops all user logins and background services, only system services are running, such as monitoring the Logical Volume Service (lvm2-monitor). Sometimes even these services need to be stopped and reinstalled, and you can use Emergency.target to enter emergency mode (emergency modes), when only the command prompt process and kernel threads are running.

three Systemctl Command replaced the RC.D Command

Boot module loading

/etc/modules-load.d/.conf, equivalent to the modules variable in the original rc.conf

# Load Virtio-net.ko at boot virtio-net

Virtio-net

The module blacklist is still under/etc/modprobe.d/, such as blacklist.conf:

Blacklist Badmod.ko

Locale

/etc/locale.conf, equivalent to the locale in the original rc.conf

Lang=en_us. UTF-8 Lc_collate=c

Lc_collate=c

Log service

Systemd with Log service, reference systemd Journal

sudo journalctl

You can delete Syslog-ng.

Host Name

/etc/hostname, equivalent to the hostname variable in the original rc.conf

Myhostname

Internet

sudo systemctl enable Networkmanager.service

It's not like rc.conf has a special place to configure a simple network, or a tool like NetworkManager or WICD.

If you insist on using a simple static configuration, you can refer to [SOLVED] static Ethernet setup under Systemd?

Run level

Four systemd with Target replaced the RunLevel concept that provides greater flexibility, such as you can inherit an existing Target , and add other services to create your own Target

sudo systemctl list-units--type=target #查询当前target

sudo systemctl isolate graphical.target #改变当前target, restart invalid

sudo systemctl enable Multi-user.target #改变启动时默认target

sudo systemctl enable Kdm.service #graphical是默认target, specifying the display manager to use

Optimization

Systemd has his own "E4rat".

sudo systemctl enable systemd-readahead-collect.service sudo systemctl enable Systemd-readahead-replay.service

/etc/fstab, modify/home partition options, check/home partition when other services are started in parallel

Defaults,noauto,x-systemd.automount

Other

sudo systemctl reboot #systemctl还有系统关机, restart, hang and other functions sudo systemctl suspend

Five Write Yourself . Service file

The SYSTEMD unit file is inspired by the XDG desktop Entry. Desktop file, and the original origin is the. ini file under Windows.

See example:systemd/services.

Handling dependencies

When using SYSTEMD, you can resolve their dependencies by writing the unit configuration file correctly. Typically, unit a requires unit B to run before a starts. In this case, add requires=b and after=b to the [unit] segment in the cell a configuration file. If this dependency is optional, you can add wants=b and after=b. Note that wants= and requires= do not imply after=, that is, if the after= option is not established, the two units will be started in parallel.

Dependencies are typically used on services (service) rather than targets . For example, Network.target is typically introduced by a service that configures a network interface, so the custom cell is queued after the service because Network.target is already started.

Starting mode

When you write a custom service file, you can choose several different ways to start your services. The startup mode can be set through the type= parameter in the configuration file [Service] segment. Refer to man systemd.service for specific parameter descriptions.

    • Type=simple (default): Systemd thinks the service will start immediately. The service process does not fork. If the service is to start another service, do not use this type to start unless the service is socket-activated.
    • Type=forking:systemd believes that when the service process is fork and the parent process exits, the service starts successfully. For a regular daemon (daemon), use this type to start up unless you are sure that this startup mode does not meet your requirements. Use this startup type to specify pidfile= at the same time so that SYSTEMD can track the main process of tracking.
    • Type=oneshot: This option applies to services that perform only one task and then exit immediately. You may need to set remainafterexit=yes at the same time so that Systemd still thinks the service is active after the service process exits.
    • Type=notify: Same as Type=simple, but the contract service sends a signal to SYSTEMD when it is ready. The implementation of this notification is provided by libsystemd-daemon.so.
    • Type=dbus: If started in this manner, when the specified busname appears on the Dbus system bus, SYSTEMD considers the service ready.

Modify an existing cell file

To change the unit file provided by the package, first create a directory named/etc/systemd/system/< cell name >.d/(such as/etc/systemd/system/httpd.service.d/), and then put the *.conf file, Where you can add or reset parameters. The parameter set here takes precedence over the original unit file. For example, if you want to add an additional dependency, create such a file:

/etc/systemd/system/<unit>.d/customdependency.conf

[Unit]

requires=< New Reliance >

after=< New Reliance >

Then run the following command to make the changes effective:

# Systemctl Daemon-reload

# Systemctl Restart < units >

In addition, the same effect can be achieved by copying the old unit files from/usr/lib/systemd/system/to/etc/systemd/system/and then modifying them. The cell files in the/etc/systemd/system/directory are always prioritized higher than the cell files of the same name in the/usr/lib/systemd/system/directory. Note that when the unit files in/usr/lib/are changed due to package upgrades, the custom cell files in/etc/do not synchronize updates. In addition, you have to perform Systemctl reenable <unit>, and manually re-enable the unit. Therefore, it is recommended to use the previous method of using *.conf.

Tips : You can use the Systemd-delta command to see which cell files are overwritten and which are modified.

Eg:slock

Locks the system with the help of Slock. Very Handy when closing the laptop lid for example.

/etc/systemd/system/screenlock.service

[Unit]

Description=lock X Session using Slock

Before=sleep.target

[Service]

User=<username>

environment=display=:0

Execstart=/usr/bin/slock

[Install]

Wantedby=sleep.target

How do I customize or add a custom unit file?

The unit file has a higher priority under/etc/systemd/system than/lib/systemd/system. Move from the latter to the former according to the individual's needs and make custom modifications.

If a row starts with. Include, followed by a file name, the file is resolved to a special file at this time. Make sure that the included files have the appropriate chapter header information before the instruction.

If possible, you should use the. Include to declare the unit file instead of copying the entire unit file under/lib/systemd/system to the/etc/systemd/system directory. This way you can upgrade the unchanged instructions correctly when you upgrade the package in the future.

Be careful when using. Include and directives, because it can be defined more than once (like environmentfile=). Since we can only add new instructions and not delete the defined instructions, we have to copy the entire file from/lib/systemd/system to/etc/systemd/system.

Assuming we have a lighttpd service, we now want to lower its niceness value. All we need to do is add nice=-5 to the Lighttpd.service file. We can copy the entire file/lib/systemd/system/lighttpd.service to/etc/systemd/system/lighttpd.service or/etc/systemd/system/ Create the following file in Lighttpd.service to do

. include/lib/systemd/system/lighttpd.service

[Service]

Nice=-5

Don't forget to use systemdctl daemon-reload to reload the systemd daemon after editing a unit file.

The type of virtualization platform used by Linux is detected.

Method One: Dmidecode

The first choice for detecting virtualization types at the bottom of Linux is the dmidecode command, which was originally designed to display information about the system BIOS and hardware components. Use the following command to detect the associated virtualization information:

-s System-manufacturer  

The system geek site runs on the Microsoft Azure platform, so it detects Microsoft's Hyper-V. If your system is running on a physical server, the actual name of the hardware manufacturer (such as Dell INC) will be entered. If your Linux is running on a virtualized platform, it will display the associated name of the virtualization technology used, such as "microsoft Corporation""qemu""xen""virtualbox""vmware, inc", and so on.

Note: This method does not apply to container-based virtualization technology.

Method Two: Systemd

For Linux systems using SYSTEMD, the Systemd-detect-virt command can be used for detection, which currently detects hypervisor-based virtualization technologies such as KVM, QEMU, VMware, Xen, Oracle VMs, VirtualBox, UML), and container-based virtualization technologies (such as LXC, Docker, OpenVZ).

Systemd-detect-virt   

Note: Using this command on a physical server will output "none".

Method Three: Virt-what

The last method we introduced to detect the virtualization type used by Linux is the virt-what command, Virt-what is actually a shell script. It identifies virtualized environment types through a variety of heuristics to detect QEMU/KVM, VMware, Hyper-V, VirtualBox, Openvz/virtuozzo, Xen, LXC, IBM PowerVM, and Parallels and other platform types.

Before use, you need to install virt-what through apt-get or yum, and then perform the following command to detect:

sudo virt-  What

The SYSTEMD mechanism of Linux initialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.