2017-08-03 00:23:08 +00:00
|
|
|
package procfs
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Stat represents kernel/system statistics.
|
|
|
|
type Stat struct {
|
|
|
|
// Boot time in seconds since the Epoch.
|
2017-08-04 11:13:19 +00:00
|
|
|
BootTime int64
|
2017-08-03 00:23:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewStat returns kernel/system statistics read from /proc/stat.
|
|
|
|
func NewStat() (Stat, error) {
|
|
|
|
fs, err := NewFS(DefaultMountPoint)
|
|
|
|
if err != nil {
|
|
|
|
return Stat{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return fs.NewStat()
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewStat returns an information about current kernel/system statistics.
|
|
|
|
func (fs FS) NewStat() (Stat, error) {
|
|
|
|
f, err := os.Open(fs.Path("stat"))
|
|
|
|
if err != nil {
|
|
|
|
return Stat{}, err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
2017-08-04 11:13:19 +00:00
|
|
|
s := bufio.NewScanner(f)
|
|
|
|
for s.Scan() {
|
|
|
|
line := s.Text()
|
|
|
|
if !strings.HasPrefix(line, "btime") {
|
2017-08-03 00:23:08 +00:00
|
|
|
continue
|
|
|
|
}
|
2017-08-04 11:13:19 +00:00
|
|
|
fields := strings.Fields(line)
|
|
|
|
if len(fields) != 2 {
|
|
|
|
return Stat{}, fmt.Errorf("couldn't parse %s line %s", f.Name(), line)
|
|
|
|
}
|
|
|
|
i, err := strconv.ParseInt(fields[1], 10, 32)
|
|
|
|
if err != nil {
|
|
|
|
return Stat{}, fmt.Errorf("couldn't parse %s: %s", fields[1], err)
|
2017-08-03 00:23:08 +00:00
|
|
|
}
|
2017-08-04 11:13:19 +00:00
|
|
|
return Stat{BootTime: i}, nil
|
2017-08-03 00:23:08 +00:00
|
|
|
}
|
2017-08-04 11:13:19 +00:00
|
|
|
if err := s.Err(); err != nil {
|
2017-08-03 00:23:08 +00:00
|
|
|
return Stat{}, fmt.Errorf("couldn't parse %s: %s", f.Name(), err)
|
|
|
|
}
|
|
|
|
|
2017-08-04 11:13:19 +00:00
|
|
|
return Stat{}, fmt.Errorf("couldn't parse %s, missing btime", f.Name())
|
2017-08-03 00:23:08 +00:00
|
|
|
}
|