cgroup.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright (c) 2017 Uber Technologies, Inc.
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. //go:build linux
  21. // +build linux
  22. package cgroups
  23. import (
  24. "bufio"
  25. "io"
  26. "os"
  27. "path/filepath"
  28. "strconv"
  29. )
  30. // CGroup represents the data structure for a Linux control group.
  31. type CGroup struct {
  32. path string
  33. }
  34. // NewCGroup returns a new *CGroup from a given path.
  35. func NewCGroup(path string) *CGroup {
  36. return &CGroup{path: path}
  37. }
  38. // Path returns the path of the CGroup*.
  39. func (cg *CGroup) Path() string {
  40. return cg.path
  41. }
  42. // ParamPath returns the path of the given cgroup param under itself.
  43. func (cg *CGroup) ParamPath(param string) string {
  44. return filepath.Join(cg.path, param)
  45. }
  46. // readFirstLine reads the first line from a cgroup param file.
  47. func (cg *CGroup) readFirstLine(param string) (string, error) {
  48. paramFile, err := os.Open(cg.ParamPath(param))
  49. if err != nil {
  50. return "", err
  51. }
  52. defer paramFile.Close()
  53. scanner := bufio.NewScanner(paramFile)
  54. if scanner.Scan() {
  55. return scanner.Text(), nil
  56. }
  57. if err := scanner.Err(); err != nil {
  58. return "", err
  59. }
  60. return "", io.ErrUnexpectedEOF
  61. }
  62. // readInt parses the first line from a cgroup param file as int.
  63. func (cg *CGroup) readInt(param string) (int, error) {
  64. text, err := cg.readFirstLine(param)
  65. if err != nil {
  66. return 0, err
  67. }
  68. return strconv.Atoi(text)
  69. }