pids.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package fs2
  2. import (
  3. "errors"
  4. "math"
  5. "os"
  6. "strings"
  7. "golang.org/x/sys/unix"
  8. "github.com/opencontainers/runc/libcontainer/cgroups"
  9. "github.com/opencontainers/runc/libcontainer/cgroups/fscommon"
  10. "github.com/opencontainers/runc/libcontainer/configs"
  11. )
  12. func isPidsSet(r *configs.Resources) bool {
  13. return r.PidsLimit != 0
  14. }
  15. func setPids(dirPath string, r *configs.Resources) error {
  16. if !isPidsSet(r) {
  17. return nil
  18. }
  19. if val := numToStr(r.PidsLimit); val != "" {
  20. if err := cgroups.WriteFile(dirPath, "pids.max", val); err != nil {
  21. return err
  22. }
  23. }
  24. return nil
  25. }
  26. func statPidsFromCgroupProcs(dirPath string, stats *cgroups.Stats) error {
  27. // if the controller is not enabled, let's read PIDS from cgroups.procs
  28. // (or threads if cgroup.threads is enabled)
  29. contents, err := cgroups.ReadFile(dirPath, "cgroup.procs")
  30. if errors.Is(err, unix.ENOTSUP) {
  31. contents, err = cgroups.ReadFile(dirPath, "cgroup.threads")
  32. }
  33. if err != nil {
  34. return err
  35. }
  36. pids := strings.Count(contents, "\n")
  37. stats.PidsStats.Current = uint64(pids)
  38. stats.PidsStats.Limit = 0
  39. return nil
  40. }
  41. func statPids(dirPath string, stats *cgroups.Stats) error {
  42. current, err := fscommon.GetCgroupParamUint(dirPath, "pids.current")
  43. if err != nil {
  44. if os.IsNotExist(err) {
  45. return statPidsFromCgroupProcs(dirPath, stats)
  46. }
  47. return err
  48. }
  49. max, err := fscommon.GetCgroupParamUint(dirPath, "pids.max")
  50. if err != nil {
  51. return err
  52. }
  53. // If no limit is set, read from pids.max returns "max", which is
  54. // converted to MaxUint64 by GetCgroupParamUint. Historically, we
  55. // represent "no limit" for pids as 0, thus this conversion.
  56. if max == math.MaxUint64 {
  57. max = 0
  58. }
  59. stats.PidsStats.Current = current
  60. stats.PidsStats.Limit = max
  61. return nil
  62. }