-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfileContent.go
More file actions
285 lines (230 loc) · 7.96 KB
/
Copy pathfileContent.go
File metadata and controls
285 lines (230 loc) · 7.96 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
package cmd
import (
"bufio"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"strconv"
sbRegex "github.com/NETWAYS/check_system_basics/internal/common/regexp"
fileContent "github.com/NETWAYS/check_system_basics/internal/files"
"github.com/NETWAYS/go-check"
"github.com/NETWAYS/go-check/result"
"github.com/spf13/cobra"
)
var FileContentConfig fileContent.FileContentconfig
var fileContentCmd = &cobra.Command{
Use: "fileContent",
Short: "Submodule to test for different properties on file content ",
Example: ``,
Run: func(_ *cobra.Command, _ []string) {
if len(FileContentConfig.Paths) == 0 {
check.Exit(check.Unknown, "At least one path (--paths) must be selected")
}
// Input sanity check
for _, inputPath := range FileContentConfig.Paths {
if !path.IsAbs(inputPath) {
check.Exit(check.Unknown, fmt.Sprintf("Path %s is not an absolute path, but must be one", inputPath))
}
}
overall := result.Overall{}
// find files
for _, inputPath := range FileContentConfig.Paths {
sc, err := PathEvaluation(inputPath, FileContentConfig)
if err != nil {
check.ExitError(err)
}
overall.AddSubcheck(sc)
}
check.Exit(overall.GetStatus(), overall.GetOutput())
},
}
func PathEvaluation(path string, config fileContent.FileContentconfig) (*result.PartialResult, error) {
fileInfo, err := os.Stat(path)
if err != nil {
return nil, err
}
// nolint: nestif
if fileInfo.IsDir() {
// Input path is a directory
// apply conditions for all files inside
partialDir := result.NewPartialResult()
partialDir.SetDefaultState(check.OK)
partialDir.SetOutput(path)
dirs, err := os.ReadDir(path)
if err != nil {
return nil, err
}
for _, dirEntry := range dirs {
if dirEntry.IsDir() {
if config.Recursive {
// TODO head down
ssc, err := PathEvaluation(filepath.Join(path, dirEntry.Name()), config)
if err != nil {
return nil, err
}
partialDir.AddSubcheck(ssc)
}
// non recursive, ignore the dir
continue
}
// it's a file!
fileSC, err := EvaluateFile(filepath.Join(path, dirEntry.Name()), config)
if err != nil {
return nil, err
}
partialDir.AddSubcheck(fileSC)
}
return partialDir, nil
}
// Input path is a file
// apply conditions directly
return EvaluateFile(path, config)
}
// EvaluateFile receives a path and some evaluation parameters
// and applies the conditions to the file content
// nolint: gocognit,gocyclo
func EvaluateFile(path string, config fileContent.FileContentconfig) (*result.PartialResult, error) { // nolint: gocognit
evaluationResult := result.NewPartialResult()
evaluationResult.SetDefaultState(check.OK)
baseName := filepath.Base(path)
evaluationResult.SetOutput(baseName)
// Evaluation
// -- Pattern matching in file
// nolint: nestif
if (len(config.OKPatterns) != 0) || (len(config.WarningPatterns) != 0) || (len(config.CriticalPatterns) != 0) || config.MetricPattern.IsSet {
// Pattern matching priority:
// if Critical > Warning > OK
// start with critical and first match wins
foundOKPattern := false
foundWarningPattern := false
foundCriticalPattern := false
foundMetric := false
var metric float64
var patternFound sbRegex.SBRegex
fileDesc, err := os.Open(path)
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(fileDesc)
for scanner.Scan() {
if !foundCriticalPattern {
for _, critPattern := range config.CriticalPatterns {
if critPattern.Regex.MatchString(scanner.Text()) {
foundCriticalPattern = true
patternFound = critPattern
break
}
}
}
if !foundWarningPattern {
for _, warnPattern := range config.WarningPatterns {
if warnPattern.Regex.MatchString(scanner.Text()) {
foundWarningPattern = true
patternFound = warnPattern
break
}
}
}
if !foundOKPattern {
for _, okPattern := range config.OKPatterns {
if okPattern.Regex.MatchString(scanner.Text()) {
foundOKPattern = true
patternFound = okPattern
break
}
}
}
if config.MetricPattern.IsSet {
if config.MetricPattern.Regex.MatchString(scanner.Text()) {
foundMetric = true
matchSlice := config.MetricPattern.Regex.FindStringSubmatch(scanner.Text())
if matchSlice == nil {
check.ExitError(errors.New("metrix regex submatch failed somehow"))
}
metric, err = strconv.ParseFloat(matchSlice[1], 64)
if err != nil {
check.ExitError(err)
}
}
}
if (config.MetricPattern.IsSet || foundMetric) &&
(len(config.CriticalPatterns) == 0 || foundCriticalPattern) &&
(len(config.WarningPatterns) == 0 || foundWarningPattern) &&
(len(config.OKPatterns) == 0 || foundOKPattern) {
// Abort if we are done
break
}
}
// Scanner failure?
err = scanner.Err()
if err != nil {
return nil, err
}
scPattern := result.NewPartialResult()
scPattern.SetDefaultState(config.NotFoundStatus.Status)
if !foundCriticalPattern && !foundWarningPattern && !foundOKPattern {
scPattern.SetState(config.NotFoundStatus.Status)
scPattern.SetOutput("Regex pattern did not match in file")
} else {
// ok we found something
scPattern.SetOutput("Found pattern \"" + patternFound.String() + "\"")
// nolint: gocritic
if foundCriticalPattern {
scPattern.SetState(check.Critical)
} else if foundWarningPattern {
scPattern.SetState(check.Warning)
} else {
scPattern.SetState(check.OK)
}
}
evaluationResult.AddSubcheck(scPattern)
if config.MetricPattern.IsSet {
// Expected a metric match
scMetric := result.NewPartialResult()
if !foundMetric {
scMetric.SetState(config.MetricNotFoundStatus.Status)
scMetric.SetOutput("Metric not found")
} else {
scMetric.SetState(check.OK)
scMetric.SetOutput(fmt.Sprintf("%s: %g", config.MetricLabel, metric))
pdMetrcis := check.Perfdata{
Value: metric,
Label: config.MetricLabel,
}
if config.MetricThresholds.Warn.IsSet {
pdMetrcis.Warn = &config.MetricThresholds.Warn.Th
}
if config.MetricThresholds.Warn.Th.DoesViolate(metric) {
scMetric.SetState(check.Warning)
}
if config.MetricThresholds.Crit.IsSet {
pdMetrcis.Crit = &config.MetricThresholds.Crit.Th
}
if config.MetricThresholds.Crit.Th.DoesViolate(metric) {
scMetric.SetState(check.Critical)
}
scMetric.AddPerfdata(&pdMetrcis)
}
evaluationResult.AddSubcheck(scMetric)
}
}
return evaluationResult, nil
}
func init() {
rootCmd.AddCommand(fileContentCmd)
fileContentCmd.DisableFlagsInUseLine = true
fileContentFS := fileContentCmd.Flags()
fileContentFS.StringArrayVar(&FileContentConfig.Paths, "paths", []string{}, "File paths to evaluate")
fileContentFS.BoolVar(&FileContentConfig.Recursive, "recursive", false, "Recursively test all files in \"paths\"")
fileContentFS.Var(&FileContentConfig.OKPatterns, "ok-pattern", "Regex pattern in file which are OK")
fileContentFS.Var(&FileContentConfig.WarningPatterns, "warning-pattern", "Regex pattern in file which cause a WARNING")
fileContentFS.Var(&FileContentConfig.CriticalPatterns, "critical-pattern", "Regex pattern in file which cause a CRITICAL")
fileContentFS.Var(&FileContentConfig.NotFoundStatus, "not-found-status", "Exit status if none of the patterns apply (OK (0), warning (1), critical (2), Uknown (3)) (default: OK)")
fileContentFS.Var(&FileContentConfig.MetricPattern, "metric-pattern", "Regex pattern to find numerical values in the file")
fileContentFS.StringVar(&FileContentConfig.MetricLabel, "metric-label", "metric", "(Perfdata) label for matched metrics")
fileContentFS.Var(&FileContentConfig.MetricThresholds.Warn, "metric-warning", "Warning threshold for the matched metric")
fileContentFS.Var(&FileContentConfig.MetricThresholds.Crit, "metric-critical", "Critical threshold for the matched metric")
fileContentFS.Var(&FileContentConfig.MetricNotFoundStatus, "metric-not-found-status", "Exit status if the metric patterns were not found. (OK (0), warning (1), critical (2), Uknown (3)) (default: OK)")
}