github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/rootless/specconv/specconv_linux.go (about)

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