-
Notifications
You must be signed in to change notification settings - Fork 97
/
check-disk.go
352 lines (298 loc) · 9.68 KB
/
check-disk.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package checkdisk
import (
"errors"
"fmt"
"os"
"sort"
"strconv"
"strings"
"github.com/jessevdk/go-flags"
"github.com/mackerelio/checkers"
gpud "github.com/shirou/gopsutil/v3/disk"
)
var opts struct {
Warning *string `short:"w" long:"warning" value-name:"N, N%" description:"Exit with WARNING status if less than N units or N% of disk are free"`
Critical *string `short:"c" long:"critical" value-name:"N, N%" description:"Exit with CRITICAL status if less than N units or N% of disk are free"`
InodeWarning *string `short:"W" long:"iwarning" value-name:"N%" description:"Exit with WARNING status if less than PERCENT of inode space is free"`
InodeCritical *string `short:"K" long:"icritical" value-name:"N%" description:"Exit with CRITICAL status if less than PERCENT of inode space is free"`
Path *[]string `short:"p" long:"path" value-name:"PATH" description:"Mount point or block device as emitted by the mount(8) command (may be repeated)"`
Exclude *[]string `short:"x" long:"exclude-device" value-name:"EXCLUDE PATH" description:"Ignore device (may be repeated; only works if -p unspecified)"`
All bool `short:"A" long:"all" description:"Explicitly select all paths."`
ExcludeType *[]string `short:"X" long:"exclude-type" value-name:"TYPE" description:"Ignore all filesystems of indicated type (may be repeated)"`
IncludeType *[]string `short:"N" long:"include-type" value-name:"TYPE" description:"Check only filesystems of indicated type (may be repeated)"`
Units *string `short:"u" long:"units" value-name:"STRING" description:"Choose bytes, kB, MB, GB, TB (default: MB)"`
}
const (
b = float64(1)
kb = float64(1024) * b
mb = float64(1024) * kb
gb = float64(1024) * mb
tb = float64(1024) * gb
)
type unit struct {
Name string
Size float64
}
func checkDisk(current checkers.Status, threshold string, units float64, disk *gpud.UsageStat, status checkers.Status) (checkers.Status, error) {
if strings.HasSuffix(threshold, "%") {
thresholdPct, err := strconv.ParseFloat(strings.TrimRight(threshold, "%"), 64)
if err != nil {
return checkers.UNKNOWN, err
}
freePct := float64(100) - disk.UsedPercent
if thresholdPct > freePct {
current = status
}
} else {
thresholdVal, err := strconv.ParseFloat(threshold, 64)
if err != nil {
return checkers.UNKNOWN, err
}
free := float64(disk.Free) / units
if thresholdVal > free {
current = status
}
}
return current, nil
}
func checkInodes(current checkers.Status, threshold string, disk *gpud.UsageStat, status checkers.Status) (checkers.Status, error) {
if !strings.HasSuffix(threshold, "%") {
return checkers.UNKNOWN, errors.New("-W, -K value should be N%")
}
thresholdPct, err := strconv.ParseFloat(strings.TrimRight(threshold, "%"), 64)
if err != nil {
return checkers.UNKNOWN, err
}
if disk.InodesTotal == 0 {
return checkers.UNKNOWN, fmt.Errorf("Disk %s does not have inodes", disk.Path)
}
inodesFreePct := float64(100) - disk.InodesUsedPercent
if thresholdPct > inodesFreePct {
current = status
}
return current, nil
}
func genMessage(disk *gpud.UsageStat, u unit) string {
all := float64(disk.Total) / u.Size
used := float64(disk.Used) / u.Size
free := float64(disk.Free) / u.Size
freePct := float64(100) - disk.UsedPercent
inodesFreePctStr := ""
if disk.InodesTotal != 0 {
inodesFreePct := float64(100) - disk.InodesUsedPercent
inodesFreePctStr = fmt.Sprintf(" (inodes %.2f)", inodesFreePct)
}
return fmt.Sprintf("Path: %v, All: %.2f %v, Used: %.2f %v, Free: %.2f %v, Free percentage: %.2f%s", disk.Path, all, u.Name, used, u.Name, free, u.Name, freePct, inodesFreePctStr)
}
// Do the plugin
func Do() {
ckr := run(os.Args[1:])
ckr.Name = "Disk"
ckr.Exit()
}
func run(args []string) *checkers.Checker {
_, err := flags.ParseArgs(&opts, args)
if err != nil {
os.Exit(1)
}
partitions, err := listPartitions()
if err != nil {
return checkers.Unknown(fmt.Sprintf("Failed to fetch partitions: %s", err))
}
if !opts.All {
// Filtering partitions by Fstype
if opts.IncludeType != nil {
partitions = filterPartitionsByInclusion(partitions, *opts.IncludeType, fstypeOfPartition)
if len(partitions) == 0 {
return checkers.Unknown(fmt.Sprintf("Failed to fetch partitions: %s", errors.New("No device found for the specified *FsType*")))
}
}
if opts.ExcludeType != nil {
partitions = filterPartitionsByExclusion(partitions, *opts.ExcludeType, fstypeOfPartition)
}
// Filtering partions by Mountpoint
if opts.Path != nil {
if opts.Exclude != nil {
return checkers.Unknown(fmt.Sprintf("Invalid arguments: %s", errors.New("-x does not work with -p")))
}
partitions = filterPartitionsByInclusion(partitions, *opts.Path, mountpointOfPartition)
if len(partitions) == 0 {
return checkers.Unknown(fmt.Sprintf("Failed to fetch partitions: %s", errors.New("No device found for the specified *Mountpoint*")))
}
}
if opts.Path == nil && opts.Exclude != nil {
partitions = filterPartitionsByExclusion(partitions, *opts.Exclude, mountpointOfPartition)
}
}
if len(partitions) == 0 {
return checkers.Unknown(fmt.Sprintf("Failed to fetch partitions: %s", errors.New("No device found")))
}
var disks []*gpud.UsageStat
for _, partition := range partitions {
disk, err := gpud.Usage(partition.Mountpoint)
if err != nil {
return checkers.Unknown(fmt.Sprintf("%s[type=%s]: Failed to fetch disk usage: %s", partition.Mountpoint, partition.Fstype, err))
}
if disk.Total != 0 {
disks = append(disks, disk)
}
}
u := unit{"MB", mb}
if opts.Units != nil {
us := strings.ToLower(*opts.Units)
if us == "bytes" {
u = unit{us, b}
} else if us == "kb" {
u = unit{us, mb}
} else if us == "gb" {
u = unit{us, gb}
} else if us == "tb" {
u = unit{us, tb}
} else {
return checkers.Unknown(fmt.Sprintf("Failed to check disk status: %s", errors.New("Invalid argument flag '-u, --units'")))
}
}
checkSt := checkers.OK
if opts.InodeCritical != nil {
for _, disk := range disks {
checkSt, err = checkInodes(checkSt, *opts.InodeCritical, disk, checkers.CRITICAL)
if err != nil {
return checkers.Unknown(fmt.Sprintf("%s: Failed to check disk status: %s", disk.Path, err))
}
if checkSt == checkers.CRITICAL {
break
}
}
}
if checkSt != checkers.CRITICAL && opts.Critical != nil {
for _, disk := range disks {
checkSt, err = checkDisk(checkSt, *opts.Critical, u.Size, disk, checkers.CRITICAL)
if err != nil {
return checkers.Unknown(fmt.Sprintf("%s: Failed to check disk status: %s", disk.Path, err))
}
if checkSt == checkers.CRITICAL {
break
}
}
}
if checkSt != checkers.CRITICAL && opts.InodeWarning != nil {
for _, disk := range disks {
checkSt, err = checkInodes(checkSt, *opts.InodeWarning, disk, checkers.WARNING)
if err != nil {
return checkers.Unknown(fmt.Sprintf("%s: Failed to check disk status: %s", disk.Path, err))
}
if checkSt == checkers.WARNING {
break
}
}
}
if checkSt == checkers.OK && opts.Warning != nil {
for _, disk := range disks {
checkSt, err = checkDisk(checkSt, *opts.Warning, u.Size, disk, checkers.WARNING)
if err != nil {
return checkers.Unknown(fmt.Sprintf("%s: Failed to check disk status: %s", disk.Path, err))
}
if checkSt == checkers.WARNING {
break
}
}
}
sortDisks(disks)
var msgs []string
for _, disk := range disks {
msg := genMessage(disk, u)
msgs = append(msgs, msg)
}
msgss := strings.Join(msgs, ";\n")
return checkers.NewChecker(checkSt, msgss)
}
// ref: mountlist.c in gnulib
// https://github.com/coreutils/gnulib/blob/df336dc/lib/mountlist.c#L164
func listPartitions() ([]gpud.PartitionStat, error) {
allPartitions, err := gpud.Partitions(true)
if err != nil {
return nil, err
}
partitions := make([]gpud.PartitionStat, 0, len(allPartitions))
for _, p := range allPartitions {
switch p.Fstype {
case "autofs",
"proc",
"subfs",
"debugfs",
"devpts",
"fusectl",
"fuse.portal",
"mqueue",
"rpc_pipefs",
"sysfs",
"devfs",
"kernfs",
"ignore":
continue
case "none":
if !isBindMount(p.Opts) {
continue
}
partitions = append(partitions, p)
default:
partitions = append(partitions, p)
}
}
return partitions, nil
}
func isBindMount(mountOpts []string) bool {
for _, opt := range mountOpts {
if opt == "bind" {
return true
}
}
return false
}
func mountpointOfPartition(partition gpud.PartitionStat) string {
return partition.Mountpoint
}
func fstypeOfPartition(partition gpud.PartitionStat) string {
return partition.Fstype
}
func filterPartitionsByInclusion(partitions []gpud.PartitionStat, list []string, key func(_ gpud.PartitionStat) string) []gpud.PartitionStat {
newPartitions := make([]gpud.PartitionStat, 0, len(partitions))
for _, partition := range partitions {
var ok = false
for _, l := range list {
if l == key(partition) {
ok = true
break
}
}
if ok {
newPartitions = append(newPartitions, partition)
}
}
return newPartitions
}
func filterPartitionsByExclusion(partitions []gpud.PartitionStat, list []string, key func(_ gpud.PartitionStat) string) []gpud.PartitionStat {
newPartitions := make([]gpud.PartitionStat, 0, len(partitions))
for _, partition := range partitions {
var ok = true
for _, l := range list {
if l == key(partition) {
ok = false
break
}
}
if ok {
newPartitions = append(newPartitions, partition)
}
}
return newPartitions
}
// sortDisks sorts by UsedPercent only at the moment. If this is refactored, ideally this sort would match what threshold was tripped.
func sortDisks(disks []*gpud.UsageStat) {
if len(disks) <= 1 {
return
}
sort.SliceStable(disks, func(i, j int) bool {
return disks[i].UsedPercent > disks[j].UsedPercent
})
}