utils.go 12 KB

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