-
Notifications
You must be signed in to change notification settings - Fork 0
/
sys.go
109 lines (97 loc) · 2.18 KB
/
sys.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
package mxdisk
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
)
// SysBlockInfo the info from /sys/block
type SysBlockInfo struct {
Ro int64
Removable int64
slaves []string
}
// SysMapBlocks the map of /sys/block devices
type SysMapBlocks map[string]SysBlockInfo
func (p SysMapBlocks) String() string {
var s string
for k, v := range p {
s += fmt.Sprintf("%v : %+v\n", k, v)
}
return s
}
func (p SysMapBlocks) exposeDevsSlaves(devs []string) []string {
mp := make(map[string]bool)
for _, v := range devs {
mp[v] = true
if m, ok := p[v]; ok {
for _, s := range m.slaves {
mp[s] = true
}
}
}
var res []string
for k := range mp {
res = append(res, k)
}
// recursion for detect sub-sub slaves
if len(res) > len(devs) {
return p.exposeDevsSlaves(res)
}
return res
}
func readIntFromFile(f string) (val int64, err error) {
var data []byte
if data, err = ioutil.ReadFile(f); err != nil {
return
}
sdata := string(data[:len(data)-1])
if val, err = strconv.ParseInt(sdata, 10, 0); err != nil {
return
}
return val, err
}
func readSysBlockSlaveInPath(path string) []string {
var res []string
filepath.Walk(path, func(path string, inf os.FileInfo, err error) error {
if err != nil {
return err // if path is not exists
}
if inf.IsDir() {
return nil
}
if (inf.Mode() & os.ModeSymlink) != 0 {
base := "/dev/" + filepath.Base(path)
res = append(res, base)
}
return err
})
return res
}
// info from std /sys/class/block path
func fetchSysBlock(path string) SysMapBlocks {
mp := make(SysMapBlocks)
filepath.Walk(path, func(path string, inf os.FileInfo, err error) error {
if err != nil {
return err // if path is not exists
}
if inf.IsDir() {
return nil
}
if (inf.Mode() & os.ModeSymlink) != 0 {
base := "/dev/" + filepath.Base(path)
syspath, _ := filepath.EvalSymlinks(path)
ro, _ := readIntFromFile(syspath + "/ro")
removable, _ := readIntFromFile(syspath + "/removable")
slaves := readSysBlockSlaveInPath(syspath + "/slaves/") // for detect mdadm slaves
mp[base] = SysBlockInfo{
Ro: ro,
Removable: removable,
slaves: slaves,
}
}
return err
})
return mp
}