Debian Codegraph @

response.go

raw
1 //Package monitoringplugin provides types for writing monitoring check plugins for nagios, icinga2, zabbix, etc
2 package monitoringplugin
3
4 import (
5 "bytes"
6 "fmt"
7 "github.com/pkg/errors"
8 "os"
9 "sort"
10 "strings"
11 )
12
13 const (
14 // OK check plugin status = OK
15 OK = 0
16 // WARNING check plugin status = WARNING
17 WARNING = 1
18 // CRITICAL check plugin status = CRITICAL
19 CRITICAL = 2
20 // UNKNOWN check plugin status = UNKNOWN
21 UNKNOWN = 3
22 )
23
24 // InvalidCharacterBehavior specifies how the monitoringplugin should behave if an invalid character is found in the
25 // output message. Does not affect invalid characters in the performance data.
26 type InvalidCharacterBehavior int
27
28 const (
29 // InvalidCharacterRemove removes invalid character in the output message.
30 InvalidCharacterRemove InvalidCharacterBehavior = iota + 1
31 // InvalidCharacterReplace replaces invalid character in the output message with another character.
32 // Only valid if replace character is set
33 InvalidCharacterReplace
34 // InvalidCharacterRemoveMessage removes the message with the invalid character.
35 // StatusCode of the message will still be set.
36 InvalidCharacterRemoveMessage
37 // InvalidCharacterReplaceWithError replaces the whole message with an error message if an invalid character is found.
38 InvalidCharacterReplaceWithError
39 // InvalidCharacterReplaceWithErrorAndSetUNKNOWN replaces the whole message with an error message if an invalid character is found.
40 // Also sets the status code to UNKNOWN.
41 InvalidCharacterReplaceWithErrorAndSetUNKNOWN
42 )
43
44 // OutputMessage represents a message of the response. It contains a message and a status code.
45 type OutputMessage struct {
46 Status int `yaml:"status" json:"status" xml:"status"`
47 Message string `yaml:"message" json:"message" xml:"message"`
48 }
49
50 // Response is the main type that is responsible for the check plugin Response.
51 // It stores the current status code, output messages, performance data and the output message delimiter.
52 type Response struct {
53 statusCode int
54 defaultOkMessage string
55 outputMessages []OutputMessage
56 performanceData performanceData
57 outputDelimiter string
58 performanceDataJSONLabel bool
59 printPerformanceData bool
60 sortOutputMessagesByStatus bool
61 invalidCharacterBehaviour InvalidCharacterBehavior
62 invalidCharacterReplaceChar string
63 }
64
65 /*
66 NewResponse creates a new Response and sets the default OK message to the given string.
67 The default OK message will be displayed together with the other output messages, but only
68 if the status is still OK when the check exits.
69 */
70 func NewResponse(defaultOkMessage string) *Response {
71 response := &Response{
72 statusCode: OK,
73 defaultOkMessage: defaultOkMessage,
74 outputDelimiter: "\n",
75 printPerformanceData: true,
76 sortOutputMessagesByStatus: true,
77 invalidCharacterBehaviour: InvalidCharacterRemove,
78 }
79 response.performanceData = make(performanceData)
80 return response
81 }
82
83 /*
84 AddPerformanceDataPoint adds a PerformanceDataPoint to the performanceData map,
85 using performanceData.add(*PerformanceDataPoint).
86 Usage:
87 err := Response.AddPerformanceDataPoint(NewPerformanceDataPoint("temperature", 32, "°C").SetWarn(35).SetCrit(40))
88 if err != nil {
89 ...
90 }
91 */
92 func (r *Response) AddPerformanceDataPoint(point *PerformanceDataPoint) error {
93 err := r.performanceData.add(point)
94 if err != nil {
95 return errors.Wrap(err, "failed to add performance data point")
96 }
97
98 if !point.Thresholds.IsEmpty() {
99 name := point.Metric
100 if point.Label != "" {
101 name += " (" + point.Label + ")"
102 }
103 err = r.CheckThresholds(point.Thresholds, point.Value, name)
104 if err != nil {
105 return errors.Wrap(err, "failed to check thresholds")
106 }
107 }
108
109 return nil
110 }
111
112 /*
113 UpdateStatus updates the exit status of the Response and adds a statusMessage to the outputMessages that
114 will be displayed when the check exits.
115 See updateStatusCode(int) for a detailed description of the algorithm that is used to update the status code.
116 */
117 func (r *Response) UpdateStatus(statusCode int, statusMessage string) {
118 r.updateStatusCode(statusCode)
119 if statusMessage != "" {
120 r.outputMessages = append(r.outputMessages, OutputMessage{statusCode, statusMessage})
121 }
122 }
123
124 // GetStatusCode returns the current status code.
125 func (r *Response) GetStatusCode() int {
126 return r.statusCode
127 }
128
129 // SetPerformanceDataJSONLabel updates the JSON metric.
130 func (r *Response) SetPerformanceDataJSONLabel(jsonLabel bool) {
131 r.performanceDataJSONLabel = jsonLabel
132 }
133
134 // SetInvalidCharacterBehavior sets the desired behavior if an invalid character is found in a message.
135 // Default is InvalidCharacterRemove.
136 // replaceCharacter is only necessary if InvalidCharacterReplace is set.
137 func (r *Response) SetInvalidCharacterBehavior(behavior InvalidCharacterBehavior, replaceCharacter string) error {
138 switch behavior {
139 case InvalidCharacterReplace:
140 if replaceCharacter == "" {
141 return errors.New("empty replace character set")
142 }
143 r.invalidCharacterReplaceChar = replaceCharacter
144 fallthrough
145 case InvalidCharacterRemove, InvalidCharacterRemoveMessage, InvalidCharacterReplaceWithError, InvalidCharacterReplaceWithErrorAndSetUNKNOWN:
146 r.invalidCharacterBehaviour = behavior
147 default:
148 return errors.New("unknown behavior")
149 }
150 return nil
151 }
152
153 /*
154 This function updates the statusCode of the Response. The status code is mapped to a state like this:
155 0 = OK
156 1 = WARNING
157 2 = CRITICAL
158 3 = UNKNOWN
159 Everything else is also mapped to UNKNOWN.
160
161 UpdateStatus uses the following algorithm to update the exit status:
162 CRITICAL > UNKNOWN > WARNING > OK
163 Everything "left" from the current status code is seen as worse than the current one.
164 If the function wants to set a status code, it will only update it if the new status code is "left" of the current one.
165 Example:
166 //current status code = 1
167 Response.updateStatusCode(0) //nothing changes
168 Response.updateStatusCode(2) //status code changes to CRITICAL (=2)
169
170 //now current status code = 2
171 Response.updateStatusCode(3) //nothing changes, because CRITICAL is worse than UNKNOWN
172
173 */
174 func (r *Response) updateStatusCode(statusCode int) {
175 if r.statusCode == CRITICAL { //critical is the worst status code; if its critical, do not change anything
176 return
177 }
178 if statusCode == CRITICAL {
179 r.statusCode = statusCode
180 return
181 }
182 if statusCode < OK || statusCode > UNKNOWN {
183 statusCode = UNKNOWN
184 }
185 if statusCode > r.statusCode {
186 r.statusCode = statusCode
187 }
188 }
189
190 // UpdateStatusIf calls UpdateStatus(statusCode, statusMessage) if the given condition is true.
191 func (r *Response) UpdateStatusIf(condition bool, statusCode int, statusMessage string) bool {
192 if condition {
193 r.UpdateStatus(statusCode, statusMessage)
194 }
195 return condition
196 }
197
198 // UpdateStatusIfNot calls UpdateStatus(statusCode, statusMessage) if the given condition is false.
199 func (r *Response) UpdateStatusIfNot(condition bool, statusCode int, statusMessage string) bool {
200 if !condition {
201 r.UpdateStatus(statusCode, statusMessage)
202 }
203 return !condition
204 }
205
206 // UpdateStatusOnError calls UpdateStatus(statusCode, statusMessage) if the given error is not nil.
207 func (r *Response) UpdateStatusOnError(err error, statusCode int, statusMessage string, includeErrorMessage bool) bool {
208 x := err != nil
209 if x {
210 msg := statusMessage
211 if includeErrorMessage {
212 if msg != "" {
213 msg = fmt.Sprintf("%s (error: %s)", msg, err)
214 } else {
215 msg = err.Error()
216 }
217 }
218 r.UpdateStatus(statusCode, msg)
219 }
220 return x
221 }
222
223 /*
224 SetOutputDelimiter is used to set the delimiter that is used to separate the outputMessages that will be displayed when
225 the check plugin exits. The default value is a linebreak (\n)
226 It can be set to any string.
227 Example:
228 Response.SetOutputDelimiter(" / ")
229 //this results in the output having the following format:
230 //OK: defaultOkMessage / outputMessage1 / outputMessage2 / outputMessage3 | performanceData
231 */
232 func (r *Response) SetOutputDelimiter(delimiter string) {
233 r.outputDelimiter = delimiter
234 }
235
236 // OutputDelimiterMultiline sets the outputDelimiter to "\n". (See Response.SetOutputDelimiter(string))
237 func (r *Response) OutputDelimiterMultiline() {
238 r.SetOutputDelimiter("\n")
239 }
240
241 // PrintPerformanceData activates or deactivates printing performance data
242 func (r *Response) PrintPerformanceData(b bool) {
243 r.printPerformanceData = b
244 }
245
246 // SortOutputMessagesByStatus sorts the output messages according to their status.
247 func (r *Response) SortOutputMessagesByStatus(b bool) {
248 r.sortOutputMessagesByStatus = b
249 }
250
251 // This function returns the output that will be returned by the check plugin as a string.
252 func (r *Response) outputString() string {
253 return string(r.output())
254 }
255
256 // This function returns the output that will be returned by the check plugin.
257 func (r *Response) output() []byte {
258 var buffer bytes.Buffer
259 buffer.WriteString(StatusCode2Text(r.statusCode))
260 buffer.WriteString(": ")
261 if r.statusCode == OK {
262 buffer.WriteString(r.defaultOkMessage)
263 if len(r.outputMessages) > 0 {
264 buffer.WriteString(r.outputDelimiter)
265 }
266 }
267
268 for c, x := range r.outputMessages {
269 if c != 0 {
270 buffer.WriteString(r.outputDelimiter)
271 }
272 buffer.WriteString(x.Message)
273 }
274
275 if r.printPerformanceData {
276 firstPoint := true
277 for _, perfDataPoint := range r.performanceData {
278 if firstPoint {
279 buffer.WriteString(" | ")
280 firstPoint = false
281 } else {
282 buffer.WriteByte(' ')
283 }
284 buffer.Write(perfDataPoint.output(r.performanceDataJSONLabel))
285 }
286 }
287 return buffer.Bytes()
288 }
289
290 func (r *Response) validate() {
291 if strings.Contains(r.defaultOkMessage, "|") {
292 switch r.invalidCharacterBehaviour {
293 case InvalidCharacterReplace:
294 r.defaultOkMessage = strings.ReplaceAll(r.defaultOkMessage, "|", r.invalidCharacterReplaceChar)
295 case InvalidCharacterRemoveMessage:
296 r.defaultOkMessage = ""
297 case InvalidCharacterReplaceWithError:
298 r.defaultOkMessage = "default output message contains invalid character"
299 case InvalidCharacterReplaceWithErrorAndSetUNKNOWN:
300 r.statusCode = UNKNOWN
301 r.outputMessages = []OutputMessage{{
302 Status: UNKNOWN,
303 Message: "default output message contains invalid character",
304 }}
305 r.outputMessages = nil
306 return
307 default: // InvalidCharacterRemove
308 r.defaultOkMessage = strings.ReplaceAll(r.defaultOkMessage, "|", "")
309 }
310 }
311 r.validateMessages()
312 if r.sortOutputMessagesByStatus {
313 r.sortMessagesByStatus()
314 }
315 }
316
317 func (r *Response) validateMessages() {
318 var messages []OutputMessage
319 out:
320 for _, message := range r.outputMessages {
321 if !strings.Contains(message.Message, "|") {
322 messages = append(messages, message)
323 } else {
324 switch r.invalidCharacterBehaviour {
325 case InvalidCharacterReplace:
326 newMessage := strings.ReplaceAll(message.Message, "|", r.invalidCharacterReplaceChar)
327 if newMessage != "" {
328 messages = append(messages, OutputMessage{
329 Status: message.Status,
330 Message: newMessage,
331 })
332 }
333 case InvalidCharacterRemoveMessage:
334 // done
335 case InvalidCharacterReplaceWithErrorAndSetUNKNOWN:
336 r.statusCode = UNKNOWN
337 message.Status = UNKNOWN
338 fallthrough
339 case InvalidCharacterReplaceWithError:
340 messages = []OutputMessage{{
341 Status: message.Status,
342 Message: "output message contains invalid character",
343 }}
344 break out
345 default: // InvalidCharacterRemove
346 newMessage := strings.ReplaceAll(message.Message, "|", "")
347 if newMessage != "" {
348 messages = append(messages, OutputMessage{
349 Status: message.Status,
350 Message: newMessage,
351 })
352 }
353 }
354 }
355 }
356 r.outputMessages = messages
357 }
358
359 func (r *Response) sortMessagesByStatus() {
360 sort.Slice(r.outputMessages, func(i, j int) bool {
361 if r.outputMessages[i].Status == CRITICAL {
362 return true
363 }
364 return r.outputMessages[i].Status > r.outputMessages[j].Status
365 })
366 }
367
368 /*
369 OutputAndExit generates the output string and prints it to stdout.
370 After that the check plugin exits with the current exit code.
371 Example:
372 Response := NewResponse("everything checked!")
373 defer Response.OutputAndExit()
374
375 //check plugin logic...
376 */
377 func (r *Response) OutputAndExit() {
378 r.validate()
379 fmt.Println(r.outputString())
380 os.Exit(r.statusCode)
381 }
382
383 // ResponseInfo has all available information for a response. It also contains the RawOutput.
384 type ResponseInfo struct {
385 StatusCode int `yaml:"status_code" json:"status_code" xml:"status_code"`
386 PerformanceData []PerformanceDataPoint `yaml:"performance_data" json:"performance_data" xml:"performance_data"`
387 RawOutput string `yaml:"raw_output" json:"raw_output" xml:"raw_output"`
388 Messages []OutputMessage `yaml:"messages" json:"messages" xml:"messages"`
389 }
390
391 // GetInfo returns all information for a response.
392 func (r *Response) GetInfo() ResponseInfo {
393 r.validate()
394 return ResponseInfo{
395 RawOutput: r.outputString(),
396 StatusCode: r.statusCode,
397 PerformanceData: r.performanceData.getInfo(),
398 Messages: r.outputMessages,
399 }
400 }
401
402 // CheckThresholds checks if the value exceeds the given thresholds and updates the response
403 func (r *Response) CheckThresholds(thresholds Thresholds, value interface{}, name string) error {
404 res, err := thresholds.CheckValue(value)
405 if err != nil {
406 return errors.Wrap(err, "failed to check value against threshold")
407 }
408 if res != OK {
409 r.UpdateStatus(res, name+" is outside of "+StatusCode2Text(res)+" threshold")
410 }
411 return nil
412 }
413
414 /*
415 String2StatusCode returns the status code for a string.
416 OK -> 1, WARNING -> 2, CRITICAL -> 3, UNKNOWN and everything else -> 4 (case insensitive)
417 */
418 func String2StatusCode(s string) int {
419 switch {
420 case strings.EqualFold("OK", s):
421 return OK
422 case strings.EqualFold("WARNING", s):
423 return WARNING
424 case strings.EqualFold("CRITICAL", s):
425 return CRITICAL
426 default:
427 return UNKNOWN
428 }
429 }
430
431 // StatusCode2Text is used to map the status code to a string.
432 func StatusCode2Text(statusCode int) string {
433 switch {
434 case statusCode == OK:
435 return "OK"
436 case statusCode == WARNING:
437 return "WARNING"
438 case statusCode == CRITICAL:
439 return "CRITICAL"
440 default:
441 return "UNKNOWN"
442 }
443 }