utils.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // +build linux
  2. package fs
  3. import (
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. )
  11. var (
  12. ErrNotSupportStat = errors.New("stats are not supported for subsystem")
  13. ErrNotValidFormat = errors.New("line is not a valid key value format")
  14. )
  15. // Saturates negative values at zero and returns a uint64.
  16. // Due to kernel bugs, some of the memory cgroup stats can be negative.
  17. func parseUint(s string, base, bitSize int) (uint64, error) {
  18. value, err := strconv.ParseUint(s, base, bitSize)
  19. if err != nil {
  20. intValue, intErr := strconv.ParseInt(s, base, bitSize)
  21. // 1. Handle negative values greater than MinInt64 (and)
  22. // 2. Handle negative values lesser than MinInt64
  23. if intErr == nil && intValue < 0 {
  24. return 0, nil
  25. } else if intErr != nil && intErr.(*strconv.NumError).Err == strconv.ErrRange && intValue < 0 {
  26. return 0, nil
  27. }
  28. return value, err
  29. }
  30. return value, nil
  31. }
  32. // Parses a cgroup param and returns as name, value
  33. // i.e. "io_service_bytes 1234" will return as io_service_bytes, 1234
  34. func getCgroupParamKeyValue(t string) (string, uint64, error) {
  35. parts := strings.Fields(t)
  36. switch len(parts) {
  37. case 2:
  38. value, err := parseUint(parts[1], 10, 64)
  39. if err != nil {
  40. return "", 0, fmt.Errorf("unable to convert param value (%q) to uint64: %v", parts[1], err)
  41. }
  42. return parts[0], value, nil
  43. default:
  44. return "", 0, ErrNotValidFormat
  45. }
  46. }
  47. // Gets a single uint64 value from the specified cgroup file.
  48. func getCgroupParamUint(cgroupPath, cgroupFile string) (uint64, error) {
  49. fileName := filepath.Join(cgroupPath, cgroupFile)
  50. contents, err := ioutil.ReadFile(fileName)
  51. if err != nil {
  52. return 0, err
  53. }
  54. res, err := parseUint(strings.TrimSpace(string(contents)), 10, 64)
  55. if err != nil {
  56. return res, fmt.Errorf("unable to parse %q as a uint from Cgroup file %q", string(contents), fileName)
  57. }
  58. return res, nil
  59. }
  60. // Gets a string value from the specified cgroup file
  61. func getCgroupParamString(cgroupPath, cgroupFile string) (string, error) {
  62. contents, err := ioutil.ReadFile(filepath.Join(cgroupPath, cgroupFile))
  63. if err != nil {
  64. return "", err
  65. }
  66. return strings.TrimSpace(string(contents)), nil
  67. }