stat.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package procfs
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "strings"
  8. )
  9. // Stat represents kernel/system statistics.
  10. type Stat struct {
  11. // Boot time in seconds since the Epoch.
  12. BootTime int64
  13. }
  14. // NewStat returns kernel/system statistics read from /proc/stat.
  15. func NewStat() (Stat, error) {
  16. fs, err := NewFS(DefaultMountPoint)
  17. if err != nil {
  18. return Stat{}, err
  19. }
  20. return fs.NewStat()
  21. }
  22. // NewStat returns an information about current kernel/system statistics.
  23. func (fs FS) NewStat() (Stat, error) {
  24. f, err := os.Open(fs.Path("stat"))
  25. if err != nil {
  26. return Stat{}, err
  27. }
  28. defer f.Close()
  29. s := bufio.NewScanner(f)
  30. for s.Scan() {
  31. line := s.Text()
  32. if !strings.HasPrefix(line, "btime") {
  33. continue
  34. }
  35. fields := strings.Fields(line)
  36. if len(fields) != 2 {
  37. return Stat{}, fmt.Errorf("couldn't parse %s line %s", f.Name(), line)
  38. }
  39. i, err := strconv.ParseInt(fields[1], 10, 32)
  40. if err != nil {
  41. return Stat{}, fmt.Errorf("couldn't parse %s: %s", fields[1], err)
  42. }
  43. return Stat{BootTime: i}, nil
  44. }
  45. if err := s.Err(); err != nil {
  46. return Stat{}, fmt.Errorf("couldn't parse %s: %s", f.Name(), err)
  47. }
  48. return Stat{}, fmt.Errorf("couldn't parse %s, missing btime", f.Name())
  49. }