/
disk_linux.go
330 lines (301 loc) · 8.21 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package hardware_check
import (
"bufio"
"encoding/json"
"fmt"
"gitlab.com/anthony.j.martin/aether-report/internal/pkg/util_funcs"
"io"
"os"
"regexp"
"strconv"
"strings"
"syscall"
"text/tabwriter"
)
type ValidDisks struct {
Partition string `json:"partition"`
Mount string `json:"mount"`
Type string `json:"type"`
Options string `json:"options"`
}
type DiskBlocks struct {
Blocks uint64 `json:"blocks"`
Bsize int64 `json:"block_size"`
Bfree uint64 `json:"blocks_free"`
Bavail uint64 `json:"blocks_avail"`
Bused uint64 `json:"blocks_used"`
Bpercent string `json:"blocks_percent"`
Balert string `json:"blocks_alert"`
}
type DiskInodes struct {
Inodes uint64 `json:"inodes"`
Ifree uint64 `json:"inodes_free"`
Iused uint64 `json:"inodes_used"`
Ipercent string `json:"inodes_percent"`
Ialert string `json:"inodes_alert"`
}
type DiskDetails struct {
Name string `json:"name"`
Partition string `json:"partition"`
PartitionType string `json:"partition_type"`
ReadOnly bool `json:"read_only"`
Blocks DiskBlocks `json:"disk_blocks"`
Inodes DiskInodes `json:"disk_inodes"`
}
// Convert DiskDetails fields to human-readable formats.
func (d DiskDetails) humanReadable(metric string) (sizeAsString string) {
var sizedBlocks float64
switch {
case metric == "total":
sizedBlocks = float64(d.Blocks.Blocks * uint64(d.Blocks.Bsize))
case metric == "used":
sizedBlocks = float64(d.Blocks.Bused * uint64(d.Blocks.Bsize))
case metric == "available":
sizedBlocks = float64(d.Blocks.Bavail * uint64(d.Blocks.Bsize))
default:
sizedBlocks = float64(d.Blocks.Blocks * uint64(d.Blocks.Bsize))
}
switch {
case sizedBlocks >= TB:
sizeAsString = fmt.Sprintf("%.2fTB", sizedBlocks/float64(TB))
case sizedBlocks >= GB:
sizeAsString = fmt.Sprintf("%.2fGB", sizedBlocks/float64(GB))
case sizedBlocks >= MB:
sizeAsString = fmt.Sprintf("%.2fMB", sizedBlocks/float64(MB))
case sizedBlocks >= KB:
sizeAsString = fmt.Sprintf("%.2fKB", sizedBlocks/float64(KB))
default:
sizeAsString = fmt.Sprintf("%.2fB", sizedBlocks)
}
return sizeAsString
}
const (
B = 1
KB = B << 10
MB = KB << 10
GB = MB << 10
TB = GB << 10
)
var excludedFsTypes = []string{
"autofs",
"usbfs",
"rootfs",
"proc",
"sysfs",
"devtmpfs",
"devpts",
"tmpfs",
"binfmt_misc",
"rpc_pipefs",
"squashfs",
"debugfs",
"efivarfs",
"cgroup",
"mqueue",
"hugetlbfs",
"fuse",
"config",
"configfs",
"pstore",
"securityfs",
"nsfs",
"selinuxfs",
"tracefs",
"overlay",
}
// Get list of mounted filesystems
func getMounts(diskFile string, testDiskInfo syscall.Statfs_t) ([]DiskDetails, error) {
var diskDetails []DiskDetails
var validDisks []ValidDisks
if strings.HasPrefix(diskFile, "/") {
inFile, err := os.Open(diskFile)
if err != nil {
return nil, err
}
defer inFile.Close()
validDisk, err := parseDiskFile(inFile)
if err != nil {
return nil, err
}
for i := range validDisk {
validDisks = append(validDisks, validDisk[i])
}
} else {
inFile := strings.NewReader(diskFile)
validDisk, err := parseDiskFile(inFile)
if err != nil {
return nil, err
}
for i := range validDisk {
validDisks = append(validDisks, validDisk[i])
}
}
for i := range validDisks {
data := validDisks[i]
ro := true
opts := strings.Split(data.Options, ",")
for _, opt := range opts {
if opt == "rw" {
ro = false
break
}
}
fs, err := getDiskInfo(data.Mount, testDiskInfo)
if err != nil {
continue
}
bPercent, _ := getPercent(fs.Blocks, fs.Bavail)
iPercent, _ := getPercent(fs.Files, fs.Ffree)
blockAlert, inodeAlert := checkAlert(fs.Blocks, fs.Bavail, fs.Files, fs.Ffree, fs.Bsize)
mount := DiskDetails{
Name: data.Mount,
Partition: data.Partition,
PartitionType: data.Type,
ReadOnly: ro,
Blocks: DiskBlocks{
Blocks: fs.Blocks,
Bsize: fs.Bsize,
Bfree: fs.Bfree,
Bavail: fs.Bavail,
Bused: fs.Blocks - fs.Bavail,
Bpercent: bPercent,
Balert: blockAlert,
},
Inodes: DiskInodes{
Inodes: fs.Files,
Ifree: fs.Ffree,
Iused: fs.Files - fs.Ffree,
Ipercent: iPercent,
Ialert: inodeAlert,
},
}
diskDetails = append(diskDetails, mount)
}
return diskDetails, nil
}
// Return syscall.Statfs_t struct with drive info. Mainly in its own func for testing purposes.
func getDiskInfo(mount string, fakeDiskInfo syscall.Statfs_t) (fs syscall.Statfs_t, err error) {
fs = syscall.Statfs_t{}
if fakeDiskInfo == fs {
err = syscall.Statfs(mount, &fs)
return
} else {
fs, err = fakeDiskInfo, nil
return
}
}
// Return strings from file that contain valid disk information.
func parseDiskFile(inFile io.Reader) ([]ValidDisks, error) {
var validDisks []ValidDisks
skipMountRegex, _ := regexp.Compile("^/(proc|snap)/") // We do not want reports on virtual filesystems.
scanner := bufio.NewScanner(inFile)
for scanner.Scan() {
line := scanner.Text()
data := strings.Fields(line)
if !skipMountRegex.MatchString(data[1]) && !util_funcs.StringInSlice(data[2], excludedFsTypes) {
diskString := ValidDisks{
Partition: data[0],
Mount: data[1],
Type: data[2],
Options: data[3],
}
validDisks = append(validDisks, diskString)
}
}
if len(validDisks) == 0 {
err := fmt.Errorf("no disk found")
return nil, err
}
return validDisks, nil
}
// Calculate percent for blocks and inodes.
func getPercent(total, avail uint64) (sPercent string, iPercent int) {
iPercent = int(float64(total-avail) / float64(total) * 100)
switch {
case iPercent >= 0:
sPercent = strconv.Itoa(iPercent) + "%"
default:
iPercent = 0
sPercent = "-%"
}
return
}
// Determine if storage needs to have a warning, alert, or is ok.
func checkAlert(blocks, blocksAvail, inodes, inodesFree uint64, blockSize int64) (blockAlert string, inodeAlert string) {
_, bPercent := getPercent(blocks, blocksAvail)
bAvail := blockSize * int64(blocksAvail)
_, iPercent := getPercent(inodes, inodesFree)
switch {
case bPercent < 90 || bAvail >= 20*GB && bPercent < 95:
blockAlert = "ok"
case bPercent >= 90 && bPercent < 95:
blockAlert = "warn"
default:
blockAlert = "alert"
}
if iPercent >= 95 {
inodeAlert = "alert"
} else {
inodeAlert = "ok"
}
return
}
// Output data for "text" format.
func textOutput(humanRead, inode bool, diskFile string, testDiskInfo syscall.Statfs_t) error {
if humanRead && inode {
return fmt.Errorf("can not use humanRead and inode together")
}
fmt.Println("##### Disk Usage Stats #####")
w := new(tabwriter.Writer)
w.Init(os.Stdout, 2, 4, 0, ' ', 0)
defer w.Flush()
diskDetails, err := getMounts(diskFile, testDiskInfo)
if err != nil {
return err
}
switch {
case inode:
fmt.Fprintln(w, "Filesystem \tInodes \tUsed \tAvail \tUse% \tMount")
case humanRead:
fmt.Fprintln(w, "Filesystem \tSize \tUsed \tAvail \tUse% \tMount")
default:
fmt.Fprintln(w, "Filesystem \tBlocks \tUsed \tAvail \tUse% \tMount\t BlockSize")
}
for i := range diskDetails {
d := diskDetails[i]
dI := d.Inodes
dB := d.Blocks
if inode {
fmt.Fprintf(w, "%s \t%d \t%d \t%d \t%s \t%s \n",
d.Partition, dI.Inodes, dI.Iused, dI.Ifree, dI.Ipercent, d.Name)
} else {
if humanRead {
fmt.Fprintf(w, "%s \t%s \t%s \t%s \t%s \t%s \n",
d.Partition, d.humanReadable("total"), d.humanReadable("used"), d.humanReadable("available"), dB.Bpercent, d.Name)
} else {
fmt.Fprintf(w, "%s \t%d \t%d \t%d \t%s \t%s \t%d \n",
d.Partition, dB.Blocks, dB.Bused, dB.Bavail, dB.Bpercent, d.Name, dB.Bsize)
}
}
}
return nil
}
// Process data based on passed variables.
func RunDiskInfo(outputFmt string, humanRead, inode bool, diskFile string, fakeDiskInfo syscall.Statfs_t) (jsonReturn []byte, err, textReturn error) {
if humanRead && inode {
err = fmt.Errorf("\nError: Cannot use both -h and -i flags.\n\nRun 'aether-report COMMAND --help' for more information on a command.")
return
}
if outputFmt == "text" {
textReturn = textOutput(humanRead, inode, diskFile, fakeDiskInfo)
return
} else if outputFmt == "json" {
jsonData, err := getMounts(diskFile, fakeDiskInfo)
if err != nil {
return nil, err, nil
}
jsonReturn, err = json.Marshal(jsonData)
fmt.Println(string(jsonReturn))
}
return
}