utils.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. // +build linux
  2. package cgroups
  3. import (
  4. "bufio"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/opencontainers/runc/libcontainer/cgroups/fscommon"
  16. "github.com/opencontainers/runc/libcontainer/userns"
  17. "github.com/sirupsen/logrus"
  18. "golang.org/x/sys/unix"
  19. )
  20. const (
  21. CgroupProcesses = "cgroup.procs"
  22. unifiedMountpoint = "/sys/fs/cgroup"
  23. )
  24. var (
  25. isUnifiedOnce sync.Once
  26. isUnified bool
  27. )
  28. // IsCgroup2UnifiedMode returns whether we are running in cgroup v2 unified mode.
  29. func IsCgroup2UnifiedMode() bool {
  30. isUnifiedOnce.Do(func() {
  31. var st unix.Statfs_t
  32. err := unix.Statfs(unifiedMountpoint, &st)
  33. if err != nil {
  34. if os.IsNotExist(err) && userns.RunningInUserNS() {
  35. // ignore the "not found" error if running in userns
  36. logrus.WithError(err).Debugf("%s missing, assuming cgroup v1", unifiedMountpoint)
  37. isUnified = false
  38. return
  39. }
  40. panic(fmt.Sprintf("cannot statfs cgroup root: %s", err))
  41. }
  42. isUnified = st.Type == unix.CGROUP2_SUPER_MAGIC
  43. })
  44. return isUnified
  45. }
  46. type Mount struct {
  47. Mountpoint string
  48. Root string
  49. Subsystems []string
  50. }
  51. // GetCgroupMounts returns the mounts for the cgroup subsystems.
  52. // all indicates whether to return just the first instance or all the mounts.
  53. // This function should not be used from cgroupv2 code, as in this case
  54. // all the controllers are available under the constant unifiedMountpoint.
  55. func GetCgroupMounts(all bool) ([]Mount, error) {
  56. if IsCgroup2UnifiedMode() {
  57. // TODO: remove cgroupv2 case once all external users are converted
  58. availableControllers, err := GetAllSubsystems()
  59. if err != nil {
  60. return nil, err
  61. }
  62. m := Mount{
  63. Mountpoint: unifiedMountpoint,
  64. Root: unifiedMountpoint,
  65. Subsystems: availableControllers,
  66. }
  67. return []Mount{m}, nil
  68. }
  69. return getCgroupMountsV1(all)
  70. }
  71. // GetAllSubsystems returns all the cgroup subsystems supported by the kernel
  72. func GetAllSubsystems() ([]string, error) {
  73. // /proc/cgroups is meaningless for v2
  74. // https://github.com/torvalds/linux/blob/v5.3/Documentation/admin-guide/cgroup-v2.rst#deprecated-v1-core-features
  75. if IsCgroup2UnifiedMode() {
  76. // "pseudo" controllers do not appear in /sys/fs/cgroup/cgroup.controllers.
  77. // - devices: implemented in kernel 4.15
  78. // - freezer: implemented in kernel 5.2
  79. // We assume these are always available, as it is hard to detect availability.
  80. pseudo := []string{"devices", "freezer"}
  81. data, err := fscommon.ReadFile("/sys/fs/cgroup", "cgroup.controllers")
  82. if err != nil {
  83. return nil, err
  84. }
  85. subsystems := append(pseudo, strings.Fields(data)...)
  86. return subsystems, nil
  87. }
  88. f, err := os.Open("/proc/cgroups")
  89. if err != nil {
  90. return nil, err
  91. }
  92. defer f.Close()
  93. subsystems := []string{}
  94. s := bufio.NewScanner(f)
  95. for s.Scan() {
  96. text := s.Text()
  97. if text[0] != '#' {
  98. parts := strings.Fields(text)
  99. if len(parts) >= 4 && parts[3] != "0" {
  100. subsystems = append(subsystems, parts[0])
  101. }
  102. }
  103. }
  104. if err := s.Err(); err != nil {
  105. return nil, err
  106. }
  107. return subsystems, nil
  108. }
  109. func readProcsFile(file string) ([]int, error) {
  110. f, err := os.Open(file)
  111. if err != nil {
  112. return nil, err
  113. }
  114. defer f.Close()
  115. var (
  116. s = bufio.NewScanner(f)
  117. out = []int{}
  118. )
  119. for s.Scan() {
  120. if t := s.Text(); t != "" {
  121. pid, err := strconv.Atoi(t)
  122. if err != nil {
  123. return nil, err
  124. }
  125. out = append(out, pid)
  126. }
  127. }
  128. return out, s.Err()
  129. }
  130. // ParseCgroupFile parses the given cgroup file, typically /proc/self/cgroup
  131. // or /proc/<pid>/cgroup, into a map of subsystems to cgroup paths, e.g.
  132. // "cpu": "/user.slice/user-1000.slice"
  133. // "pids": "/user.slice/user-1000.slice"
  134. // etc.
  135. //
  136. // Note that for cgroup v2 unified hierarchy, there are no per-controller
  137. // cgroup paths, so the resulting map will have a single element where the key
  138. // is empty string ("") and the value is the cgroup path the <pid> is in.
  139. func ParseCgroupFile(path string) (map[string]string, error) {
  140. f, err := os.Open(path)
  141. if err != nil {
  142. return nil, err
  143. }
  144. defer f.Close()
  145. return parseCgroupFromReader(f)
  146. }
  147. // helper function for ParseCgroupFile to make testing easier
  148. func parseCgroupFromReader(r io.Reader) (map[string]string, error) {
  149. s := bufio.NewScanner(r)
  150. cgroups := make(map[string]string)
  151. for s.Scan() {
  152. text := s.Text()
  153. // from cgroups(7):
  154. // /proc/[pid]/cgroup
  155. // ...
  156. // For each cgroup hierarchy ... there is one entry
  157. // containing three colon-separated fields of the form:
  158. // hierarchy-ID:subsystem-list:cgroup-path
  159. parts := strings.SplitN(text, ":", 3)
  160. if len(parts) < 3 {
  161. return nil, fmt.Errorf("invalid cgroup entry: must contain at least two colons: %v", text)
  162. }
  163. for _, subs := range strings.Split(parts[1], ",") {
  164. cgroups[subs] = parts[2]
  165. }
  166. }
  167. if err := s.Err(); err != nil {
  168. return nil, err
  169. }
  170. return cgroups, nil
  171. }
  172. func PathExists(path string) bool {
  173. if _, err := os.Stat(path); err != nil {
  174. return false
  175. }
  176. return true
  177. }
  178. func EnterPid(cgroupPaths map[string]string, pid int) error {
  179. for _, path := range cgroupPaths {
  180. if PathExists(path) {
  181. if err := WriteCgroupProc(path, pid); err != nil {
  182. return err
  183. }
  184. }
  185. }
  186. return nil
  187. }
  188. func rmdir(path string) error {
  189. err := unix.Rmdir(path)
  190. if err == nil || err == unix.ENOENT {
  191. return nil
  192. }
  193. return &os.PathError{Op: "rmdir", Path: path, Err: err}
  194. }
  195. // RemovePath aims to remove cgroup path. It does so recursively,
  196. // by removing any subdirectories (sub-cgroups) first.
  197. func RemovePath(path string) error {
  198. // try the fast path first
  199. if err := rmdir(path); err == nil {
  200. return nil
  201. }
  202. infos, err := ioutil.ReadDir(path)
  203. if err != nil {
  204. if os.IsNotExist(err) {
  205. err = nil
  206. }
  207. return err
  208. }
  209. for _, info := range infos {
  210. if info.IsDir() {
  211. // We should remove subcgroups dir first
  212. if err = RemovePath(filepath.Join(path, info.Name())); err != nil {
  213. break
  214. }
  215. }
  216. }
  217. if err == nil {
  218. err = rmdir(path)
  219. }
  220. return err
  221. }
  222. // RemovePaths iterates over the provided paths removing them.
  223. // We trying to remove all paths five times with increasing delay between tries.
  224. // If after all there are not removed cgroups - appropriate error will be
  225. // returned.
  226. func RemovePaths(paths map[string]string) (err error) {
  227. const retries = 5
  228. delay := 10 * time.Millisecond
  229. for i := 0; i < retries; i++ {
  230. if i != 0 {
  231. time.Sleep(delay)
  232. delay *= 2
  233. }
  234. for s, p := range paths {
  235. if err := RemovePath(p); err != nil {
  236. // do not log intermediate iterations
  237. switch i {
  238. case 0:
  239. logrus.WithError(err).Warnf("Failed to remove cgroup (will retry)")
  240. case retries - 1:
  241. logrus.WithError(err).Error("Failed to remove cgroup")
  242. }
  243. }
  244. _, err := os.Stat(p)
  245. // We need this strange way of checking cgroups existence because
  246. // RemoveAll almost always returns error, even on already removed
  247. // cgroups
  248. if os.IsNotExist(err) {
  249. delete(paths, s)
  250. }
  251. }
  252. if len(paths) == 0 {
  253. //nolint:ineffassign,staticcheck // done to help garbage collecting: opencontainers/runc#2506
  254. paths = make(map[string]string)
  255. return nil
  256. }
  257. }
  258. return fmt.Errorf("Failed to remove paths: %v", paths)
  259. }
  260. func GetHugePageSize() ([]string, error) {
  261. dir, err := os.OpenFile("/sys/kernel/mm/hugepages", unix.O_DIRECTORY|unix.O_RDONLY, 0)
  262. if err != nil {
  263. return nil, err
  264. }
  265. files, err := dir.Readdirnames(0)
  266. dir.Close()
  267. if err != nil {
  268. return nil, err
  269. }
  270. return getHugePageSizeFromFilenames(files)
  271. }
  272. func getHugePageSizeFromFilenames(fileNames []string) ([]string, error) {
  273. pageSizes := make([]string, 0, len(fileNames))
  274. for _, file := range fileNames {
  275. // example: hugepages-1048576kB
  276. val := strings.TrimPrefix(file, "hugepages-")
  277. if len(val) == len(file) {
  278. // unexpected file name: no prefix found
  279. continue
  280. }
  281. // The suffix is always "kB" (as of Linux 5.9)
  282. eLen := len(val) - 2
  283. val = strings.TrimSuffix(val, "kB")
  284. if len(val) != eLen {
  285. logrus.Warnf("GetHugePageSize: %s: invalid filename suffix (expected \"kB\")", file)
  286. continue
  287. }
  288. size, err := strconv.Atoi(val)
  289. if err != nil {
  290. return nil, err
  291. }
  292. // Model after https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/mm/hugetlb_cgroup.c?id=eff48ddeab782e35e58ccc8853f7386bbae9dec4#n574
  293. // but in our case the size is in KB already.
  294. if size >= (1 << 20) {
  295. val = strconv.Itoa(size>>20) + "GB"
  296. } else if size >= (1 << 10) {
  297. val = strconv.Itoa(size>>10) + "MB"
  298. } else {
  299. val += "KB"
  300. }
  301. pageSizes = append(pageSizes, val)
  302. }
  303. return pageSizes, nil
  304. }
  305. // GetPids returns all pids, that were added to cgroup at path.
  306. func GetPids(dir string) ([]int, error) {
  307. return readProcsFile(filepath.Join(dir, CgroupProcesses))
  308. }
  309. // GetAllPids returns all pids, that were added to cgroup at path and to all its
  310. // subcgroups.
  311. func GetAllPids(path string) ([]int, error) {
  312. var pids []int
  313. // collect pids from all sub-cgroups
  314. err := filepath.Walk(path, func(p string, info os.FileInfo, iErr error) error {
  315. if iErr != nil {
  316. return iErr
  317. }
  318. if info.IsDir() || info.Name() != CgroupProcesses {
  319. return nil
  320. }
  321. cPids, err := readProcsFile(p)
  322. if err != nil {
  323. return err
  324. }
  325. pids = append(pids, cPids...)
  326. return nil
  327. })
  328. return pids, err
  329. }
  330. // WriteCgroupProc writes the specified pid into the cgroup's cgroup.procs file
  331. func WriteCgroupProc(dir string, pid int) error {
  332. // Normally dir should not be empty, one case is that cgroup subsystem
  333. // is not mounted, we will get empty dir, and we want it fail here.
  334. if dir == "" {
  335. return fmt.Errorf("no such directory for %s", CgroupProcesses)
  336. }
  337. // Dont attach any pid to the cgroup if -1 is specified as a pid
  338. if pid == -1 {
  339. return nil
  340. }
  341. file, err := fscommon.OpenFile(dir, CgroupProcesses, os.O_WRONLY)
  342. if err != nil {
  343. return fmt.Errorf("failed to write %v to %v: %v", pid, CgroupProcesses, err)
  344. }
  345. defer file.Close()
  346. for i := 0; i < 5; i++ {
  347. _, err = file.WriteString(strconv.Itoa(pid))
  348. if err == nil {
  349. return nil
  350. }
  351. // EINVAL might mean that the task being added to cgroup.procs is in state
  352. // TASK_NEW. We should attempt to do so again.
  353. if errors.Is(err, unix.EINVAL) {
  354. time.Sleep(30 * time.Millisecond)
  355. continue
  356. }
  357. return fmt.Errorf("failed to write %v to %v: %v", pid, CgroupProcesses, err)
  358. }
  359. return err
  360. }
  361. // Since the OCI spec is designed for cgroup v1, in some cases
  362. // there is need to convert from the cgroup v1 configuration to cgroup v2
  363. // the formula for cpuShares is y = (1 + ((x - 2) * 9999) / 262142)
  364. // convert from [2-262144] to [1-10000]
  365. // 262144 comes from Linux kernel definition "#define MAX_SHARES (1UL << 18)"
  366. func ConvertCPUSharesToCgroupV2Value(cpuShares uint64) uint64 {
  367. if cpuShares == 0 {
  368. return 0
  369. }
  370. return (1 + ((cpuShares-2)*9999)/262142)
  371. }
  372. // ConvertMemorySwapToCgroupV2Value converts MemorySwap value from OCI spec
  373. // for use by cgroup v2 drivers. A conversion is needed since Resources.MemorySwap
  374. // is defined as memory+swap combined, while in cgroup v2 swap is a separate value.
  375. func ConvertMemorySwapToCgroupV2Value(memorySwap, memory int64) (int64, error) {
  376. // for compatibility with cgroup1 controller, set swap to unlimited in
  377. // case the memory is set to unlimited, and swap is not explicitly set,
  378. // treating the request as "set both memory and swap to unlimited".
  379. if memory == -1 && memorySwap == 0 {
  380. return -1, nil
  381. }
  382. if memorySwap == -1 || memorySwap == 0 {
  383. // -1 is "max", 0 is "unset", so treat as is
  384. return memorySwap, nil
  385. }
  386. // sanity checks
  387. if memory == 0 || memory == -1 {
  388. return 0, errors.New("unable to set swap limit without memory limit")
  389. }
  390. if memory < 0 {
  391. return 0, fmt.Errorf("invalid memory value: %d", memory)
  392. }
  393. if memorySwap < memory {
  394. return 0, errors.New("memory+swap limit should be >= memory limit")
  395. }
  396. return memorySwap - memory, nil
  397. }
  398. // Since the OCI spec is designed for cgroup v1, in some cases
  399. // there is need to convert from the cgroup v1 configuration to cgroup v2
  400. // the formula for BlkIOWeight to IOWeight is y = (1 + (x - 10) * 9999 / 990)
  401. // convert linearly from [10-1000] to [1-10000]
  402. func ConvertBlkIOToIOWeightValue(blkIoWeight uint16) uint64 {
  403. if blkIoWeight == 0 {
  404. return 0
  405. }
  406. return uint64(1 + (uint64(blkIoWeight)-10)*9999/990)
  407. }