loadavg.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package linux
  2. import (
  3. "errors"
  4. "io/ioutil"
  5. "strconv"
  6. "strings"
  7. )
  8. type LoadAvg struct {
  9. Last1Min float64 `json:"last1min"`
  10. Last5Min float64 `json:"last5min"`
  11. Last15Min float64 `json:"last15min"`
  12. ProcessRunning uint64 `json:"process_running"`
  13. ProcessTotal uint64 `json:"process_total"`
  14. LastPID uint64 `json:"last_pid"`
  15. }
  16. func ReadLoadAvg(path string) (*LoadAvg, error) {
  17. b, err := ioutil.ReadFile(path)
  18. if err != nil {
  19. return nil, err
  20. }
  21. content := strings.TrimSpace(string(b))
  22. fields := strings.Fields(content)
  23. if len(fields) < 5 {
  24. return nil, errors.New("Cannot parse loadavg: " + content)
  25. }
  26. process := strings.Split(fields[3], "/")
  27. if len(process) != 2 {
  28. return nil, errors.New("Cannot parse loadavg: " + content)
  29. }
  30. loadavg := LoadAvg{}
  31. if loadavg.Last1Min, err = strconv.ParseFloat(fields[0], 64); err != nil {
  32. return nil, err
  33. }
  34. if loadavg.Last5Min, err = strconv.ParseFloat(fields[1], 64); err != nil {
  35. return nil, err
  36. }
  37. if loadavg.Last15Min, err = strconv.ParseFloat(fields[2], 64); err != nil {
  38. return nil, err
  39. }
  40. if loadavg.ProcessRunning, err = strconv.ParseUint(process[0], 10, 64); err != nil {
  41. return nil, err
  42. }
  43. if loadavg.ProcessTotal, err = strconv.ParseUint(process[1], 10, 64); err != nil {
  44. return nil, err
  45. }
  46. if loadavg.LastPID, err = strconv.ParseUint(fields[4], 10, 64); err != nil {
  47. return nil, err
  48. }
  49. return &loadavg, nil
  50. }