-
Notifications
You must be signed in to change notification settings - Fork 0
/
host_info.go
99 lines (88 loc) · 1.78 KB
/
host_info.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
93
94
95
96
97
98
99
package main
import (
"bytes"
"encoding/json"
"fmt"
"os/exec"
"strconv"
"strings"
)
const (
cmdCPU = "lscpu --json"
cmdDisk = "lsblk --json --nodeps --bytes"
)
type hostInfo struct {
cpuModel string
diskSize int64
}
type lscpuInfo struct {
Lscpu []struct {
Field string `json:"field"`
Data string `json:"data"`
} `json:"lscpu"`
}
type lsblkInfo struct {
Lsblk []struct {
Name string `json:"name"`
Size string `json:"size"`
} `json:"blockdevices"`
}
func (h *hostInfo) getDiskInfo() error {
out, err := execShell(cmdDisk)
if err != nil {
return err
}
i := &lsblkInfo{}
if err := json.Unmarshal([]byte(out), i); err != nil {
return err
}
size := int64(0)
for _, b := range i.Lsblk {
if strings.Contains(b.Name, "loop") {
continue
}
s, err := strconv.ParseInt(b.Size, 10, 64)
if err != nil {
return err
}
size += s
}
h.diskSize = size
return nil
}
func (h *hostInfo) getCPUInfo() error {
out, err := execShell(cmdCPU)
if err != nil {
return err
}
i := &lscpuInfo{}
if err := json.Unmarshal([]byte(out), i); err != nil {
return err
}
for _, c := range i.Lscpu {
if strings.Contains(c.Field, "Model name") {
h.cpuModel = parseCPUModel(c.Data)
break
}
}
return nil
}
func parseCPUModel(model string) string {
if strings.Contains(model, "Intel") {
ms := strings.Split(model, " ")
return strings.TrimSpace(ms[2])
}
return model
}
// ExecBashShell exec bash shell command
func execShell(arg string) (string, error) {
cmd := exec.Command("bash", "-c", arg)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("exec shell failed, out_msg:%s, err_msg:%s, err:%s",
stdout.String(), stderr.String(), err.Error())
}
return stdout.String(), nil
}