v1.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package cgroups
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. )
  9. // V1 returns all the groups in the default cgroups mountpoint in a single hierarchy
  10. func V1() ([]Subsystem, error) {
  11. root, err := v1MountPoint()
  12. if err != nil {
  13. return nil, err
  14. }
  15. subsystems, err := defaults(root)
  16. if err != nil {
  17. return nil, err
  18. }
  19. var enabled []Subsystem
  20. for _, s := range pathers(subsystems) {
  21. // check and remove the default groups that do not exist
  22. if _, err := os.Lstat(s.Path("/")); err == nil {
  23. enabled = append(enabled, s)
  24. }
  25. }
  26. return enabled, nil
  27. }
  28. // v1MountPoint returns the mount point where the cgroup
  29. // mountpoints are mounted in a single hiearchy
  30. func v1MountPoint() (string, error) {
  31. f, err := os.Open("/proc/self/mountinfo")
  32. if err != nil {
  33. return "", err
  34. }
  35. defer f.Close()
  36. scanner := bufio.NewScanner(f)
  37. for scanner.Scan() {
  38. if err := scanner.Err(); err != nil {
  39. return "", err
  40. }
  41. var (
  42. text = scanner.Text()
  43. fields = strings.Split(text, " ")
  44. // safe as mountinfo encodes mountpoints with spaces as \040.
  45. index = strings.Index(text, " - ")
  46. postSeparatorFields = strings.Fields(text[index+3:])
  47. numPostFields = len(postSeparatorFields)
  48. )
  49. // this is an error as we can't detect if the mount is for "cgroup"
  50. if numPostFields == 0 {
  51. return "", fmt.Errorf("Found no fields post '-' in %q", text)
  52. }
  53. if postSeparatorFields[0] == "cgroup" {
  54. // check that the mount is properly formated.
  55. if numPostFields < 3 {
  56. return "", fmt.Errorf("Error found less than 3 fields post '-' in %q", text)
  57. }
  58. return filepath.Dir(fields[4]), nil
  59. }
  60. }
  61. return "", ErrMountPointNotExist
  62. }