github.com/coreos/rocket@v1.30.1-0.20200224141603-171c416fac02/common/cgroup/cgroup.go (about)

     1  // Copyright 2015 The rkt Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  //+build linux
    16  
    17  package cgroup
    18  
    19  import (
    20  	"errors"
    21  	"path/filepath"
    22  	"syscall"
    23  
    24  	"github.com/hashicorp/errwrap"
    25  	"github.com/rkt/rkt/common/cgroup/v1"
    26  	"github.com/rkt/rkt/common/cgroup/v2"
    27  )
    28  
    29  const (
    30  	// The following const comes from
    31  	// #define CGROUP2_SUPER_MAGIC  0x63677270
    32  	// https://github.com/torvalds/linux/blob/v4.6/include/uapi/linux/magic.h#L58
    33  	Cgroup2fsMagicNumber = 0x63677270
    34  )
    35  
    36  // IsIsolatorSupported returns whether an isolator is supported in the kernel
    37  func IsIsolatorSupported(isolator string) (bool, error) {
    38  	isUnified, err := IsCgroupUnified("/")
    39  	if err != nil {
    40  		return false, errwrap.Wrap(errors.New("error determining cgroup version"), err)
    41  	}
    42  
    43  	if isUnified {
    44  		controllers, err := v2.GetEnabledControllers()
    45  		if err != nil {
    46  			return false, errwrap.Wrap(errors.New("error determining enabled controllers"), err)
    47  		}
    48  		for _, c := range controllers {
    49  			if c == isolator {
    50  				return true, nil
    51  			}
    52  		}
    53  		return false, nil
    54  	}
    55  	return v1.IsControllerMounted(isolator)
    56  }
    57  
    58  // IsCgroupUnified checks if cgroup mounted at /sys/fs/cgroup is
    59  // the new unified version (cgroup v2)
    60  func IsCgroupUnified(root string) (bool, error) {
    61  	cgroupFsPath := filepath.Join(root, "/sys/fs/cgroup")
    62  	var statfs syscall.Statfs_t
    63  	if err := syscall.Statfs(cgroupFsPath, &statfs); err != nil {
    64  		return false, err
    65  	}
    66  
    67  	return statfs.Type == Cgroup2fsMagicNumber, nil
    68  }