cpu.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package fs2
  2. import (
  3. "bufio"
  4. "os"
  5. "strconv"
  6. "github.com/opencontainers/runc/libcontainer/cgroups"
  7. "github.com/opencontainers/runc/libcontainer/cgroups/fscommon"
  8. "github.com/opencontainers/runc/libcontainer/configs"
  9. )
  10. func isCpuSet(r *configs.Resources) bool {
  11. return r.CpuWeight != 0 || r.CpuQuota != 0 || r.CpuPeriod != 0
  12. }
  13. func setCpu(dirPath string, r *configs.Resources) error {
  14. if !isCpuSet(r) {
  15. return nil
  16. }
  17. // NOTE: .CpuShares is not used here. Conversion is the caller's responsibility.
  18. if r.CpuWeight != 0 {
  19. if err := cgroups.WriteFile(dirPath, "cpu.weight", strconv.FormatUint(r.CpuWeight, 10)); err != nil {
  20. return err
  21. }
  22. }
  23. if r.CpuQuota != 0 || r.CpuPeriod != 0 {
  24. str := "max"
  25. if r.CpuQuota > 0 {
  26. str = strconv.FormatInt(r.CpuQuota, 10)
  27. }
  28. period := r.CpuPeriod
  29. if period == 0 {
  30. // This default value is documented in
  31. // https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html
  32. period = 100000
  33. }
  34. str += " " + strconv.FormatUint(period, 10)
  35. if err := cgroups.WriteFile(dirPath, "cpu.max", str); err != nil {
  36. return err
  37. }
  38. }
  39. return nil
  40. }
  41. func statCpu(dirPath string, stats *cgroups.Stats) error {
  42. const file = "cpu.stat"
  43. f, err := cgroups.OpenFile(dirPath, file, os.O_RDONLY)
  44. if err != nil {
  45. return err
  46. }
  47. defer f.Close()
  48. sc := bufio.NewScanner(f)
  49. for sc.Scan() {
  50. t, v, err := fscommon.ParseKeyValue(sc.Text())
  51. if err != nil {
  52. return &parseError{Path: dirPath, File: file, Err: err}
  53. }
  54. switch t {
  55. case "usage_usec":
  56. stats.CpuStats.CpuUsage.TotalUsage = v * 1000
  57. case "user_usec":
  58. stats.CpuStats.CpuUsage.UsageInUsermode = v * 1000
  59. case "system_usec":
  60. stats.CpuStats.CpuUsage.UsageInKernelmode = v * 1000
  61. case "nr_periods":
  62. stats.CpuStats.ThrottlingData.Periods = v
  63. case "nr_throttled":
  64. stats.CpuStats.ThrottlingData.ThrottledPeriods = v
  65. case "throttled_usec":
  66. stats.CpuStats.ThrottlingData.ThrottledTime = v * 1000
  67. }
  68. }
  69. if err := sc.Err(); err != nil {
  70. return &parseError{Path: dirPath, File: file, Err: err}
  71. }
  72. return nil
  73. }