-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin.go
More file actions
467 lines (385 loc) · 11.3 KB
/
plugin.go
File metadata and controls
467 lines (385 loc) · 11.3 KB
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/*
Package plugin provides a Go library which helps writing monitoring plugins.
Features:
* Setting and appending check messages
* Aggregation of results
* Thresholds and ranges for metrics with breaches reported
* Exit shortcut helper methods
* Provides extensive command line options parser
Example usage:
package main
// import plugin library
import (
"github.com/ajgb/go-plugin"
)
// define command line options
var opts struct {
Hostname string `short:"H" long:"hostname" description:"Host" required:"true"`
Port int `short:"p" long:"port" description:"Port" required:"true"`
}
func main() {
// initialize check
check := plugin.New("check_service", "v1.0.0")
// parse command line arguments
if err := check.ParseArgs(&opts); err != nil {
check.ExitCritical("Error parsing arguments: %s", err)
}
// return result on exit
defer check.Final()
// add service data to output
check.AddMessage("Service %s:%d", opts.Hostname, opts.Port)
// gather metrics - provided by some function
serviceMetrics, err := .... // retrieve metrics
if err != nil {
check.ExitCritical("Connection failed: %s", err)
}
// add metrics to output
for metric, value := range serviceMetrics {
check.AddMetric(metric, value)
}
}
*/
package plugin
import (
"bytes"
"fmt"
"github.com/jessevdk/go-flags"
"io"
"os"
"sort"
"strconv"
"strings"
)
// Plugin represents the check - its name, version and help messages. It also
// stores the check status, messages and metrics data.
type Plugin struct {
status Status
messages []string
metrics checkMetrics
// Plugin name
Name string
// Plugin version
Version string
// Preamble displayed in help output before flags usage
Preamble string
// Plugin description displayed in help after flags usage
Description string
// If true all metrics will be added to check message
AllMetricsInOutput bool
// Messages separator, default: ", "
MessageSeparator string
}
type checkMetric struct {
value interface{}
status Status
uom string
warn string
critical string
}
type checkMetrics map[string]*checkMetric
var pOsExit = func(code Status) { os.Exit(code.ExitCode()) }
var pOutputHandle io.Writer = os.Stdout
var pArgs = os.Args[1:]
/*
New creates a new plugin instance.
check := plugin.New("check_service", "v1.0.0")
*/
func New(name, version string) *Plugin {
return &Plugin{
status: OK,
messages: make([]string, 0),
metrics: make(checkMetrics),
Name: name,
Version: version,
AllMetricsInOutput: false,
MessageSeparator: ", ",
}
}
/*
AddMetric adds new metric to check's performance data, with name and value
parameters required. The optional string arguments include (in order):
uom (unit of measurement), warning threshold, critical threshold - for
details see Monitoring Plugins Development Guidelines.
Note: Metrics names have to be unique.
// basic usage - add metric with value
check.AddMetric("load5", 0.98)
// metric with UOM
check.AddMetric("tmp", 15789, "MB")
// metric with warning threshold (without uom)
check.AddMetric("rtmax", 28.723, "", 75)
// metric with warning & critical thresholds (with uom)
check.AddMetric("rta", 24.558, "ms", 50, 100)
*/
func (p *Plugin) AddMetric(name string, value interface{}, args ...string) error {
argsCount := len(args)
metric := &checkMetric{}
if strings.ContainsRune(name, ' ') && !strings.HasPrefix(name, "'") {
name = "'" + name + "'"
}
if _, ok := p.metrics[name]; ok {
return fmt.Errorf("Duplicated metric %s", name)
}
metric.value = value
if argsCount >= 1 {
metric.uom = args[0]
}
val, err := i2f(value)
if err != nil {
return fmt.Errorf("Invalid value of %s: %v", name, value)
}
var alertMessage string
if argsCount == 2 || argsCount == 3 {
var thresholdBreached bool
for i, a := range args[1:] {
var thresholdName string
var invert bool
if len(a) == 0 {
continue
}
arg := strings.TrimPrefix(a, "@")
if a != arg {
invert = true
}
thresh := strings.Split(arg, ":")
switch i {
case 0:
thresholdName = "warning"
metric.warn = a
case 1:
thresholdName = "critical"
metric.critical = a
}
switch len(thresh) {
case 1:
// v < X
tMax, err := strconv.ParseFloat(thresh[0], 64)
if err != nil {
return fmt.Errorf("Invalid format of %s threshold %s: %s", thresholdName, name, a)
}
thresholdBreached = val < 0 || val > tMax
case 2:
switch {
case thresh[0] == "~":
tMax, err := strconv.ParseFloat(thresh[1], 64)
if err != nil {
return fmt.Errorf("Invalid format of %s threshold %s: %s", thresholdName, name, a)
}
thresholdBreached = val > tMax
case thresh[1] == "":
tMin, err := strconv.ParseFloat(thresh[0], 64)
if err != nil {
return fmt.Errorf("Invalid format of %s threshold %s: %s", thresholdName, name, a)
}
thresholdBreached = val < tMin
default:
tMin, err := strconv.ParseFloat(thresh[0], 64)
if err != nil {
return fmt.Errorf("Invalid format of %s threshold %s: %s", thresholdName, name, a)
}
tMax, err := strconv.ParseFloat(thresh[1], 64)
if err != nil {
return fmt.Errorf("Invalid format of %s threshold %s: %s", thresholdName, name, a)
}
if tMin > tMax {
return fmt.Errorf("Invalid format of %s threshold %s: %s", thresholdName, name, a)
}
thresholdBreached = val < tMin || val > tMax
}
default:
return fmt.Errorf("Invalid format of %s threshold %s: %s", thresholdName, name, a)
}
if invert {
thresholdBreached = !thresholdBreached
}
if thresholdBreached {
metric.status = Status(i + 1) // i=0 warning, i=1 critical
if invert {
alertMessage = fmt.Sprintf("%s is %v%s (inside %s)", name, value, metric.uom, a)
} else {
alertMessage = fmt.Sprintf("%s is %v%s (outside %s)", name, value, metric.uom, a)
}
}
}
} else if argsCount > 3 {
return fmt.Errorf("Too many arguments")
}
if len(alertMessage) > 0 {
p.AddMessage(alertMessage)
} else if p.AllMetricsInOutput {
p.AddMessage(fmt.Sprintf("%s is %v%s", name, value, metric.uom))
}
p.metrics[name] = metric
p.UpdateStatus(metric.status)
return nil
}
/*
AddMessage appends message to check output.
check.AddMessage("Server %s", opts.Hostname)
*/
func (p *Plugin) AddMessage(format string, args ...interface{}) {
var msg string
if len(args) > 0 {
msg = fmt.Sprintf(format, args...)
} else {
msg = fmt.Sprint(format)
}
p.messages = append(p.messages, msg)
}
/*
AddResult aggregates results and appends message to check output - the worst
result is final.
// would not change the final result
check.AddResult(plugin.OK, "Server %s", opts.Hostname)
// increases to WARNING level
if opts.SkipSSLChecks {
check.AddResult(plugin.WARNING, "Skiping SSL Certificate checks")
}
*/
func (p *Plugin) AddResult(code Status, format string, args ...interface{}) {
p.UpdateStatus(code)
p.AddMessage(format, args...)
}
/*
Final calculates the final check output and exit status.
check := plugin.New("check_service, "v1.0.0")
// make sure Final() is called
defer check.Final()
*/
func (p *Plugin) Final() {
if r := recover(); r != nil {
p.ExitCritical("%s panic: %v", p.Name, r)
return // for testing only as it overrides the os.Exit
}
fmt.Fprintf(pOutputHandle, "%s:", p.status.String())
if len(p.messages) > 0 {
fmt.Fprintf(pOutputHandle, " ")
fmt.Fprint(pOutputHandle, strings.Join(p.messages, p.MessageSeparator))
}
if len(p.metrics) > 0 {
var sorted []string
sorted = make([]string, 0, len(p.metrics))
fmt.Fprintf(pOutputHandle, " |")
for k := range p.metrics {
sorted = append(sorted, k)
}
sort.Strings(sorted)
for _, k := range sorted {
fmt.Fprintf(pOutputHandle, " %s=%v%s;%s;%s;;",
k,
p.metrics[k].value,
p.metrics[k].uom,
p.metrics[k].warn,
p.metrics[k].critical,
)
}
}
fmt.Fprintf(pOutputHandle, "\n")
pOsExit(p.status)
}
/*
SetMessage replaces accumulated messages with new one provided.
check.SetMessage("%s", opts.Hostname)
*/
func (p *Plugin) SetMessage(format string, args ...interface{}) {
p.messages = []string{}
p.AddMessage(format, args...)
}
func (p *Plugin) exit(code Status, format string, args ...interface{}) {
p.status = code
p.SetMessage(format, args...)
p.metrics = make(checkMetrics)
p.Final()
}
/*
ExitOK exits with specified message and OK exit status.
Note: existing messages and metrics are discarded.
check.ExitOK("Test mode | metric1=1.1; metric2=2.2")
*/
func (p *Plugin) ExitOK(format string, args ...interface{}) {
p.exit(OK, format, args...)
}
// ExitUnknown exits with specified message and UNKNOWN exit status.
// Note: existing messages and metrics are discarded.
func (p *Plugin) ExitUnknown(format string, args ...interface{}) {
p.exit(UNKNOWN, format, args...)
}
// ExitWarning exits with specified message and WARNING exit status.
// Note: existing messages and metrics are discarded.
func (p *Plugin) ExitWarning(format string, args ...interface{}) {
p.exit(WARNING, format, args...)
}
// ExitCritical exits with specified message and CRITICAL exit status.
// Note: existing messages and metrics are discarded.
func (p *Plugin) ExitCritical(format string, args ...interface{}) {
p.exit(CRITICAL, format, args...)
}
/*
ParseArgs parses the command line options using flags parsing library
providing handling of short/long names, flags and lists, and default and
required options. For details please see https://godoc.org/github.com/jessevdk/go-flags.
Note: -h/--help is automatically added
if err := check.ParseArgs(&opts); err != nil {
check.ExitCritical("Error parsing arguments: %s", err)
}
*/
func (p *Plugin) ParseArgs(opts interface{}) error {
var err error
var builtin struct {
Help bool `short:"h" long:"help" description:"Show this help message"`
}
parser := flags.NewParser(opts, 0)
_, err = parser.AddGroup("Default Options", "", &builtin)
g := parser.Command.Group.Find("Application Options")
if g != nil {
g.ShortDescription = "Plugin Options"
}
_, err = parser.ParseArgs(pArgs)
if builtin.Help {
fmt.Fprintf(pOutputHandle, "%s v%s\n", p.Name, strings.TrimPrefix(p.Version, "v"))
if len(p.Preamble) > 0 {
fmt.Fprintln(pOutputHandle, p.Preamble)
}
parser.Options = flags.HelpFlag
var b bytes.Buffer
parser.WriteHelp(&b)
fmt.Fprintln(pOutputHandle, b.String())
if len(p.Description) > 0 {
fmt.Fprintln(pOutputHandle, p.Description)
}
pOsExit(UNKNOWN)
}
return err
}
/*
UpdateStatus updates final exit status if the provided value is higher
(worse) then the current Status.
// keep people awake
if rand.Intn(100) % 3 == 0 {
check.UpdateStatus(plugin.CRITICAL)
}
*/
func (p *Plugin) UpdateStatus(status Status) {
if int(status) > int(p.status) {
p.status = status
}
}
/*
Status returns current status.
fmt.Printf("Status after first five metrics: %s\n", check.Status)
*/
func (p *Plugin) Status() Status {
return p.status
}
func i2f(v interface{}) (float64, error) {
var f float64
var err error
switch v.(type) {
case float32:
f = float64(v.(float32))
case float64:
f = v.(float64)
default:
f, err = strconv.ParseFloat(fmt.Sprintf("%v", v), 64)
}
return f, err
}