disk_linux.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. // Contains the Linux implementation of process disk IO counter retrieval.
  17. package metrics
  18. import (
  19. "bufio"
  20. "fmt"
  21. "io"
  22. "os"
  23. "strconv"
  24. "strings"
  25. )
  26. // ReadDiskStats retrieves the disk IO stats belonging to the current process.
  27. func ReadDiskStats(stats *DiskStats) error {
  28. // Open the process disk IO counter file
  29. inf, err := os.Open(fmt.Sprintf("/proc/%d/io", os.Getpid()))
  30. if err != nil {
  31. return err
  32. }
  33. in := bufio.NewReader(inf)
  34. // Iterate over the IO counter, and extract what we need
  35. for {
  36. // Read the next line and split to key and value
  37. line, err := in.ReadString('\n')
  38. if err != nil {
  39. if err == io.EOF {
  40. return nil
  41. }
  42. return err
  43. }
  44. key, value := "", int64(0)
  45. if parts := strings.Split(line, ":"); len(parts) != 2 {
  46. continue
  47. } else {
  48. key = strings.TrimSpace(parts[0])
  49. if value, err = strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64); err != nil {
  50. return err
  51. }
  52. }
  53. // Update the counter based on the key
  54. switch key {
  55. case "syscr":
  56. stats.ReadCount = value
  57. case "syscw":
  58. stats.WriteCount = value
  59. case "rchar":
  60. stats.ReadBytes = value
  61. case "wchar":
  62. stats.WriteBytes = value
  63. }
  64. }
  65. return nil
  66. }