1
0

load_linux.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // +build linux
  2. package load
  3. import (
  4. "context"
  5. "io/ioutil"
  6. "strconv"
  7. "strings"
  8. "github.com/shirou/gopsutil/internal/common"
  9. )
  10. func Avg() (*AvgStat, error) {
  11. return AvgWithContext(context.Background())
  12. }
  13. func AvgWithContext(ctx context.Context) (*AvgStat, error) {
  14. filename := common.HostProc("loadavg")
  15. line, err := ioutil.ReadFile(filename)
  16. if err != nil {
  17. return nil, err
  18. }
  19. values := strings.Fields(string(line))
  20. load1, err := strconv.ParseFloat(values[0], 64)
  21. if err != nil {
  22. return nil, err
  23. }
  24. load5, err := strconv.ParseFloat(values[1], 64)
  25. if err != nil {
  26. return nil, err
  27. }
  28. load15, err := strconv.ParseFloat(values[2], 64)
  29. if err != nil {
  30. return nil, err
  31. }
  32. ret := &AvgStat{
  33. Load1: load1,
  34. Load5: load5,
  35. Load15: load15,
  36. }
  37. return ret, nil
  38. }
  39. // Misc returnes miscellaneous host-wide statistics.
  40. // Note: the name should be changed near future.
  41. func Misc() (*MiscStat, error) {
  42. return MiscWithContext(context.Background())
  43. }
  44. func MiscWithContext(ctx context.Context) (*MiscStat, error) {
  45. filename := common.HostProc("stat")
  46. out, err := ioutil.ReadFile(filename)
  47. if err != nil {
  48. return nil, err
  49. }
  50. ret := &MiscStat{}
  51. lines := strings.Split(string(out), "\n")
  52. for _, line := range lines {
  53. fields := strings.Fields(line)
  54. if len(fields) != 2 {
  55. continue
  56. }
  57. v, err := strconv.ParseInt(fields[1], 10, 64)
  58. if err != nil {
  59. continue
  60. }
  61. switch fields[0] {
  62. case "procs_running":
  63. ret.ProcsRunning = int(v)
  64. case "procs_blocked":
  65. ret.ProcsBlocked = int(v)
  66. case "ctxt":
  67. ret.Ctxt = int(v)
  68. default:
  69. continue
  70. }
  71. }
  72. return ret, nil
  73. }