utils.go 2.0 KB

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