-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathcheckdata.go
More file actions
1706 lines (1494 loc) · 46.2 KB
/
Copy pathcheckdata.go
File metadata and controls
1706 lines (1494 loc) · 46.2 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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package snclient
import (
"fmt"
"math"
"slices"
"sort"
"strconv"
"strings"
"time"
"github.com/consol-monitoring/snclient/pkg/convert"
"github.com/consol-monitoring/snclient/pkg/utils"
)
var (
// Variable to use in Threshold Min/Max
Zero = float64(0)
Hundred = float64(100)
DefaultCheckTimeout = 60 * time.Second
)
// InventoryMode sets available inventory move
type InventoryMode uint8
const (
NoInventory InventoryMode = iota
ListInventory // calls this check and uses listDetails
ScriptsInventory // does not call this check and puts it into the scripts section
NoCallInventory // does not call this check and puts single entry into inventory
)
// OutputMode sets available output modes
type OutputMode uint8
const (
OutputDefault OutputMode = iota
OutputInventory // only reports available inventory
)
type CommaStringList []string
type CheckArgument struct {
value any // reference to storage pointer
description string // used in help
isFilter bool // if true, default filter is not used when this argument is set
defaultCritical string // overrides default filter if argument is used
defaultWarning string // same for critical condition
}
// Implemented defines the available supported operating systems
type Implemented uint8
// Implemented defines the available supported operating systems
const (
_ Implemented = 1 << iota
Windows
Linux
Darwin
FreeBSD
ALL = Windows | Linux | Darwin | FreeBSD
)
// ShowHelp defines available help options
type ShowHelp uint8
// ShowHelp defines available help options
const (
_ ShowHelp = iota
Markdown
PluginHelp
)
type Unit uint8
const (
UNone Unit = iota
UByte
UDuration
UDate
UTimestamp
UPercent
UBool
)
type CheckAttribute struct {
name string
description string
unit Unit
}
// CheckData contains the runtime data of a generic check plugin
type CheckData struct {
noCopy noCopy
name string
description string
docTitle string
usage string
defaultFilter string
conditionAlias map[string]map[string]string // replacement map of equivalent condition values
conditionColAlias map[string][]string // if there are filter for given column, apply to alias columns too
args map[string]CheckArgument
extraArgs map[string]CheckArgument // internal, map of expanded args
argsPassthrough bool // allow arbitrary arguments without complaining about unknown argument
hasArgsSupplied map[string]bool // map which is true if a arg has been specified on the command line
rawArgs []string
filter ConditionList // if set, only show entries matching this filter set
warnThreshold ConditionList
defaultWarning string
critThreshold ConditionList
defaultCritical string
okThreshold ConditionList
detailSyntax string
topSyntax string
okSyntax string
hasArgsFilter bool // will be true if any arg supplied which has isFilter set
emptySyntax string
emptyState int64
emptyStateSet bool
details map[string]string
listData []map[string]string
listCombine string // join string for detail list
listCombineSet bool // has the listCombine been set by user
showAll bool // flag if check called with show-all
addCountMetrics bool
addCountMetricsToFront bool
addProblemCountMetrics bool
addProblemCountMetricsToFront bool
result *CheckResult
showHelp ShowHelp
timeout float64 // timeout in seconds
perfConfig []PerfConfig
perfSyntax string
hasInventory InventoryMode
output OutputMode
implemented Implemented
attributes []CheckAttribute
listSorted []string // sort result list by this keys
exampleDefault string
exampleArgs string
timezone *time.Location // timezone used for date output set by --timezone
}
func (cd *CheckData) Finalize() (*CheckResult, error) {
defer restoreLogLevel()
log.Tracef("finalize check results:")
if cd.details == nil {
cd.details = map[string]string{}
}
cd.details["top-syntax"] = cd.topSyntax
cd.details["ok-syntax"] = cd.okSyntax
cd.details["empty-syntax"] = cd.emptySyntax
cd.details["detail-syntax"] = cd.detailSyntax
log.Debugf("filter: %s", cd.filter.String())
log.Debugf("condition warning: %s", cd.warnThreshold.String())
log.Debugf("condition critical: %s", cd.critThreshold.String())
log.Debugf("condition ok: %s", cd.okThreshold.String())
// Run thresholds once on cd.details. This is done separately than metrics or entries
// This can possibly set a value to cd.details[_state]
cd.Check(cd.details, cd.warnThreshold, cd.critThreshold, cd.okThreshold)
log.Tracef("details:")
logTraceASCIIMap(cd.details)
// apply final filter
cd.listData = cd.Filter(cd.filter, cd.listData)
cd.listData = cd.sortList(cd.listData, cd.listSorted)
if cd.result == nil {
cd.result = &CheckResult{}
}
cd.result.Raw = cd
if cd.output == OutputInventory {
return cd.result, nil
}
return cd.finalizeOutput()
}
func (cd *CheckData) finalizeOutput() (*CheckResult, error) {
if len(cd.listData) > 0 {
for _, entry := range cd.listData {
if entry["_skip"] == "1" {
continue
}
// not yet filtered errors are fatal
errMsg := entry["_error"]
exitCode := entry["_exit"]
if exitCode != "" {
cd.result.State = convert.Int64(exitCode)
cd.result.Output = fmt.Sprintf("%s - %s", convert.StateString(cd.result.State), errMsg)
log.Tracef("list data:")
logTraceASCIIMap(cd.listData)
log.Tracef("this entry exited and is not filtered, which is fatal:")
log.Tracef("%#v", entry)
return cd.result, nil
}
if errMsg != "" {
log.Tracef("list data:")
logTraceASCIIMap(cd.listData)
log.Tracef("this entry errored and is not filtered, which is fatal:")
log.Tracef("%#v", entry)
return nil, fmt.Errorf("%s", errMsg)
}
// each entry in the list data is individually checked
// This may set "_state" of each entry
cd.Check(entry, cd.warnThreshold, cd.critThreshold, cd.okThreshold)
}
log.Tracef("list data:")
logTraceASCIIMap(cd.listData)
}
var finalMacros map[string]string
log.Tracef("detail template: %s", cd.detailSyntax)
if len(cd.listData) == 1 {
finalMacros = cd.buildListMacrosFromSingleEntry()
} else {
finalMacros = cd.buildListMacros()
}
err := cd.result.ApplyPerfConfig(cd.perfConfig)
if err != nil {
return nil, fmt.Errorf("%s", err.Error())
}
cd.result.ApplyPerfSyntax(cd.perfSyntax, cd.timezone)
// Run a separate check on the macros
cd.Check(finalMacros, cd.warnThreshold, cd.critThreshold, cd.okThreshold)
cd.setStateFromMaps(finalMacros)
// Metrics are checked last, which also sets the final state
cd.CheckMetrics(cd.warnThreshold, cd.critThreshold, cd.okThreshold)
switch {
case cd.result.Output != "":
// already set, leave it
return cd.result, nil
case len(cd.listData) == 0 && (len(cd.filter) > 0 || cd.hasArgsFilter):
if cd.emptySyntax != "" {
cd.result.Output = cd.emptySyntax
}
if cd.emptyStateSet || !cd.HasThreshold("count") {
log.Debugf("exit code set by empty state: %d", cd.emptyState)
cd.result.State = cd.emptyState
}
case cd.showAll:
cd.result.Output = "%(status) - %(list)"
case cd.result.State == 0 && cd.okSyntax != "":
cd.result.Output = cd.okSyntax
default:
cd.result.Output = cd.topSyntax
}
log.Tracef("output template: %s", cd.result.Output)
cd.result.Finalize(cd.timezone, cd.details, finalMacros)
cd.result.Output = removeUnusedMacroFunctions(cd.result.Output)
return cd.result, nil
}
func (cd *CheckData) buildListMacros() map[string]string {
list := make([]string, 0, len(cd.listData))
okList := make([]string, 0)
warnList := make([]string, 0)
critList := make([]string, 0)
count := int64(0)
okCount := int64(0)
warnCount := int64(0)
critCount := int64(0)
for _, entry := range cd.listData {
weight := int64(1)
if w, ok := entry["_count"]; ok {
weight = convert.Int64(w)
}
count += weight
if _, ok := entry["count"]; !ok {
entry["count"] = fmt.Sprintf("%d", weight)
}
expanded, err := ReplaceTemplate(cd.detailSyntax, cd.timezone, entry)
if err != nil {
log.Debugf("replacing syntax failed %s: %s", cd.detailSyntax, err.Error())
}
list = append(list, expanded)
switch entry["_state"] {
case "0":
okList = append(okList, expanded)
okCount += weight
case "1":
warnList = append(warnList, expanded)
warnCount += weight
case "2":
critList = append(critList, expanded)
critCount += weight
}
}
if cd.listCombine == "" && !cd.listCombineSet {
cd.listCombine = ", "
}
result := map[string]string{
"count": fmt.Sprintf("%d", count),
"list": strings.Join(list, cd.listCombine),
"ok_count": fmt.Sprintf("%d", okCount),
"ok_list": "",
"warn_count": fmt.Sprintf("%d", warnCount),
"warn_list": "",
"crit_count": fmt.Sprintf("%d", critCount),
"crit_list": "",
"problem_count": fmt.Sprintf("%d", warnCount+critCount),
"problem_list": "",
"detail_list": "",
}
problemList := []string{}
detailList := []string{}
// if there is only one problem, there is no need to add brackets
if len(critList) > 0 {
result["crit_list"] = "critical(" + strings.Join(critList, cd.listCombine) + ")"
problemList = append(problemList, result["crit_list"])
detailList = append(detailList, result["crit_list"])
}
if len(warnList) > 0 {
result["warn_list"] = "warning(" + strings.Join(warnList, cd.listCombine) + ")"
problemList = append(problemList, result["warn_list"])
detailList = append(detailList, result["warn_list"])
}
if len(okList) > 0 {
result["ok_list"] = strings.Join(okList, cd.listCombine)
detailList = append(detailList, result["ok_list"])
}
result["problem_list"] = strings.Join(problemList, " ")
result["detail_list"] = strings.Join(detailList, " ")
cd.buildCountMetrics(len(list), len(critList), len(warnList))
return result
}
func (cd *CheckData) buildListMacrosFromSingleEntry() map[string]string {
entry := cd.listData[0]
expanded, err := ReplaceTemplate(cd.detailSyntax, cd.timezone, entry)
if err != nil {
log.Debugf("replacing template failed: %s: %s", cd.detailSyntax, err.Error())
}
result := map[string]string{
"count": "1",
"list": expanded,
"ok_count": "0",
"ok_list": "",
"warn_count": "0",
"warn_list": "",
"crit_count": "0",
"crit_list": "",
"problem_count": "0",
"problem_list": "",
"detail_list": expanded,
}
numWarn := 0
numCrit := 0
switch entry["_state"] {
case "0":
result["ok_list"] = expanded
result["ok_count"] = "1"
case "1":
result["problem_list"] = expanded
result["warn_list"] = expanded
result["warn_count"] = "1"
numWarn = 1
case "2":
result["problem_list"] = expanded
result["crit_list"] = expanded
result["crit_count"] = "1"
numCrit = 1
}
cd.buildCountMetrics(1, numCrit, numWarn)
return result
}
func (cd *CheckData) buildCountMetrics(listLen, critLen, warnLen int) {
// prepending is slower, so keep separate flags for adding to front
if cd.addProblemCountMetrics {
metric := &CheckMetric{
Name: "failed",
Value: critLen + warnLen,
Warning: cd.warnThreshold,
Critical: cd.critThreshold,
Min: &Zero,
}
if cd.addProblemCountMetricsToFront {
cd.result.Metrics = append([]*CheckMetric{metric}, cd.result.Metrics...)
} else {
cd.result.Metrics = append(cd.result.Metrics, metric)
}
}
if cd.addCountMetrics {
metric := &CheckMetric{
Name: "count",
Value: listLen,
Warning: cd.warnThreshold,
Critical: cd.critThreshold,
Min: &Zero,
}
if cd.addCountMetricsToFront {
cd.result.Metrics = append([]*CheckMetric{metric}, cd.result.Metrics...)
} else {
cd.result.Metrics = append(cd.result.Metrics, metric)
}
}
}
// setStateFromMaps sets main state from _state or list counts. main state is saved under cd.details["_state"]
func (cd *CheckData) setStateFromMaps(macros map[string]string) {
switch macros["_state"] {
case "1":
cd.result.EscalateStatus(1)
case "2":
cd.result.EscalateStatus(2)
case "3":
cd.result.EscalateStatus(3)
}
switch {
case macros["crit_count"] != "0":
cd.result.EscalateStatus(2)
macros["_state"] = "2"
case macros["warn_count"] != "0":
cd.result.EscalateStatus(1)
macros["_state"] = "1"
}
if state, ok := cd.details["_state"]; ok {
cd.result.EscalateStatus(convert.Int64(state))
}
cd.details["_state"] = fmt.Sprintf("%d", cd.result.State)
}
// Check tries warn/crit/ok conditions against given data and sets result state.
// The data argument can be anything that has the correct keys that conditions use
func (cd *CheckData) Check(data map[string]string, warnCond, critCond, okCond ConditionList) {
data["_state"] = fmt.Sprintf("%d", CheckExitOK)
for i := range warnCond {
if res, ok := warnCond[i].Match(data); res && ok {
log.Debugf("This data '%s' matched the WARNING Condition", warnCond[i].original)
data["_state"] = fmt.Sprintf("%d", CheckExitWarning)
}
}
for i := range critCond {
if res, ok := critCond[i].Match(data); res && ok {
log.Debugf("This data '%s' matched the CRITICAL Condition", critCond[i].original)
data["_state"] = fmt.Sprintf("%d", CheckExitCritical)
}
}
for i := range okCond {
if res, ok := okCond[i].Match(data); res && ok {
log.Debugf("This data '%s' matched the OK Condition", okCond[i].original)
data["_state"] = fmt.Sprintf("%d", CheckExitOK)
}
}
}
// CheckMetrics tries warn/crit/ok conditions against given metrics and sets final state accordingly
func (cd *CheckData) CheckMetrics(warnCond, critCond, okCond ConditionList) {
// each metric is ran through conditions individually
for _, metric := range cd.result.Metrics {
state := CheckExitOK
// build up a data map[string]string as condition.Match function requires it as an argument
data := map[string]string{
metric.Name: fmt.Sprintf("%v", metric.Value),
}
if metric.ThresholdName != "" {
data[metric.ThresholdName] = fmt.Sprintf("%v", metric.Value)
}
for i := range warnCond {
if res, ok := warnCond[i].Match(data); res && ok {
state = CheckExitWarning
}
}
for i := range critCond {
if res, ok := critCond[i].Match(data); res && ok {
state = CheckExitCritical
}
}
for i := range okCond {
if res, ok := okCond[i].Match(data); res && ok {
state = CheckExitOK
}
}
if state > CheckExitOK {
log.Debugf("metric.Name: '%s', metric.ThresholdName: '%s', metric.Value: '%v', gave non-ok state: %s", metric.Name, metric.ThresholdName, metric.Value, convert.StateString(state))
cd.result.EscalateStatus(state)
}
}
}
// MatchFilter returns true if {name: value} matches any filter
func (cd *CheckData) MatchFilter(name, value string) bool {
data := map[string]string{name: value}
res, _ := cd.MatchFilterMap(data)
return res
}
// MatchFilterMap returns true if given map matches any filter
// returns either the result or not ok if the result cannot be determined
func (cd *CheckData) MatchFilterMap(data map[string]string) (res, ok bool) {
finalOK := true
for _, cond := range cd.filter {
if cond.isNone {
return true, true
}
if res, ok = cond.Match(data); res && ok {
return true, true
}
if !ok {
finalOK = false
}
}
return false, finalOK
}
// MatchMapCondition returns true if listEntry matches any filter
// preCheck defines behavior in case an attribute does not exist (set true for pre checks and false for final filter)
func (cd *CheckData) MatchMapCondition(conditions ConditionList, entry map[string]string, preCheck bool) bool {
allOK := true
allNone := true
for _, cond := range conditions {
if cond.isNone {
continue
}
allNone = false
res, ok := cond.Match(entry)
if !ok && !preCheck {
res = cond.compareEmpty()
ok = true
}
if res {
return true
}
if !ok {
allOK = false
}
}
if allNone {
// if all conditions are none, we can safely return true
return true
}
// nothing matched but all conditions were found can be safely filtered
if allOK && preCheck {
return false
}
// nothing matched, this ok on pre checks but a failure otherwise
return preCheck
}
// Filter data map by conditions and return filtered list.
// ALl items not matching given filter will be removed.
func (cd *CheckData) Filter(conditions ConditionList, data []map[string]string) []map[string]string {
if len(conditions) == 0 {
return data
}
result := make([]map[string]string, 0)
for num := range data {
if cd.MatchMapCondition(conditions, data[num], false) {
result = append(result, data[num])
}
}
return result
}
func (cd *CheckData) sortList(listData []map[string]string, keys []string) []map[string]string {
if len(keys) == 0 {
return listData
}
slices.SortStableFunc(listData, func(a, b map[string]string) int {
sortA := make([]string, 0, len(keys))
sortB := make([]string, 0, len(keys))
for _, k := range keys {
sortA = append(sortA, a[k])
sortB = append(sortB, b[k])
}
strA := utils.ReplaceNumbersWithZeroPadded(strings.Join(sortA, ";"), 10)
strB := utils.ReplaceNumbersWithZeroPadded(strings.Join(sortB, ";"), 10)
switch {
case strA == strB:
return 0
case strA > strB:
return 1
default:
return -1
}
})
return listData
}
// parseStateString translates string naemon state to int64
func (cd *CheckData) parseStateString(state string) int64 {
switch strings.ToLower(state) {
case "0", "ok":
return 0
case "1", "warn", "warning":
return 1
case "2", "crit", "critical":
return 2
}
return 3
}
// parseArgs parses check arguments into the CheckData struct
// and returns all unknown options
func (cd *CheckData) parseArgs(args []string) (argList []Argument, err error) {
cd.rawArgs = args
cd.hasArgsSupplied = map[string]bool{}
argList = make([]Argument, 0, len(args))
cd.expandArgDefinitions()
sanitized, defaultWarning, defaultCritical, applyDefaultFilter, err := cd.preParseArgs(args)
if err != nil {
return nil, err
}
// skip argument parsing for external scripts
if _, ok := AvailableChecks[cd.name]; !ok && cd.argsPassthrough {
for _, arg := range sanitized {
argList = append(argList, Argument{key: arg.key, value: arg.value})
}
} else {
argList, applyDefaultFilter, err = cd.processArgs(sanitized, defaultWarning, defaultCritical, applyDefaultFilter)
if err != nil {
return nil, err
}
}
if cd.timezone == nil {
timeZone, _ := time.LoadLocation("Local")
cd.timezone = timeZone
}
err = cd.setFallbacks(applyDefaultFilter, defaultWarning, defaultCritical)
if err != nil {
return nil, err
}
cd.applyConditionColAlias()
cd.applyConditionAlias()
return argList, nil
}
//nolint:funlen,gocyclo // it is not complex, it is just a long list of options
func (cd *CheckData) processArgs(sanitized []Argument, defaultWarning, defaultCritical string, initialApplyDefaultFilter bool) (argList []Argument, applyDefaultFilter bool, err error) {
topSupplied := false
okSupplied := false
applyDefaultFilter = initialApplyDefaultFilter
for _, arg := range sanitized {
keyword := arg.key
argValue := arg.value
argExpr := arg.raw
switch keyword {
case "help":
switch argValue {
case "markdown", "md":
cd.showHelp = Markdown
default:
cd.showHelp = PluginHelp
}
return nil, false, nil
case "ok":
cond, err2 := NewCondition(argValue, &cd.attributes)
if err2 != nil {
return nil, false, err2
}
cd.okThreshold = append(cd.okThreshold, cond)
case "warn+", "warning+":
warn, err2 := cd.appendDefaultThreshold(keyword, argValue, defaultWarning, cd.warnThreshold)
if err2 != nil {
return nil, false, err2
}
cd.warnThreshold = warn
case "warn", "warning":
cond, err2 := NewCondition(argValue, &cd.attributes)
if err2 != nil {
return nil, false, err2
}
cd.warnThreshold = append(cd.warnThreshold, cond)
case "crit+", "critical+":
crit, err2 := cd.appendDefaultThreshold(keyword, argValue, defaultCritical, cd.critThreshold)
if err2 != nil {
return nil, false, err2
}
cd.critThreshold = crit
case "crit", "critical":
cond, err2 := NewCondition(argValue, &cd.attributes)
if err2 != nil {
return nil, false, err2
}
cd.critThreshold = append(cd.critThreshold, cond)
case "filter+":
applyDefaultFilter = false
filter, err2 := cd.appendDefaultThreshold(keyword, argValue, cd.defaultFilter, cd.filter)
if err2 != nil {
return nil, false, err2
}
cd.filter = filter
case "filter":
applyDefaultFilter = false
cond, err2 := NewCondition(argValue, &cd.attributes)
if err2 != nil {
return nil, false, err2
}
cd.filter = append(cd.filter, cond)
case "debug":
// not in use
case "detail-syntax":
cd.detailSyntax = argValue
case "list-combine":
cd.listCombine = argValue
cd.listCombineSet = true
case "top-syntax":
cd.topSyntax = argValue
topSupplied = true
case "ok-syntax":
cd.okSyntax = argValue
okSupplied = true
case "empty-syntax":
cd.emptySyntax = argValue
case "empty-state":
cd.emptyState = cd.parseStateString(argValue)
cd.emptyStateSet = true
case "show-all", "ShowAll":
if argValue == "" {
cd.showAll = true
} else {
showAll, err2 := convert.BoolE(argValue)
if err2 != nil {
return nil, false, fmt.Errorf("parseBool %s: %s", argValue, err2.Error())
}
cd.showAll = showAll
}
case "timezone":
timeZone, err2 := time.LoadLocation(argValue)
if err2 != nil {
return nil, false, fmt.Errorf("couldn't find timezone: %s", argValue)
}
cd.timezone = timeZone
case "timeout":
timeout, err2 := convert.Float64E(argValue)
if err2 != nil {
return nil, false, fmt.Errorf("timeout parse error: %s", err2.Error())
}
cd.timeout = timeout
case "perf-config":
perf, err2 := NewPerfConfig(argValue)
if err2 != nil {
return nil, false, err2
}
cd.perfConfig = append(cd.perfConfig, perf...)
case "perf-syntax":
cd.perfSyntax = argValue
case "output":
switch argValue {
case "inventory_json":
cd.output = OutputInventory
default:
return nil, false, fmt.Errorf("unknown output mode: %s (valid values are: inventory_json)", argValue)
}
default:
parsed, err2 := cd.parseAnyArg(argExpr, keyword, argValue)
switch {
case err2 != nil:
return nil, false, err2
case parsed:
// ok
case cd.argsPassthrough:
argList = append(argList, Argument{key: keyword, value: argValue})
case keyword == "-h", keyword == "--help":
cd.showHelp = PluginHelp
case keyword == "-a":
// ignore -a for legacy compatibility
default:
return nil, false, fmt.Errorf("unknown argument: %s", keyword)
}
}
}
if topSupplied && !okSupplied {
cd.okSyntax = cd.topSyntax
}
return argList, applyDefaultFilter, nil
}
func (cd *CheckData) preParseArgs(args []string) (sanitized []Argument, defaultWarning, defaultCritical string, hasArgsFilter bool, err error) {
sanitized = make([]Argument, 0)
numArgs := len(args)
applyDefaultFilter := true
defaultWarning = cd.defaultWarning
defaultCritical = cd.defaultCritical
for idx := 0; idx < numArgs; idx++ {
argExpr := cd.removeQuotes(args[idx])
split := strings.SplitN(argExpr, "=", 2)
keyword := cd.removeQuotes(split[0])
argValue, newIdx, err2 := cd.fetchNextArg(args, split, keyword, idx, numArgs)
if err2 != nil {
return nil, "", "", false, err2
}
idx = newIdx
argValue = cd.removeQuotes(argValue)
var chkArg *CheckArgument
if a, ok := cd.args[keyword]; ok && a.isFilter {
chkArg = &a
}
if a, ok := cd.extraArgs[keyword]; ok && a.isFilter {
chkArg = &a
}
if chkArg != nil {
applyDefaultFilter = false
cd.hasArgsFilter = true
if chkArg.defaultWarning != "" {
defaultWarning = chkArg.defaultWarning
}
if chkArg.defaultCritical != "" {
defaultCritical = chkArg.defaultCritical
}
}
sanitized = append(sanitized, Argument{key: keyword, value: argValue, raw: argExpr})
}
return sanitized, defaultWarning, defaultCritical, applyDefaultFilter, nil
}
func (cd *CheckData) fetchNextArg(args, split []string, keyword string, idx, numArgs int) (argVal string, newIdx int, err error) {
if len(split) == 2 {
return split[1], idx, nil
}
arg, ok := cd.args[keyword]
if !ok {
arg, ok = cd.extraArgs[keyword]
if !ok {
return "", idx, nil
}
}
_, ok = arg.value.(*bool)
if ok {
return "", idx, nil
}
// known arg and not a bool value -> consume next value
idx++
if idx >= numArgs {
return "", idx, fmt.Errorf("argument value expected for %s", keyword)
}
return args[idx], idx, nil
}
// parseAnyArg parses args into the args map with custom arguments
func (cd *CheckData) parseAnyArg(argExpr, keyword, argValue string) (bool, error) {
arg, ok := cd.args[keyword]
if !ok {
arg, ok = cd.extraArgs[keyword]
if !ok {
return false, nil
}
}
switch argRef := arg.value.(type) {
case *[]string:
if _, ok := cd.hasArgsSupplied[keyword]; !ok {
// first time this arg occurs, empty default lists
empty := make([]string, 0)
*argRef = empty
}
*argRef = append(*argRef, argValue)
case *CommaStringList:
if _, ok := cd.hasArgsSupplied[keyword]; !ok {
// first time this arg occurs, empty default lists
empty := make([]string, 0)
*argRef = empty
}
*argRef = append(*argRef, strings.Split(argValue, ",")...)
case *string:
*argRef = argValue
case *float64:
f, err := strconv.ParseFloat(argValue, 64)
if err != nil {
return true, fmt.Errorf("parseFloat %s: %s", argExpr, err.Error())
}
*argRef = f
case *int64:
i, err := strconv.ParseInt(argValue, 10, 64)
if err != nil {
return true, fmt.Errorf("parseInt %s: %s", argExpr, err.Error())
}
*argRef = i
case *int:
i, err := strconv.ParseInt(argValue, 10, 32)
if err != nil {
return true, fmt.Errorf("parseInt %s: %s", argExpr, err.Error())
}
*argRef = int(i)
case *bool:
if argValue == "" {
b := true
*argRef = b
} else {
b, err := convert.BoolE(argValue)
if err != nil {
return true, fmt.Errorf("parseBool %s: %s", argValue, err.Error())
}
*argRef = b
}
default:
log.Errorf("unsupported args type: %T in %s", argRef, argExpr)
}
cd.hasArgsSupplied[keyword] = true
return true, nil
}
// removeQuotes remove single/double quotes around string
func (cd *CheckData) removeQuotes(str string) string {
str = strings.TrimSpace(str)
switch {
case strings.HasPrefix(str, "'") && strings.HasSuffix(str, "'"):
str = strings.TrimPrefix(str, "'")
str = strings.TrimSuffix(str, "'")
return str
case strings.HasPrefix(str, `"`) && strings.HasSuffix(str, `"`):
str = strings.TrimPrefix(str, `"`)
str = strings.TrimSuffix(str, `"`)
return str
}
return str
}
// setFallbacks sets default filter/warn/crit thresholds unless already set.
func (cd *CheckData) setFallbacks(applyDefaultFilter bool, defaultWarning, defaultCritical string) error {
if applyDefaultFilter && cd.defaultFilter != "" {
cond, err := NewCondition(cd.defaultFilter, &cd.attributes)
if err != nil {
return err
}
cd.filter = append(cd.filter, cond)
}
// default warning/critical overridden from check arguments, ex. check_service
if defaultWarning != "" {
cd.defaultWarning = defaultWarning
}
if defaultCritical != "" {
cd.defaultCritical = defaultCritical
}
cd.warnThreshold = cd.applyDefaultThreshold(cd.defaultWarning, cd.warnThreshold)
cd.critThreshold = cd.applyDefaultThreshold(cd.defaultCritical, cd.critThreshold)
if cd.timeout == 0 {
cd.timeout = DefaultCheckTimeout.Seconds()