/
stats.go
50 lines (45 loc) · 1005 Bytes
/
stats.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
package nexnode
import (
"bufio"
"os"
"strconv"
"strings"
controlapi "github.com/synadia-io/nex/control-api"
)
// This function only works on Linux, but that's okay since nex-node can only run on 64-bit linux
func ReadMemoryStats() (*controlapi.MemoryStat, error) {
file, err := os.Open("/proc/meminfo")
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
res := controlapi.MemoryStat{}
for scanner.Scan() {
key, value := parseLine(scanner.Text())
switch key {
case "MemTotal":
res.MemTotal = value
case "MemFree":
res.MemFree = value
case "MemAvailable":
res.MemAvailable = value
}
}
return &res, nil
}
func parseLine(raw string) (key string, value int) {
text := strings.ReplaceAll(raw[:len(raw)-2], " ", "")
keyValue := strings.Split(text, ":")
return keyValue[0], toInt(keyValue[1])
}
func toInt(raw string) int {
if raw == "" {
return 0
}
res, err := strconv.Atoi(raw)
if err != nil {
return -1
}
return res
}