[Build] mount cgroup2 in chroot to fix build on ubuntu 22.04 (#13030)

Why I did it
Ubuntu 22.04 uses cgroup2 by default, but docker.sh doesn't mount it.
As a result we get an error when trying to run docker info in chroot env:

ERROR: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

How I did it
mount cgroup2 in chroot if all enabled kernel cgroup controllers are currently not in use by cgroup1

So we need to mount cgroup in chroot environment on /sys/fs/cgroup.
Because inside chroot we don't know which cgroup version is used by the host we have two possible solutions:

cgroup tree for chroot is mounted by the host (it was my 1st version of this fix)
cgroup tree is mounted inside chroot based on info from /proc/cgroups (it's current version of this fix)
My 2nd version based on this code from systemd: 5c6c587ce2/src/shared/cgroup-setup.c (L35-L74)

We parse info from /proc/cgroups
Skip header line started from #
Skip controller if it's disabled (4th column = 0)
Count number of controllers with non-zero of hierarchy_id (2nd column)
If this number is not zero then we assume some of controllers are used by host system and the host system uses hybrid or legacy cgroup tree. In this case we can't use unified cgroup tree inside chroot and mount old cgroup tree (v1).
If this number is zero then we assume host system uses unified cgroup tree and we need to mount cgroup2 inside chroot.

Signed-off-by: Konstantin Vasin <k.vasin@yadro.com>
This commit is contained in:
Konstantin Vasin 2022-12-17 23:16:45 +03:00 committed by GitHub
parent 947561c225
commit 8a3fad2891
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -63,10 +63,18 @@ cgroupfs_mount() {
# see also https://github.com/tianon/cgroupfs-mount/blob/master/cgroupfs-mount
if grep -v '^#' /etc/fstab | grep -q cgroup \
|| [ ! -e /proc/cgroups ] \
|| [ ! -d /sys/fs/cgroup ]; then
|| [ ! -d /sys/fs/cgroup ] \
|| [ "$(stat -fc '%T' /sys/fs/cgroup)" = "cgroup2fs" ]; then
return
fi
if ! mountpoint -q /sys/fs/cgroup; then
# cgroup2
# https://github.com/systemd/systemd/blob/5c6c587ce24096d36826418b5390599d1e5ad55c/src/shared/cgroup-setup.c#L35-L74
if awk '!/^#/ && $4 == 1 && $2 != 0 { count++ } END { exit count != 0 }' /proc/cgroups; then
mount -t cgroup2 cgroup2 /sys/fs/cgroup
return
fi
# cgroup1
mount -t tmpfs -o uid=0,gid=0,mode=0755 cgroup /sys/fs/cgroup
fi
(