Some notes on the control group CGroup (Resource Management Guide) in Linux

Write in front

If you read indiscriminately or endlessly without thinking, you will never remember what you have read, and most of it will eventually disappear—— schopenhauer

Chapter 1 Introduction to control group

1.1. What is a control group

Control group is a function of the Linux kernel:

A hierarchical group of processes running in a system that you can allocate resources (such as CPU time, system memory, network bandwidth, or a combination of these resources).

By using cgroup, system administrators can carry out fine control in allocating, sorting, rejecting, managing and monitoring system resources. Hardware resources can be intelligently allocated between applications and users, thereby increasing overall efficiency.

The control group can group and mark processes hierarchically, and limit their available resources.

Traditionally, all processes share the same amount of system resources, and the administrator adjusts it with the process niceness value.

Adjusted with the niceness value, an application with a large number of processes can obtain more resources than an application with a small number of processes, which has nothing to do with the importance of the application.

By bundling the cgroup hierarchy with the systemd unit tree, Linux can move resource management settings from the process level to the application level.

You can use the systemctl directive or modify the systemd unit file to manage system resources.

In versions prior to Linux 7, system administrators used the cgconfig command in the libcgroup package to establish a custom cgroup level. But now, this package is outdated and not recommended because it is easy to conflict with the default cgroup level. However, in some specific cases, libcgroup is still available, such as when systemd is not available, or when using the net prio subsystem.

The above tools provide a high-level interface to interact with the cgroup Manager (also known as subsystem) in the Linux kernel. The main cggroup controllers used for resource management are cpu, memory and blkio. Please refer to the list of controllers activated by default

1.2. Default level of CGroup

By default, systemd will automatically create slice, scope and service levels to provide a unified structure for the cgroup tree. Using the systemctl command, you can further modify this structure by creating a custom slice. systemd also automatically mounts the level of the important kernel resource manager in the / system / FS / cgroup / directory.

Unit type of systemd

All processes running in the system are sub processes of systemd init process. In terms of resource control, systemd provides three types of units:

service

Service: a process or group of processes started by systemd according to the company configuration file. Service encapsulates the specified process so that the process can be started or terminated as a whole. The service is named by reference to the following methods:

name.service # Where name represents the service name.
Undefined

scope

Scope: a set of externally created processes. Scope encapsulates the process that is started and terminated by the forced process through the fork() function and then registered by systemd at run time. For example, user sessions, containers, and virtual machines are considered scopes. The scope is named as follows:

name.scope #Where name represents the scope name.
Undefined

slice

Slice: a group of units arranged hierarchically. Slice does not contain processes, but it will form a hierarchy and place both scope and service in it. The real process is contained in a scope or service. In this hierarchical tree, the name of each slice unit corresponds to the path to a location in the hierarchy. The small horizontal line ("-") serves to separate the path components. For example, if the name of a slice is:

parent-name.slice
Undefined

This indicates that parent-name.slice is a child slice of parent.slice. This child slice can have its own child slice, which is named parent-name-name2.slice, and so on.

-.slice
Undefined

Service, scope, and slice units are mapped directly to objects in the cgroup tree. When these units are activated, they are directly mapped one by one to the cgroup path established by the unit name. For example, ex.service belongs to test-waldo.slice and will be directly mapped to cgroup test.slice/test-waldo.slice/ex.service /.

service, scope and slice are created manually by the system administrator or dynamically by the program. By default, the operating system will define some built-in services necessary to run the system. In addition, by default, the system creates four slices:

slice: describe
-.sliceRoot slice;
system.sliceDefault location of all system service s;
user.sliceDefault location of all user sessions;
machine.sliceDefault location for all virtual machines and Linux containers.

Note that all user sessions, virtual machines, and container processes are automatically placed in a separate scope unit. Moreover, all users will get an implicit sub slice. In addition to the above default configuration, the system administrator may define a new slice and put the service and scope in it.

├─1 /usr/lib/systemd/systemd --switched-root --system --deserialize 21
├─docker
│ ├─3254bcd54a7b2b1a5ece2ca873ab18c3215484e6b4f83617a522afe4e853c378
│ │ ├─11885 /home/weave/runsvinit
│ │ ├─11902 /sbin/runsvdir /etc/service
│ │ ├─11903 runsv probe
│ │ ├─11904 runsv app
│ │ ├─11907 scope-probe --mode probe --probe.docker=true
│ │ └─11908 scope-app --mode app --probe.docker=true
│ ├─b867272463dffc7a2f698848a622e33ed59a2176da89b99038e451eaf181bc57
│ │ └─11484 /usr/bin/cadvisor -logtostderr
│ ├─a771eed8c7c39cd410bd6f43909a67bfcf181d87fcafffe57001f17f3fdff408
│ │ ├─11310 /bin/bash
│ │ └─11361 bash
│ ├─3b2df1738e84159f4fa02dadbfc285f6da8ddde4d94cb449bc775c9a70eaa4ea
│ │ └─11086 /bin/bash
│ └─55e45b34d93d0a36a06283c90e7da9097ad3d85d26dfbdc9d07d2e45aeced8f1
│   └─10677 /bin/bash
├─user.slice
│ └─user-0.slice
│   ├─session-169.scope
│   │ ├─26654 sshd: root@pts/2
│   │ ├─26656 -bash
│   │ └─26925 systemd-cgls
│   ├─session-166.scope
│   │ ├─25790 sshd: root@pts/1
│   │ └─25792 -bash
│   └─session-158.scope
│     ├─24025 sshd: root@pts/0
│     └─24027 -bash
└─system.slice
  ├─docker.service
  │ ├─10151 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd...
  │ ├─11445 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 8080...
  │ └─11452 /usr/bin/docker-proxy -proto tcp -host-ip :: -host-port 8080 -con...
  ├─postfix.service
  │ ├─ 1027 /usr/libexec/postfix/master -w
  │ ├─ 1043 qmgr -l -t unix -u
  │ └─26337 pickup -l -t unix -u
  ├─tuned.service
  │ └─943 /usr/bin/python -Es /usr/sbin/tuned -l -P
  ├─sshd.service
  │ └─942 /usr/sbin/sshd -D
  ├─containerd.service
  │ ├─  946 /usr/bin/containerd
  │ ├─10656 /usr/bin/containerd-shim-runc-v2 -namespace moby -id 55e45b34d93d...
  │ ├─11066 /usr/bin/containerd-shim-runc-v2 -namespace moby -id 3b2df1738e84...
  │ ├─11288 /usr/bin/containerd-shim-runc-v2 -namespace moby -id a771eed8c7c3...
  │ ├─11465 /usr/bin/containerd-shim-runc-v2 -namespace moby -id b867272463df...
  │ └─11865 /usr/bin/containerd-shim-runc-v2 -namespace moby -id 3254bcd54a7b...
  ├─crond.service
  │ └─605 /usr/sbin/crond -n
  ├─rsyslog.service
  │ └─600 /usr/sbin/rsyslogd -n
  ├─dbus.service
  │ └─590 /bin/dbus-daemon --system --address=systemd: --nofork --nopidfile -...
  ├─irqbalance.service
  │ └─589 /usr/sbin/irqbalance --foreground
  ├─polkit.service
  │ └─586 /usr/lib/polkit-1/polkitd --no-debug
  ├─vmtoolsd.service
  │ └─583 /usr/bin/vmtoolsd
  ├─vgauthd.service
  │ └─582 /usr/bin/VGAuthService -s
  ├─chronyd.service
  │ └─594 /usr/sbin/chronyd
  ├─systemd-logind.service
  │ └─542 /usr/lib/systemd/systemd-logind
  ├─auditd.service
  │ └─495 /sbin/auditd
  ├─systemd-udevd.service
  │ └─463 /usr/lib/systemd/systemd-udevd
  ├─system-getty.slice
  │ └─getty@tty1.service
  │   └─612 /sbin/agetty --noclear tty1 linux
  └─systemd-journald.service
    └─438 /usr/lib/systemd/systemd-journald

service and scope contain processes, but are placed in slices that do not contain their own processes. The only exception is PID 1 in the special systemd.slice. Note that the. Slice is not shown because it is implicitly recognized by the root of the overall tree.

service and slice units can be configured through permanent unit files; Or make API call to PID 1 and create it dynamically at run time. scope units can only be created in the first way. Units created dynamically by API calls are temporary and exist only at run time. Temporary units will be automatically released once they are finished, shut down or the system is restarted.

1.3. Resource manager of Linux kernel

The resource manager (also known as the cgroup subsystem) represents a single resource, such as CPU time or memory. The Linux kernel provides a series of resource managers that are automatically mounted by systemd. To refer to the list of currently mounted resource managers, see / proc/cgroups or use the lssubsys monitoring tool. In Linux 7, systemd mounts the following controllers by default:

Controllers available in Linux 7

Controllerdest
blkioSet permissions for input / output access block devices;
cpuUse the CPU scheduler to allow cgroup tasks to access the CPU. It is mounted on the same mount together with cpuacct controller;
cpuacctAutomatically generate a report on CPU resources occupied by tasks in cgroup. It is mounted on the same mount together with the CPU controller;
cpusetAllocate independent CPU (in multi-core system) and memory nodes to tasks in cgroup;
devicesAllow or prohibit tasks in cgroup from accessing devices;
freezerSuspend or resume tasks in cgroup;
memoryLimit the available memory of tasks in cgroup, and automatically generate the report of memory resources occupied by tasks;
net_clsNetwork packets are marked with a class ID, which allows the Linux traffic controller (tc instruction) to identify packets from specific cgroup tasks;
perf_eventAllow the use of perf tools to monitor cgroup s;
hugetlbAllow the use of large virtual memory pages and force the amount of available resources for these memory pages.

Linux Kernel shows a series of resource manager tunable parameters that can be configured by systemd. For detailed description of parameters, please refer to the kernel documentation (reference list of special introduction to kernel controller).

Chapter 2 using control groups

Overview of tasks related to creating, managing, and controlling groups. systemd is the recommended way to manage cgroup s and will be supported in future versions,

2.1. Create control group

From the perspective of systemd, cgroup will connect to a system unit, which can be configured with the unit file and managed with the systemd command-line utility. Depending on the type of application, your resource management settings can be transient or persistent.

To create a transient cgroup (temporary cgroup) for a service, start the service using the systemd run command. In this way, you can limit the resources used by this service at run time. By making API calls to systemd, applications can dynamically create temporary cgroups. Once the service is stopped, the temporary units are automatically removed.

To assign a persistent cgroup to a service, write its organization profile. After the system is restarted, this configuration will be retained, so it can be used to manage automatically started services. Note that scope units cannot be created this way.

2.1.1. Create a temporary cgroup with SYSTEMd run

The systemd run instruction is used to create and start a temporary service or scope unit, and run custom instructions in this unit. The instructions executed in the service unit are started asynchronously in the background, and they are called from the systemd process. The instructions running in the scope unit are started directly from the system d-run process, so the execution state is inherited from the caller. The execution in this case is synchronous.

To run the command in a specified cgroup, enter it as root

systemd-run --unit=name --scope --slice=slice_name command
Undefined
Name represents the name you want this organization to be recognized. If -- unit is not specified, the company name will be generated automatically. It is recommended to choose a descriptive name because it will represent the units in the systemctl output. This name must be unique during unit runtime.
Use the optional -- scope parameter to create a temporary scope unit to replace the default service unit.
--Slice option, so that the newly created service or scope unit can become part of the specified slice. Replace slice with the name of an existing slice (as shown in the systemctl -t slice output)_ Name, or create a new slice by passing a unique name. By default, service and scope are created as part of system.slice.
Replace the command with the command you want to run in the service unit. Place this instruction at the end of the system d-run syntax. In this way, the parameters of this instruction are not confused with the SYSTEMd run parameter.

In addition to the above options, SYSTEMd run also has some other parameters available. For example, – description can create a description of the unit; After the service process ends, – remain after exit can collect runtime information The machine option can execute instructions in a closed container

Start a new service with SYSTEMd run

┌──[root@liruilongs.github.io]-[~]
└─$ systemd-run --unit=toptest --slice=test top -b
Running as unit toptest.service. #Now, the name toptest.service can be combined with the systemctl instruction to monitor or modify cgroup.
┌──[root@liruilongs.github.io]-[~]
└─$ systemctl status toptest.service
● toptest.service - /usr/bin/top -b
   Loaded: loaded (/run/systemd/system/toptest.service; static; vendor preset: disabled)
  Drop-In: /run/systemd/system/toptest.service.d
           └─50-Description.conf, 50-ExecStart.conf, 50-Slice.conf
   Active: active (running) since Wed 2021-10-13 01:12:43 CST; 50s ago
 Main PID: 27671 (top)
   CGroup: /test.slice/toptest.service
           └─27671 /usr/bin/top -b

Oct 13 01:13:31 liruilongs.github.io top[27671]: 24025 root      20   0  145704   5332   4072 S   0.0  0.1   0:0... sshd
Oct 13 01:13:31 liruilongs.github.io top[27671]: 24027 root      20   0  116024   2812   1784 S   0.0  0.1   0:0... bash
Oct 13 01:13:31 liruilongs.github.io top[27671]: 24926 root      20   0       0      0      0 S   0.0  0.0   0:0...er/u+
Oct 13 01:13:31 liruilongs.github.io top[27671]: 25314 root      20   0       0      0      0 S   0.0  0.0   0:0...er/0+
Oct 13 01:13:31 liruilongs.github.io top[27671]: 25790 root      20   0  145704   5328   4072 S   0.0  0.1   0:0... sshd
Oct 13 01:13:31 liruilongs.github.io top[27671]: 25792 root      20   0  115784   2440   1636 S   0.0  0.1   0:0... bash
Oct 13 01:13:31 liruilongs.github.io top[27671]: 26067 root      20   0       0      0      0 S   0.0  0.0   0:0...er/0+
Oct 13 01:13:31 liruilongs.github.io top[27671]: 26337 postfix   20   0   89648   4028   3016 S   0.0  0.1   0:0...ickup
Oct 13 01:13:31 liruilongs.github.io top[27671]: 27425 root      20   0       0      0      0 S   0.0  0.0   0:0...er/1+
Oct 13 01:13:31 liruilongs.github.io top[27671]: 27530 root      20   0       0      0      0 S   0.0  0.0   0:0...er/1+
Hint: Some lines were ellipsized, use -l to show in full.
┌──[root@liruilongs.github.io]-[~]
└─$
┌──[root@liruilongs.github.io]-[~]
└─$ systemd-cgls
├─1 /usr/lib/systemd/systemd --switched-root --system --deserialize 21
├─test.slice
│ └─toptest.service
│   └─27671 /usr/bin/top -b
├─docker
│ ├─3254bcd54a7b2b1a5ece2ca873ab18c3215484e6b4f83617a522afe4e853c378
│ │ ├─11885 /home/weave/runsvinit
│ │ ├─11902 /sbin/runsvdir /etc/service
│ │ ├─11903 runsv probe
........

2.1.2. Create permanent cgroup

To configure an auto start unit when the system starts, execute the systemctl enable command. Running this command automatically creates a unit file in the / usr/lib/systemd/system / directory. To make permanent changes to cgroup, add or modify the configuration parameters in its unit file. For more information, see section 2.3.2 "modifying unit files".

2.2. Delete control group

Once the process contained in the temporary cgroup ends, the temporary cgroup will be automatically released. By passing the -- remain after exit option to system d-run, you can let the unit continue to run after its process ends to collect runtime information. To stop the unit, enter:

systemctl stop name.service
Undefined

If you want a service to stop running, replace the name with the name of the service. To terminate processes in one or more organizations, enter as root:

systemctl kill name.service --kill-who=PID,... --signal=signal 
Undefined

Replace name with company name (such as httpd.service). Use -- kill who to select the process you want to end from the cgroup. To terminate multiple processes at the same time, send a comma separated list of PID s. Replace signal with the POSIX signal type you want to send to the specified process. SIGTERM by default.

When a unit is disabled and its configuration file is deleted by running (the following line), the permanent cgroup is released:

systemctl disable name.service  #Name represents the name of the service you want to disable.
Undefined

2.3. Modify cgroup

All permanent units regulated by systemd have a unit configuration file in the / usr/lib/systemd/system / directory. To modify the parameters of the service unit, modify this configuration file. You can do this manually or use the systemctl set property instruction from the command line interface.

# Replace name with the systemd name you want to modify, parameter with the parameter name you want to modify, and value with the new value assigned to this parameter.
systemctl set-property name parameter=value
Undefined

Not all company parameters can be modified at runtime, but most parameters related to resource control can be modified. The systemctl set property instruction allows you to modify multiple attributes at the same time. Therefore, compared with setting each attribute separately, this instruction is recommended.

The changes take effect immediately and are written to the company file and retained after restart. You can pass the -- runtime option to make the setting temporary.

systemctl set-property --runtime name property=value
Undefined

2.3.1. Set parameters in the command line interface

The systemctl set property instruction allows you to continuously modify resource control settings while the application is running. Use the following syntax as root to do this:

Using systemctl set property

# To use the command line to limit the CPU and memory usage of httpd.service, enter:
systemctl set-property httpd.service CPUShares=600 MemoryLimit=500M
# If you want this change to be temporary, add the -- runtime option:
systemctl set-property --runtime httpd.service CPUShares=600 MemoryLimit=500M
######################
┌──[root@liruilongs.github.io]-[~]
└─$ cat /usr/lib/systemd/system/httpd.service
[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target
Documentation=man:httpd(8)
Documentation=man:apachectl(8)

[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/httpd
ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND
ExecReload=/usr/sbin/httpd $OPTIONS -k graceful
ExecStop=/bin/kill -WINCH ${MAINPID}
# We want systemd to give httpd some time to finish gracefully, but still want
# it to kill httpd after TimeoutStopSec if something went wrong during the
# graceful stop. Normally, Systemd sends SIGTERM signal right after the
# ExecStop, which would kill httpd. We are sending useless SIGCONT here to give
# httpd time to finish.
KillSignal=SIGCONT
PrivateTmp=true

[Install]
WantedBy=multi-user.target
┌──[root@liruilongs.github.io]-[~]
└─$ systemctl set-property httpd.service CPUShares=600 MemoryLimit=500M
┌──[root@liruilongs.github.io]-[~]
└─$ systemctl restart httpd
┌──[root@liruilongs.github.io]-[~]
└─$ cat /usr/lib/systemd/system/httpd.service
[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target
Documentation=man:httpd(8)
Documentation=man:apachectl(8)

[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/httpd
ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND
ExecReload=/usr/sbin/httpd $OPTIONS -k graceful
ExecStop=/bin/kill -WINCH ${MAINPID}
# We want systemd to give httpd some time to finish gracefully, but still want
# it to kill httpd after TimeoutStopSec if something went wrong during the
# graceful stop. Normally, Systemd sends SIGTERM signal right after the
# ExecStop, which would kill httpd. We are sending useless SIGCONT here to give
# httpd time to finish.
KillSignal=SIGCONT
PrivateTmp=true

[Install]
WantedBy=multi-user.target
┌──[root@liruilongs.github.io]-[~]
└─$

2.3.2. Modify company documents

The systemd service unit file provides a series of advanced configuration parameters that are helpful for resource management. These parameters communicate with the Linux cgroup manager that must be enabled in the kernel. You can use these parameters to manage the properties of CPU, memory usage, block IO, and more fine units.

Manage CPU

The CPU controller is started by default in the kernel, which makes the available CPU of all system services the same, regardless of the number of processes it contains. This default setting can be modified by using the DefaultControllers parameter in the / etc/systemd/system.conf configuration file. To manage CPU allocation, use the following instructions in the [Service] section of the unit configuration file:

`CPUShares=value`

Please replace value with the number of CPU share s. The default value is 1024, which you can increase to allocate more CPU to the unit. This parameter defaults to cpuaaccounting enabled in the company file.
The CPUShares parameter controls the cpu.shares group parameter.

┌──[root@liruilongs.github.io]-[~]
└─$ cat /etc/systemd/system.conf | grep -i BlockIOAccounting
#DefaultBlockIOAccounting=no
┌──[root@liruilongs.github.io]-[~]
└─$ cat /etc/systemd/system.conf | grep -i CPUAccounting
#DefaultCPUAccounting=no
Limit the CPU availability of one unit
#To allocate 1500 CPU share s instead of 1024 for Apache service, modify the CPUShares setting in the / usr/lib/systemd/system/httpd.service unit file:
[Service]
CPUShares=1500
# To apply this modification, reload the configuration of systemd and restart Apache to make the modified service file take effect:
 systemctl daemon-reload
 systemctl restart httpd.service

memory management

To limit the size of available memory per unit, use the following instructions in the [Service] section of the unit configuration file:

MemoryLimit=value

Set the maximum available memory for the process executing in cgroup and replace value with this value. Please take Kilobyte, Megabyte, Gigabyte and Terabyte as the unit of measurement and use K, M, G and T suffixes. Similarly, the MemoryAccounting parameter must be enabled in the same cell.
The MemoryLimit parameter controls memory.limit_in_bytes controls the group parameter.

Limit the amount of memory available per unit
#To limit the maximum available memory of Apache service to 1GB, modify the MemoryLimit setting in the / usr/lib/systemd/system/httpd.service unit file:
[Service]
MemoryLimit=1G
#To apply this modification, reload the configuration of systemd and restart Apache to make the modified service file take effect:
systemctl daemon-reload
systemctl restart httpd.service

Manage Block IO

To manage Block IO, use the following instructions in the [Service] section of the unit configuration file. The following command assumes that the BlockIOAccounting parameter is enabled:

BlockIOWeight=value

Select a new overall block IO weight for the executed process and replace it with value. The weight should be selected between 10 and 1000. The default value is 1000.

BlockIODeviceWeight=device_name value

Please enter device_ Select the block IO weight for the device indicated by name and replace it with value. Replace device with a name or a path to the device_name. Because of BlockIOWeight, you can select a weight value between 10 and 1000.

BlockIOReadBandwidth=device_name value

This instruction can limit specific bandwidth for a unit. Replace device with the device name or path to the block device node_ Name and value represent bandwidth rate. Use K, M, G, T suffixes as units of measure. The default unit for values without suffix is "bytes / second".

BlockIOWriteBandwidth=device_name value

This instruction can limit the writable bandwidth to the specified device. The parameter can be consistent with BlockIOReadBandwidth.

Limit the available quantity of a unit Block IO
# To reduce the weight of Apache service accessing / home/jdoe / directory block IO, add the following characters to the / usr/lib/systemd/system/httpd.service unit file:
[Service]
BlockIODeviceWeight=/home/jdoe 750
#To set the maximum bandwidth Apache reads from the / var/log / directory to 5MB / s, use the following syntax:
[Service]
BlockIOReadBandwith=/var/log 5M
#To apply this modification, reload the configuration of systemd and restart Apache, so that the modified service file will take effect:
systemctl daemon-reload
systemctl restart httpd.service
Undefined

Manage other system resources

There are several other instructions that can be used in the unit file to assist in managing resources.

DeviceAllow=device_name options
#This option controls the number of times a specified device node is accessed. Here, device_name represents the path to the device node,
# Or a specific device group name in / proc/devices. Replace options with a combination of r, w and m,
# So that units can read, write, or create device nodes.
DevicePolicy=value
#Here, value is one of the following three.
# -strict: only the access type specified by DeviceAllow is allowed;
# -closed: allow access to standard pseudo devices, such as: / dev/null, / dev/zero, / dev/full, / dev/random and / dev/urandom; 
# -auto: if DeviceAllow is not displayed, access to all devices is allowed. This setting is the default setting.
Slice=slice_name
# Please replace slice with the slice name of the storage unit_ name.  The default name is system.slice. scope units cannot be arranged in this way because they are bound to their parent slice.
ControlGroupAttribute=attribute value
# This option can set multiple control group parameters exposed by the Linux cgroup manager. Replace attribute with the low-level cgroup parameter you want to modify, and replace value with the new value of this parameter.
Change the properties of low-level cgroup
#If you want to change the memory.flexibility setting to reset the trend of the process memory used by the Kernel to replace the cgroup task, please refer to the introduction to the memory controller in the special introduction to the Kernel controller. To set the Apache service's memory.swappiness to 70, add the following information to / usr/lib/systemd/system/httpd.service:
[Service]
ControlGroupAttribute=memory.swappiness 70
#To apply this modification, reload the configuration of systemd and restart Apache to make the modified service file take effect:
systemctl daemon-reload
systemctl restart httpd.service
Undefined

2.4. Obtain information about the control group

Use the systemctl command to list the system units and check their status. The SYSTEMd CGLS instruction can check the hierarchy of the control group, and SYSTEMd cgtop can monitor the real-time resource consumption of the control group.

2.4.1. List companies

Use the following command to list all activated units in the system:

┌──[root@liruilongs.github.io]-[~]
└─$ systemctl list-units
UNIT                                            LOAD   ACTIVE SUB       DESCRIPTION
proc-sys-fs-binfmt_misc.automount               loaded active waiting   Arbitrary Executable File Formats File System Au
sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:0-2:0:0:0-block-sda-sda1.device loaded active 
................

The results listed above include four items:

UNITThe company name also reflects the position of the company in the cgroup tree. As described in the section "company types of systemd", there are three company types related to resource control: slice, scope and service. For an introduction to the unit types of systemd, please refer to the Red Hat Enterprise Linux 7 system administrator's Guide · using systemd to manage services.
LOADDisplays whether the unit profile is loaded correctly. If the load fails, the file will contain error instead of loaded. The loading status of other units are stub, merged and masked.
ACTIVEThe activation status of advanced units is the generalization of SUB.
SUBActivation status of lower level units. The range of possible values depends on the unit type.
DESCRIPTIONDescribe unit content and performance.

By default, systemctl will only list the activated units (according to the advanced activation status in the ACTIVE domain). Use the -- all option to view inactive units. To limit the amount of information in the result list, use the -- type (-t) parameter. This parameter requires a comma separated list of company types, such as service and slice, or company loading status, such as loaded and masked.

Using systemctl list units

┌──[root@liruilongs.github.io]-[~]
└─$ systemctl -t slice
UNIT                                              LOAD   ACTIVE SUB    DESCRIPTION
-.slice                                           loaded active active Root Slice
system-getty.slice                                loaded active active system-getty.slice
system-selinux\x2dpolicy\x2dmigrate\x2dlocal\x2dchanges.slice loaded active active system-selinux\x2dpolicy\x2dmigrate\x
system.slice                                      loaded active active System Slice
user-0.slice                                      loaded active active User Slice of root
user.slice                                        loaded active active User and Session Slice

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.

6 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.
┌──[root@liruilongs.github.io]-[~]
└─$  systemctl -t service,masked
Unknown unit type or load state 'masked'.
Use -t help to see a list of allowed values.
┌──[root@liruilongs.github.io]-[~]
└─$  systemctl -t masked
0 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.
┌──[root@liruilongs.github.io]-[~]
└─$ systemctl list-unit-files
UNIT FILE                                     STATE
proc-sys-fs-binfmt_misc.automount             static
dev-hugepages.mount                           static
dev-mqueue.mount                              static
proc-sys-fs-binfmt_misc.mount                 static
sys-fs-fuse-connections.mount                 static
sys-kernel-config.mount                       static
sys-kernel-debug.mount                        static
tmp.mount
.......

2.4.2. View hierarchy of control group

The above instructions do not go beyond the unit level to show the real process running in cgroup. systemctl results also do not display the hierarchy of units. You can use the SYSTEMd CGLS instruction to group running processes according to cgroup to implement both. To display all cgroup levels in your system, enter:

systemd-cgls
#To reduce the output of SYSTEMd CGLS and view a specific part of the hierarchy:
systemd-cgls name
systemctl status httpd.service

In addition to the above tools, systemd also provides machinectl instructions for monitoring Linux.

2.4.3. View resource manager

The above systemctl instruction can monitor the high-level unit level, but it cannot display which process uses the resource manager of the Linux kernel. This information is stored in special process files. To view these files, enter as root:

# The PID represents the process ID you want to view.
cat proc/PID/cgroup
┌──[root@liruilongs.github.io]-[~]
└─$ ps -ef | grep httpd | grep -v grep
root       1231      1  0 02:00 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache     1232   1231  0 02:00 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache     1233   1231  0 02:00 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache     1234   1231  0 02:00 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache     1235   1231  0 02:00 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache     1236   1231  0 02:00 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
┌──[root@liruilongs.github.io]-[~]
└─$ cat /proc/1231/cgroup
# By default, this list is the same for all systemd enabled companies, because it automatically mounts all default controllers
11:blkio:/system.slice/httpd.service
10:memory:/system.slice/httpd.service
9:freezer:/
8:perf_event:/
7:cpuacct,cpu:/system.slice/httpd.service
6:devices:/system.slice/httpd.service
5:pids:/
4:hugetlb:/
3:net_prio,net_cls:/
2:cpuset:/
1:name=systemd:/system.slice/httpd.service
┌──[root@liruilongs.github.io]-[~]
└─$

2.4.4. Monitoring resource consumption

The SYSTEMd CGLS instruction provides a snapshot of static data at the cgroup level. To view a running cgroup dynamic description sorted by resource usage (CPU, memory, and IO), use:

systemd-cgtop
# The statistics and control options provided by SYSTEMd cgtop are similar to those provided by the top utility
┌──[root@liruilongs.github.io]-[~]
└─$ systemd-cgtop
Path                                                                             Tasks   %CPU   Memory  Input/s Output/s

/                                                                                  121      -   376.3M        -        -
/system.slice                                                                        -      -   347.7M        -        -
/system.slice/auditd.service                                                         1      -     2.7M        -        -
/system.slice/chronyd.service                                                        1      -     1.1M        -        -
/system.slice/containerd.service                                                     1      -    71.3M        -        -
/system.slice/crond.service                                                          1      -   740.0K        -        -
/system.slice/dbus.service                                                           1      -     1.1M        -        -
/system.slice/dev-disk-by...b815a\x2d8221\x2d4e2e\x2d8bed\x2dc2e74bd2368e.swap       -      -    56.0K        -        -
/system.slice/dev-hugepages.mount                                                    -      -   256.0K        -        -
/system.slice/dev-mqueue.mount                                                       -      -   292.0K        -        -
/system.slice/docker.service                                                         1      -   142.1M        -        -
/system.slice/etcd.service                                                           1      -    34.2M        -        -
/system.slice/httpd.service                                                          6      -     2.8M        -        -
/system.slice/irqbalance.service                                                     1      -   416.0K        -        -
/system.slice/polkit.service                                                         1      -    13.7M        -        -
/system.slice/postfix.service                                                        3      -     6.0M        -        -
/system.slice/rsyslog.service                                                        1      -     3.2M        -        -
/system.slice/sshd.service                                                           1      -     4.2M        -        -
/system.slice/sys-kernel-debug.mount                                                 -      -     8.0K        -        -
/system.slice/system-getty.slice                                                     1      -   164.0K        -        -
/system.slice/system-getty.slice/getty@tty1.service                                  1      -        -        -        -
/system.slice/systemd-journald.service                                               1      -     9.0M        -        -
/system.slice/systemd-logind.service                                                 1      -   872.0K        -        -
/system.slice/systemd-machined.service                                               1      -   624.0K        -        -
/system.slice/systemd-udevd.service                                                  1      -     9.1M        -        -
/system.slice/tuned.service                                                          1      -    12.4M        -        -
/system.slice/vgauthd.service                                                        1      -     7.2M        -        -
/system.slice/vmtoolsd.service                                                       1      -     4.0M        -        -
/user.slice                                                                          3      -    10.7M        -        -
/user.slice/user-0.slice/session-1.scope                                             3      -        -        -        -
^C
┌──[root@liruilongs.github.io]-[~]
└─$

Keywords: Linux

Added by DrTrans on Tue, 12 Oct 2021 21:46:55 +0300