cpu.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // +build linux
  2. package fs
  3. import (
  4. "bufio"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "github.com/opencontainers/runc/libcontainer/cgroups"
  9. "github.com/opencontainers/runc/libcontainer/configs"
  10. )
  11. type CpuGroup struct {
  12. }
  13. func (s *CpuGroup) Name() string {
  14. return "cpu"
  15. }
  16. func (s *CpuGroup) Apply(d *cgroupData) error {
  17. // We always want to join the cpu group, to allow fair cpu scheduling
  18. // on a container basis
  19. _, err := d.join("cpu")
  20. if err != nil && !cgroups.IsNotFound(err) {
  21. return err
  22. }
  23. return nil
  24. }
  25. func (s *CpuGroup) Set(path string, cgroup *configs.Cgroup) error {
  26. if cgroup.Resources.CpuShares != 0 {
  27. if err := writeFile(path, "cpu.shares", strconv.FormatInt(cgroup.Resources.CpuShares, 10)); err != nil {
  28. return err
  29. }
  30. }
  31. if cgroup.Resources.CpuPeriod != 0 {
  32. if err := writeFile(path, "cpu.cfs_period_us", strconv.FormatInt(cgroup.Resources.CpuPeriod, 10)); err != nil {
  33. return err
  34. }
  35. }
  36. if cgroup.Resources.CpuQuota != 0 {
  37. if err := writeFile(path, "cpu.cfs_quota_us", strconv.FormatInt(cgroup.Resources.CpuQuota, 10)); err != nil {
  38. return err
  39. }
  40. }
  41. if cgroup.Resources.CpuRtPeriod != 0 {
  42. if err := writeFile(path, "cpu.rt_period_us", strconv.FormatInt(cgroup.Resources.CpuRtPeriod, 10)); err != nil {
  43. return err
  44. }
  45. }
  46. if cgroup.Resources.CpuRtRuntime != 0 {
  47. if err := writeFile(path, "cpu.rt_runtime_us", strconv.FormatInt(cgroup.Resources.CpuRtRuntime, 10)); err != nil {
  48. return err
  49. }
  50. }
  51. return nil
  52. }
  53. func (s *CpuGroup) Remove(d *cgroupData) error {
  54. return removePath(d.path("cpu"))
  55. }
  56. func (s *CpuGroup) GetStats(path string, stats *cgroups.Stats) error {
  57. f, err := os.Open(filepath.Join(path, "cpu.stat"))
  58. if err != nil {
  59. if os.IsNotExist(err) {
  60. return nil
  61. }
  62. return err
  63. }
  64. defer f.Close()
  65. sc := bufio.NewScanner(f)
  66. for sc.Scan() {
  67. t, v, err := getCgroupParamKeyValue(sc.Text())
  68. if err != nil {
  69. return err
  70. }
  71. switch t {
  72. case "nr_periods":
  73. stats.CpuStats.ThrottlingData.Periods = v
  74. case "nr_throttled":
  75. stats.CpuStats.ThrottlingData.ThrottledPeriods = v
  76. case "throttled_time":
  77. stats.CpuStats.ThrottlingData.ThrottledTime = v
  78. }
  79. }
  80. return nil
  81. }