github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/engine/rootless/specconv/specconv_linux.go (about)

     1  package specconv // import "github.com/docker/docker/rootless/specconv"
     2  
     3  import (
     4  	"os"
     5  	"strconv"
     6  	"strings"
     7  
     8  	specs "github.com/opencontainers/runtime-spec/specs-go"
     9  	"github.com/sirupsen/logrus"
    10  )
    11  
    12  // ToRootless converts spec to be compatible with "rootless" runc.
    13  // * Remove non-supported cgroups
    14  // * Fix up OOMScoreAdj
    15  //
    16  // v2Controllers should be non-nil only if running with v2 and systemd.
    17  func ToRootless(spec *specs.Spec, v2Controllers []string) error {
    18  	return toRootless(spec, v2Controllers, getCurrentOOMScoreAdj())
    19  }
    20  
    21  func getCurrentOOMScoreAdj() int {
    22  	b, err := os.ReadFile("/proc/self/oom_score_adj")
    23  	if err != nil {
    24  		logrus.WithError(err).Warn("failed to read /proc/self/oom_score_adj")
    25  		return 0
    26  	}
    27  	s := string(b)
    28  	i, err := strconv.Atoi(strings.TrimSpace(s))
    29  	if err != nil {
    30  		logrus.WithError(err).Warnf("failed to parse /proc/self/oom_score_adj (%q)", s)
    31  		return 0
    32  	}
    33  	return i
    34  }
    35  
    36  func toRootless(spec *specs.Spec, v2Controllers []string, currentOOMScoreAdj int) error {
    37  	if len(v2Controllers) == 0 {
    38  		// Remove cgroup settings.
    39  		spec.Linux.Resources = nil
    40  		spec.Linux.CgroupsPath = ""
    41  	} else {
    42  		if spec.Linux.Resources != nil {
    43  			m := make(map[string]struct{})
    44  			for _, s := range v2Controllers {
    45  				m[s] = struct{}{}
    46  			}
    47  			// Remove devices: https://github.com/containers/crun/issues/255
    48  			spec.Linux.Resources.Devices = nil
    49  			if _, ok := m["memory"]; !ok {
    50  				spec.Linux.Resources.Memory = nil
    51  			}
    52  			if _, ok := m["cpu"]; !ok {
    53  				spec.Linux.Resources.CPU = nil
    54  			}
    55  			if _, ok := m["cpuset"]; !ok {
    56  				if spec.Linux.Resources.CPU != nil {
    57  					spec.Linux.Resources.CPU.Cpus = ""
    58  					spec.Linux.Resources.CPU.Mems = ""
    59  				}
    60  			}
    61  			if _, ok := m["pids"]; !ok {
    62  				spec.Linux.Resources.Pids = nil
    63  			}
    64  			if _, ok := m["io"]; !ok {
    65  				spec.Linux.Resources.BlockIO = nil
    66  			}
    67  			if _, ok := m["rdma"]; !ok {
    68  				spec.Linux.Resources.Rdma = nil
    69  			}
    70  			spec.Linux.Resources.HugepageLimits = nil
    71  			spec.Linux.Resources.Network = nil
    72  		}
    73  	}
    74  
    75  	if spec.Process.OOMScoreAdj != nil && *spec.Process.OOMScoreAdj < currentOOMScoreAdj {
    76  		*spec.Process.OOMScoreAdj = currentOOMScoreAdj
    77  	}
    78  	return nil
    79  }