/
lsblk.go
121 lines (93 loc) · 2.64 KB
/
lsblk.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
121
package utils
import (
"context"
"encoding/json"
"os"
"strings"
"github.com/bmc-toolbox/common"
"github.com/metal-toolbox/ironlib/model"
"github.com/pkg/errors"
)
const (
EnvLsblkUtility = "IRONLIB_UTIL_LSBLK"
)
var ErrLsblkTransportUnsupported = errors.New("Unsupported transport type")
type Lsblk struct {
Executor Executor
}
type lsblkDeviceAttributes struct {
Name string `json:"name"`
Device string `json:"kname"`
Model string `json:"model"`
Serial string `json:"serial"`
Firmware string `json:"rev:"`
Transport string `json:"tran"`
}
// Return a new lsblk executor
func NewLsblkCmd(trace bool) *Lsblk {
utility := "lsblk"
// lookup env var for util
if eVar := os.Getenv(EnvLsblkUtility); eVar != "" {
utility = eVar
}
e := NewExecutor(utility)
e.SetEnv([]string{"LC_ALL=C.UTF-8"})
if !trace {
e.SetQuiet()
}
return &Lsblk{Executor: e}
}
// Attributes implements the actions.UtilAttributeGetter interface
func (l *Lsblk) Attributes() (utilName model.CollectorUtility, absolutePath string, err error) {
// Call CheckExecutable first so that the Executable CmdPath is resolved.
er := l.Executor.CheckExecutable()
return "lsblk", l.Executor.CmdPath(), er
}
// Executes lsblk list, parses the output and returns a slice of *common.Drive
func (l *Lsblk) Drives(ctx context.Context) ([]*common.Drive, error) {
drives := make([]*common.Drive, 0)
out, err := l.list(ctx)
if err != nil {
return nil, err
}
items := map[string][]*lsblkDeviceAttributes{}
err = json.Unmarshal(out, &items)
if err != nil {
return nil, err
}
for _, d := range items["blockdevices"] {
dModel := d.Model
var vendor string
modelTokens := strings.Split(d.Model, " ")
if len(modelTokens) > 1 {
vendor = modelTokens[1]
}
drive := &common.Drive{
Protocol: strings.ToLower(d.Transport),
Common: common.Common{
LogicalName: strings.TrimSpace(d.Device),
Serial: strings.TrimSpace(d.Serial),
Vendor: strings.TrimSpace(vendor),
Model: strings.TrimSpace(dModel),
},
StorageControllerDriveID: -1,
}
drives = append(drives, drive)
}
return drives, nil
}
func (l *Lsblk) list(ctx context.Context) ([]byte, error) {
// lsblk --json --nodeps --output name,path,model,serial,tran -e1,7,11
l.Executor.SetArgs([]string{"--json", "--nodeps", "-p", "--output", "kname,name,model,serial,rev,tran", "-e1,7,11"})
result, err := l.Executor.ExecWithContext(ctx)
if err != nil {
return nil, err
}
return result.Stdout, nil
}
// NewFakeLsblk returns a mock lsblk collector that returns mock data for use in tests.
func NewFakeLsblk() *Lsblk {
return &Lsblk{
Executor: NewFakeExecutor("lsblk"),
}
}