-
Notifications
You must be signed in to change notification settings - Fork 83
/
meminfo.go
92 lines (78 loc) · 1.81 KB
/
meminfo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package nux
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"strconv"
"strings"
"github.com/toolkits/file"
)
type Mem struct {
Buffers uint64
Cached uint64
MemTotal uint64
MemFree uint64
MemAvailable uint64
SwapTotal uint64
SwapUsed uint64
SwapFree uint64
}
func (this *Mem) String() string {
return fmt.Sprintf("<MemTotal:%d, MemFree:%d, MemAvailable:%d, Buffers:%d, Cached:%d...>", this.MemTotal, this.MemFree, this.MemAvailable, this.Buffers, this.Cached)
}
var Multi uint64 = 1024
var WANT = map[string]struct{}{
"Buffers:": struct{}{},
"Cached:": struct{}{},
"MemTotal:": struct{}{},
"MemFree:": struct{}{},
"MemAvailable:": struct{}{},
"SwapTotal:": struct{}{},
"SwapFree:": struct{}{},
}
func MemInfo() (*Mem, error) {
contents, err := ioutil.ReadFile(Root() + "/proc/meminfo")
if err != nil {
return nil, err
}
memInfo := &Mem{}
reader := bufio.NewReader(bytes.NewBuffer(contents))
for {
line, err := file.ReadLine(reader)
if err == io.EOF {
err = nil
break
} else if err != nil {
return nil, err
}
fields := strings.Fields(string(line))
fieldName := fields[0]
_, ok := WANT[fieldName]
if ok && len(fields) == 3 {
val, numerr := strconv.ParseUint(fields[1], 10, 64)
if numerr != nil {
continue
}
switch fieldName {
case "Buffers:":
memInfo.Buffers = val * Multi
case "Cached:":
memInfo.Cached = val * Multi
case "MemTotal:":
memInfo.MemTotal = val * Multi
case "MemFree:":
memInfo.MemFree = val * Multi
case "MemAvailable:":
memInfo.MemAvailable = val * Multi
case "SwapTotal:":
memInfo.SwapTotal = val * Multi
case "SwapFree:":
memInfo.SwapFree = val * Multi
}
}
}
memInfo.SwapUsed = memInfo.SwapTotal - memInfo.SwapFree
return memInfo, nil
}