forked from shirou/gopsutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisk_linux.go
120 lines (107 loc) · 2.46 KB
/
disk_linux.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// +build linux
package gopsutil
import (
"fmt"
"os/exec"
"strconv"
"strings"
)
const (
SectorSize = 512
)
// Get disk partitions.
// should use setmntent(3) but this implement use /etc/mtab file
func DiskPartitions(all bool) ([]DiskPartitionStat, error) {
filename := "/etc/mtab"
lines, err := readLines(filename)
if err != nil {
return nil, err
}
ret := make([]DiskPartitionStat, 0, len(lines))
for _, line := range lines {
fields := strings.Fields(line)
d := DiskPartitionStat{
Device: fields[0],
Mountpoint: fields[1],
Fstype: fields[2],
Opts: fields[3],
}
ret = append(ret, d)
}
return ret, nil
}
func DiskIOCounters() (map[string]DiskIOCountersStat, error) {
filename := "/proc/diskstats"
lines, err := readLines(filename)
if err != nil {
return nil, err
}
ret := make(map[string]DiskIOCountersStat, 0)
empty := DiskIOCountersStat{}
for _, line := range lines {
fields := strings.Fields(line)
name := fields[2]
reads, err := strconv.ParseUint((fields[3]), 10, 64)
if err != nil {
return ret, err
}
rbytes, err := strconv.ParseUint((fields[5]), 10, 64)
if err != nil {
return ret, err
}
rtime, err := strconv.ParseUint((fields[6]), 10, 64)
if err != nil {
return ret, err
}
writes, err := strconv.ParseUint((fields[7]), 10, 64)
if err != nil {
return ret, err
}
wbytes, err := strconv.ParseUint((fields[9]), 10, 64)
if err != nil {
return ret, err
}
wtime, err := strconv.ParseUint((fields[10]), 10, 64)
if err != nil {
return ret, err
}
iotime, err := strconv.ParseUint((fields[12]), 10, 64)
if err != nil {
return ret, err
}
d := DiskIOCountersStat{
ReadBytes: rbytes * SectorSize,
WriteBytes: wbytes * SectorSize,
ReadCount: reads,
WriteCount: writes,
ReadTime: rtime,
WriteTime: wtime,
IoTime: iotime,
}
if d == empty {
continue
}
d.Name = name
d.SerialNumber = GetDiskSerialNumber(name)
ret[name] = d
}
return ret, nil
}
func GetDiskSerialNumber(name string) string {
n := fmt.Sprintf("--name=%s", name)
out, err := exec.Command("/sbin/udevadm", "info", "--query=property", n).Output()
// does not return error, just an empty string
if err != nil {
return ""
}
lines := strings.Split(string(out), "\n")
for _, line := range lines {
values := strings.Split(line, "=")
if len(values) < 2 || values[0] != "ID_SERIAL" {
// only get ID_SERIAL, not ID_SERIAL_SHORT
continue
}
return values[1]
}
return ""
}