-
Notifications
You must be signed in to change notification settings - Fork 51
/
disk_linux.go
60 lines (55 loc) · 1.44 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
//go:build linux
// +build linux
package disk
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
// Get disk I/O statistics.
func Get() ([]Stats, error) {
// Reference: Documentation/iostats.txt in the source of Linux
file, err := os.Open("/proc/diskstats")
if err != nil {
return nil, err
}
defer file.Close()
return collectDiskStats(file)
}
// Stats represents disk I/O statistics for linux.
type Stats struct {
Name string // device name; like "hda"
ReadsCompleted uint64 // total number of reads completed successfully
WritesCompleted uint64 // total number of writes completed successfully
}
func collectDiskStats(out io.Reader) ([]Stats, error) {
scanner := bufio.NewScanner(out)
var diskStats []Stats
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) < 14 {
continue
}
name := fields[2]
readsCompleted, err := strconv.ParseUint(fields[3], 10, 64)
if err != nil {
return nil, fmt.Errorf("failed to parse reads completed of %s", name)
}
writesCompleted, err := strconv.ParseUint(fields[7], 10, 64)
if err != nil {
return nil, fmt.Errorf("failed to parse writes completed of %s", name)
}
diskStats = append(diskStats, Stats{
Name: name,
ReadsCompleted: readsCompleted,
WritesCompleted: writesCompleted,
})
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("scan error for /proc/diskstats: %s", err)
}
return diskStats, nil
}