Documentation ¶
Overview ¶
Package nagios provides common types, constants, package-level variables, performance data and methods for use with Nagios plugins.
OVERVIEW ¶
This package provides common functionality for use by plugins used by Nagios (and similar) monitoring systems. The goal is to reduce code duplication for monitoring plugins written in the Go programming language.
PROJECT HOME ¶
See our GitHub repo (https://github.com/atc0005/go-nagios) for the latest code, to file an issue or submit improvements for review and potential inclusion into the project.
FEATURES ¶
- Nagios state labels (e.g., StateOKLabel), state exit codes (e.g., StateOKExitCode)
- Nagios ServiceState type useful in client code as a way to map internal check results to a Nagios service state value
- Nagios CheckOutputEOL constant useful for consistent newline display in results displayed in web UI, email notifications
- Plugin type with ReturnCheckResults method used to process and return all applicable check results to Nagios for further processing/display
- Optional support for collecting/emitting performance data generated by plugins (default time metric emitted if using constructor)
- Supports "branding" callback function to display application name, version, or other information as a "trailer" for check results provided to Nagios
- Panics from client code are captured and reported
- Support for collecting multiple errors from client code
- Support for explicitly omitting Errors section in LongServiceOutput (automatically omitted if none were recorded)
- Support for explicitly omitting Thresholds section in LongServiceOutput (automatically omitted if none were recorded)
- Automatically omit LongServiceOutput section if not specify by client code
- Support for overriding text used for section headers/labels
HOW TO USE ¶
- See the code documentation here for specifics
- See the README for this project for examples
Example (AddEncodedPayload) ¶
Example_addEncodedPayload demonstrates adding an encoded payload to plugin output (e.g., for potential later retrieval via the monitor systems' API).
package main import ( "log" "github.com/atc0005/go-nagios" ) // Ignore this. This is just to satisfy the "whole file" example requirements // per https://go.dev/blog/examples. var _ = "https://github.com/atc0005/go-nagios" // Example_addEncodedPayload demonstrates adding an encoded payload to plugin // output (e.g., for potential later retrieval via the monitor systems' API). func main() { // First, create an instance of the Plugin type. By default this value is // configured to indicate a successful execution. This should be // overridden by client code to indicate the final plugin state to Nagios // when the plugin exits. var plugin = nagios.NewPlugin() // Second, immediately defer ReturnCheckResults() so that it runs as the // last step in your client code. If you do not defer ReturnCheckResults() // immediately any other deferred functions in your client code will not // run. // // Avoid calling os.Exit() directly from your code. If you do, this // library is unable to function properly; this library expects that it // will handle calling os.Exit() with the required exit code (and // specifically formatted output). // // For handling error cases, the approach is roughly the same, only you // call return explicitly to end execution of the client code and allow // deferred functions to run. defer plugin.ReturnCheckResults() // more stuff here involving performing the actual service check // This simple JSON structure represents a more detailed blob of data that // might need post-processing once retrieved from the monitoring system's // API, etc. // // Imagine this is something like a full certificate chain or a system's // state and not easily represented by performance data metrics (e.g., // best represented in a structured format once later extracted and // decoded). sampleComplexData := `{"Age":17,"Interests":["books","games", "Crystal Stix"]}` if _, err := plugin.AddPayloadString(sampleComplexData); err != nil { log.Printf("failed to add encoded payload: %v", err) plugin.Errors = append(plugin.Errors, err) return } //nolint:goconst plugin.ServiceOutput = "one-line summary of plugin results " //nolint:goconst plugin.LongServiceOutput = "more detailed output from plugin here" // more stuff here involving wrapping up the service check }
Output:
Example (BasicPluginStructure) ¶
ExampleBasicPluginStructure demonstrates the basic structure for a monitoring plugin that uses this package.
package main import ( "github.com/atc0005/go-nagios" ) // Ignore this. This is just to satisfy the "whole file" example requirements // per https://go.dev/blog/examples. var _ = "https://github.com/atc0005/go-nagios" // ExampleBasicPluginStructure demonstrates the basic structure for a // monitoring plugin that uses this package. func main() { // First, create an instance of the Plugin type. By default this value is // configured to indicate a successful execution. This should be // overridden by client code to indicate the final plugin state to Nagios // when the plugin exits. var plugin = nagios.NewPlugin() // Second, immediately defer ReturnCheckResults() so that it runs as the // last step in your client code. If you do not defer ReturnCheckResults() // immediately any other deferred functions in your client code will not // run. // // Avoid calling os.Exit() directly from your code. If you do, this // library is unable to function properly; this library expects that it // will handle calling os.Exit() with the required exit code (and // specifically formatted output). // // For handling error cases, the approach is roughly the same, only you // call return explicitly to end execution of the client code and allow // deferred functions to run. defer plugin.ReturnCheckResults() // more stuff here plugin.ServiceOutput = "one-line summary of plugin results " plugin.LongServiceOutput = "more detailed output from plugin here" }
Output:
Example (EmitPerformanceData) ¶
ExampleEmitPerformanceData demonstrates providing multiple plugin performance data values explicitly.
NOTE: While this example illustrates providing a time metric, this metric is provided for you if using the nagios.NewPlugin constructor. If specifying this value ourselves, *our* value takes precedence and the default value is ignored.
package main import ( "fmt" "log" "time" "github.com/atc0005/go-nagios" ) // Ignore this. This is just to satisfy the "whole file" example requirements // per https://go.dev/blog/examples. var _ = "https://github.com/atc0005/go-nagios" // ExampleEmitPerformanceData demonstrates providing multiple plugin // performance data values explicitly. // // NOTE: While this example illustrates providing a time metric, this metric // is provided for you if using the nagios.NewPlugin constructor. If // specifying this value ourselves, *our* value takes precedence and the // default value is ignored. func main() { // Start the timer. We'll use this to emit the plugin runtime as a // performance data metric. // // NOTE: While this example illustrates providing a time metric, this // metric is provided for you if using the nagios.NewPlugin constructor. // If specifying this value ourselves, *our* value takes precedence and // the default value is ignored. pluginStart := time.Now() // First, create an instance of the Plugin type. Here we're opting to // manually construct the Plugin value instead of using the constructor // (mostly for contrast). // // We set the ExitStatusCode value to reflect a successful plugin // execution. If we do not alter the exit status code later this is what // will be reported to Nagios when the plugin exits. var plugin = nagios.Plugin{ LastError: nil, ExitStatusCode: nagios.StateOKExitCode, } // Second, immediately defer ReturnCheckResults() so that it runs as the // last step in your client code. If you do not defer ReturnCheckResults() // immediately any other deferred functions in your client code will not // run. // // Avoid calling os.Exit() directly from your code. If you do, this // library is unable to function properly; this library expects that it // will handle calling os.Exit() with the required exit code (and // specifically formatted output). // // For handling error cases, the approach is roughly the same, only you // call return explicitly to end execution of the client code and allow // deferred functions to run. defer plugin.ReturnCheckResults() pd := []nagios.PerformanceData{ { // NOTE: This metric is provided by default if using the provided // nagios.NewPlugin constructor. // // If we specify this value ourselves, *our* value takes // precedence and the default value is ignored. Label: "time", Value: fmt.Sprintf("%dms", time.Since(pluginStart).Milliseconds()), }, { Label: "datacenters", Value: fmt.Sprintf("%d", 2), }, { Label: "triggered_alarms", Value: fmt.Sprintf("%d", 14), }, } if err := plugin.AddPerfData(false, pd...); err != nil { log.Printf("failed to add performance data metrics: %v", err) plugin.Errors = append(plugin.Errors, err) // NOTE: You might wish to make this a "best effort" scenario and // proceed with plugin execution. In that case, don't return yet until // further data has been gathered. return } // more stuff here plugin.ServiceOutput = "one-line summary of plugin results " plugin.LongServiceOutput = "more detailed output from plugin here" }
Output:
Example (EmitPerformanceDataViaDeferredAnonymousFunc) ¶
ExampleEmitPerformanceDataViaDeferredAnonymousFunc demonstrates emitting plugin performance data provided via a deferred anonymous function.
NOTE: While this example illustrates providing a time metric, this metric is provided for you if using the nagios.NewPlugin constructor. If specifying this value ourselves, *our* value takes precedence and the default value is ignored.
package main import ( "fmt" "log" "time" "github.com/atc0005/go-nagios" ) // Ignore this. This is just to satisfy the "whole file" example requirements // per https://go.dev/blog/examples. var _ = "https://github.com/atc0005/go-nagios" // ExampleEmitPerformanceDataViaDeferredAnonymousFunc demonstrates emitting // plugin performance data provided via a deferred anonymous function. // // NOTE: While this example illustrates providing a time metric, this metric // is provided for you if using the nagios.NewPlugin constructor. If specifying // this value ourselves, *our* value takes precedence and the default value is // ignored. func main() { // Start the timer. We'll use this to emit the plugin runtime as a // performance data metric. // // NOTE: While this example illustrates providing a time metric, this // metric is provided for you if using the nagios.NewPlugin constructor. // If specifying this value ourselves, *our* value takes precedence and // the default value is ignored. pluginStart := time.Now() // First, create an instance of the Plugin type. Here we're opting to // manually construct the Plugin value instead of using the constructor // (mostly for contrast). // // We set the ExitStatusCode value to reflect a successful plugin // execution. If we do not alter the exit status code later this is what // will be reported to Nagios when the plugin exits. var plugin = nagios.Plugin{ LastError: nil, ExitStatusCode: nagios.StateOKExitCode, } // Second, immediately defer ReturnCheckResults() so that it runs as the // last step in your client code. If you do not defer ReturnCheckResults() // immediately any other deferred functions in your client code will not // run. // // Avoid calling os.Exit() directly from your code. If you do, this // library is unable to function properly; this library expects that it // will handle calling os.Exit() with the required exit code (and // specifically formatted output). // // For handling error cases, the approach is roughly the same, only you // call return explicitly to end execution of the client code and allow // deferred functions to run. defer plugin.ReturnCheckResults() // Collect last minute details just before ending plugin execution. defer func(plugin *nagios.Plugin, start time.Time) { // Record plugin runtime, emit this metric regardless of exit // point/cause. runtimeMetric := nagios.PerformanceData{ // NOTE: This metric is provided by default if using the provided // nagios.NewPlugin constructor. // // If we specify this value ourselves, *our* value takes // precedence and the default value is ignored. Label: "time", Value: fmt.Sprintf("%dms", time.Since(start).Milliseconds()), } if err := plugin.AddPerfData(false, runtimeMetric); err != nil { log.Printf("failed to add time (runtime) performance data metric: %v", err) plugin.Errors = append(plugin.Errors, err) } }(&plugin, pluginStart) // more stuff here //nolint:goconst plugin.ServiceOutput = "one-line summary text here" //nolint:goconst plugin.LongServiceOutput = "more detailed output here" }
Output:
Example (ExtractEncodedPayload) ¶
Example_extractEncodedPayload represents a sample client application that extracts a previously encoded payload from plugin output (e.g., retrieved via the monitoring system's API or a log file).
package main import ( "fmt" "log" "os" "github.com/atc0005/go-nagios" ) // Ignore this. This is just to satisfy the "whole file" example requirements // per https://go.dev/blog/examples. var _ = "https://github.com/atc0005/go-nagios" // Example_extractEncodedPayload represents a sample client application that // extracts a previously encoded payload from plugin output (e.g., retrieved // via the monitoring system's API or a log file). func main() { // This represents the data before it was encoded and added to the plugin // output. origData := `{"Age":17,"Interests":["books","games", "Crystal Stix"]}` // This represents the encoded data that was previously added to the // plugin output. encodedData := `<~HQkagAKj/i2_6.EDKKH1ATMs7,!&pP@W-1#F!<.ZB45XgF!<.X,"$BrF*(i,+B*ArGTpFA~>` sampleServiceOutput := "one-line summary of plugin results " sampleLongServiceOutput := "detailed text line1\ndetailed text line2\ndetailed text line3" sampleMetricsOutput := `| 'time'=874ms;;;;` // This represents the original plugin output captured by the monitoring // system which we retrieved via the monitoring system's API, a log file, // etc. originalPluginOutput := fmt.Sprintf( "%s%s%s%s%s%s%s", sampleServiceOutput, sampleLongServiceOutput, nagios.CheckOutputEOL, encodedData, nagios.CheckOutputEOL, sampleMetricsOutput, nagios.CheckOutputEOL, ) decodedPayload, err := nagios.ExtractAndDecodeASCII85Payload( originalPluginOutput, "", nagios.DefaultASCII85EncodingDelimiterLeft, nagios.DefaultASCII85EncodingDelimiterRight, ) if err != nil { log.Println("Failed to extract and decode payload from original plugin output", err) os.Exit(1) } // We compare here for illustration purposes, but in many cases you may // not have access to the data in its original form as collected by the // monitoring plugin (e.g., it was generated dynamically or retrieved from // a remote system's state and not stored long-term). if decodedPayload != origData { log.Println("Extracted & decoded payload data does not match original data") os.Exit(1) } fmt.Println("Original data:", decodedPayload) }
Output: Original data: {"Age":17,"Interests":["books","games", "Crystal Stix"]}
Example (HideSections) ¶
ExampleHideSections demonstrates explicitly hiding or omitting the optional section headers for thresholds and errors.
package main import ( "github.com/atc0005/go-nagios" ) // Ignore this. This is just to satisfy the "whole file" example requirements // per https://go.dev/blog/examples. var _ = "https://github.com/atc0005/go-nagios" // ExampleHideSections demonstrates explicitly hiding or omitting the optional // section headers for thresholds and errors. func main() { // First, create an instance of the Plugin type. By default this value is // configured to indicate a successful execution. This should be // overridden by client code to indicate the final plugin state to Nagios // when the plugin exits. var plugin = nagios.NewPlugin() // Second, immediately defer ReturnCheckResults() so that it runs as the // last step in your client code. If you do not defer ReturnCheckResults() // immediately any other deferred functions in your client code will not // run. // // Avoid calling os.Exit() directly from your code. If you do, this // library is unable to function properly; this library expects that it // will handle calling os.Exit() with the required exit code (and // specifically formatted output). // // For handling error cases, the approach is roughly the same, only you // call return explicitly to end execution of the client code and allow // deferred functions to run. defer plugin.ReturnCheckResults() // more stuff here // Hide/Omit these sections from plugin output plugin.HideErrorsSection() plugin.HideThresholdsSection() //nolint:goconst plugin.ServiceOutput = "one-line summary text here" //nolint:goconst plugin.LongServiceOutput = "more detailed output here" }
Output:
Example (OverrideSectionHeaders) ¶
ExampleOverrideSectionHeaders demonstrates overriding the default text with values that better fit our use case.
package main import ( "github.com/atc0005/go-nagios" ) // Ignore this. This is just to satisfy the "whole file" example requirements // per https://go.dev/blog/examples. var _ = "https://github.com/atc0005/go-nagios" // ExampleOverrideSectionHeaders demonstrates overriding the default text with // values that better fit our use case. func main() { // First, create an instance of the Plugin type. By default this value is // configured to indicate a successful execution. This should be // overridden by client code to indicate the final plugin state to Nagios // when the plugin exits. var plugin = nagios.NewPlugin() // Second, immediately defer ReturnCheckResults() so that it runs as the // last step in your client code. If you do not defer ReturnCheckResults() // immediately any other deferred functions in your client code will not // run. // // Avoid calling os.Exit() directly from your code. If you do, this // library is unable to function properly; this library expects that it // will handle calling os.Exit() with the required exit code (and // specifically formatted output). // // For handling error cases, the approach is roughly the same, only you // call return explicitly to end execution of the client code and allow // deferred functions to run. defer plugin.ReturnCheckResults() // more stuff here // Override default section headers with our custom values. plugin.SetErrorsLabel("VALIDATION ERRORS") plugin.SetDetailedInfoLabel("VALIDATION CHECKS REPORT") }
Output:
Example (UseABrandingCallback) ¶
ExampleUseABrandingCallback demonstrates using a branding callback to emit custom branding details at plugin exit. This can be useful to brand plugin output so that it is easier to tell which plugin generated it.
package main import ( "github.com/atc0005/go-nagios" ) // Ignore this. This is just to satisfy the "whole file" example requirements // per https://go.dev/blog/examples. var _ = "https://github.com/atc0005/go-nagios" // Pretend that this is provided by another package. Included here for // simplicity. type Config struct { EmitBranding bool } // Branding accepts a message and returns a function that concatenates that // message with version information. This function is intended to be called as // a final step before application exit after any other output has already // been emitted. // // Pretend that this is provided by another package. Included here for // simplicity. func Branding(s string) func() string { return func() string { return s + " appended branding string" } } // ExampleUseABrandingCallback demonstrates using a branding callback to emit // custom branding details at plugin exit. This can be useful to brand plugin // output so that it is easier to tell which plugin generated it. func main() { // First, create an instance of the Plugin type. By default this value is // configured to indicate a successful execution. This should be // overridden by client code to indicate the final plugin state to Nagios // when the plugin exits. var plugin = nagios.NewPlugin() // Second, immediately defer ReturnCheckResults() so that it runs as the // last step in your client code. If you do not defer ReturnCheckResults() // immediately any other deferred functions in your client code will not // run. // // Avoid calling os.Exit() directly from your code. If you do, this // library is unable to function properly; this library expects that it // will handle calling os.Exit() with the required exit code (and // specifically formatted output). // // For handling error cases, the approach is roughly the same, only you // call return explicitly to end execution of the client code and allow // deferred functions to run. defer plugin.ReturnCheckResults() // ... // In this example, we'll make a further assumption that you have a config // value with an EmitBranding field to indicate whether the user/sysadmin // has opted to emit branding information. This value might be returned // from another package. Here we're representing it as a literal value for // simplicity. config := Config{ EmitBranding: true, } if config.EmitBranding { // If enabled, show application details at end of notification plugin.BrandingCallback = Branding("Notification generated by ") } // You could just as easily create an anonymous function as the callback: if config.EmitBranding { // If enabled, show application details at end of notification plugin.BrandingCallback = func(msg string) func() string { return func() string { return "Notification generated by " + msg } }("HelloWorld") } }
Output:
Example (UsingOnlyTheProvidedConstants) ¶
Example_usingOnlyTheProvidedConstants is a simple example that illustrates using only the provided constants from this package. After you've imported this library, reference the exported data types as you would from any other package.
// In this example, we reference a specific exit code for the OK state and // also use the provided state "labels" to avoid using literal string // state values (recommended): fmt.Printf( "%s: All checks have passed%s", nagios.StateOKLabel, nagios.CheckOutputEOL, ) os.Exit(nagios.StateOKExitCode)
Output:
Example (UsingOnlyTheProvidedExitCodeConstants) ¶
Example_usingOnlyTheProvidedExitCodeConstants is a simple example that illustrates using only the provided exit code constants from this package. After you've imported this library, reference the exported data types as you would from any other package.
// In this example, we reference a specific exit code for the OK state: fmt.Println("OK: All checks have passed") os.Exit(nagios.StateOKExitCode)
Output:
Index ¶
- Constants
- Variables
- func AnnotateError(errorAdviceMap ErrorAnnotationMappings, errs ...error) []error
- func DecodeASCII85Payload(encodedInput []byte, leftDelimiter string, rightDelimiter string) ([]byte, error)
- func EncodeASCII85Payload(data []byte, leftDelimiter string, rightDelimiter string) string
- func ExitCodeToStateLabel(exitCode int) string
- func ExtractAndDecodeASCII85Payload(text string, customRegex string, leftDelimiter string, rightDelimiter string) (string, error)
- func ExtractEncodedASCII85Payload(text string, customRegex string, leftDelimiter string, rightDelimiter string) (string, error)
- func StateLabelToExitCode(label string) int
- func SupportedExitCodes() []int
- func SupportedStateLabels() []string
- type ErrorAnnotationMappings
- type ExitCallBackFunc
- type PerformanceData
- type Plugin
- func (p *Plugin) AddAnnotatedError(errorAdviceMap ErrorAnnotationMappings, errs ...error)
- func (p *Plugin) AddError(errs ...error)
- func (p *Plugin) AddPayloadBytes(input []byte) (int, error)
- func (p *Plugin) AddPayloadString(input string) (int, error)
- func (p *Plugin) AddPerfData(skipValidate bool, perfData ...PerformanceData) error
- func (p *Plugin) AddUniqueAnnotatedError(errorAdviceMap ErrorAnnotationMappings, errs ...error)
- func (p *Plugin) AddUniqueError(errs ...error)
- func (p *Plugin) AnnotateRecordedErrors(errorAdviceMap ErrorAnnotationMappings)
- func (p *Plugin) EvaluateThreshold(perfData ...PerformanceData) error
- func (p *Plugin) HideErrorsSection()
- func (p *Plugin) HideThresholdsSection()
- func (p *Plugin) ReturnCheckResults()
- func (p *Plugin) SetDetailedInfoLabel(newLabel string)
- func (p *Plugin) SetEncodedPayloadDelimiterLeft(delimiter string)
- func (p *Plugin) SetEncodedPayloadDelimiterRight(delimiter string)
- func (p *Plugin) SetEncodedPayloadLabel(newLabel string)
- func (p *Plugin) SetErrorsLabel(newLabel string)
- func (p *Plugin) SetOutputTarget(w io.Writer)
- func (p *Plugin) SetPayloadBytes(input []byte) (int, error)
- func (p *Plugin) SetPayloadString(input string) (int, error)
- func (p *Plugin) SetThresholdsLabel(newLabel string)
- func (p *Plugin) SkipOSExit()
- func (p *Plugin) UnencodedPayload() string
- type Range
- type ServiceState
Examples ¶
- Package (AddEncodedPayload)
- Package (BasicPluginStructure)
- Package (EmitPerformanceData)
- Package (EmitPerformanceDataViaDeferredAnonymousFunc)
- Package (ExtractEncodedPayload)
- Package (HideSections)
- Package (OverrideSectionHeaders)
- Package (UseABrandingCallback)
- Package (UsingOnlyTheProvidedConstants)
- Package (UsingOnlyTheProvidedExitCodeConstants)
Constants ¶
const ( StateOKExitCode int = 0 StateWARNINGExitCode int = 1 StateCRITICALExitCode int = 2 StateUNKNOWNExitCode int = 3 StateDEPENDENTExitCode int = 4 )
Nagios plugin/service check states. These constants replicate the values from utils.sh which is normally found at one of these two locations, depending on which Linux distribution you're using:
- /usr/lib/nagios/plugins/utils.sh - /usr/local/nagios/libexec/utils.sh
See also http://nagios-plugins.org/doc/guidelines.html
const ( StateOKLabel string = "OK" StateWARNINGLabel string = "WARNING" StateCRITICALLabel string = "CRITICAL" StateUNKNOWNLabel string = "UNKNOWN" StateDEPENDENTLabel string = "DEPENDENT" )
Nagios plugin/service check state "labels". These constants are provided as an alternative to using literal state strings throughout client application code.
const ( // DefaultASCII85EncodingDelimiterLeft is the left delimiter often used // with ascii85-encoded data. DefaultASCII85EncodingDelimiterLeft string = "<~" // DefaultASCII85EncodingDelimiterRight is the right delimiter often used // with ascii85-encoded data. DefaultASCII85EncodingDelimiterRight string = "~>" // DefaultASCII85EncodingPatternRegex is the default regex pattern used to // match and extract an Ascii85 encoded payload as used in the btoa tool // and Adobe's PostScript and PDF document formats. // // In Ascii85-encoded blocks, whitespace and line-break characters may be // present anywhere, including in the middle of a 5-character block, but // they must be silently ignored. // // - https://pkg.go.dev/encoding/ascii85 // - https://en.wikipedia.org/wiki/Ascii85 // // NOTE: Not using delimiters when saving an encoded payload makes the // extraction process *VERY* unreliable as this regex pattern (by itself) // matches far more than likely intended. // DefaultASCII85EncodingPatternRegex string = `[\x21-\x75\s]+` )
const CheckOutputEOL string = " \n"
CheckOutputEOL is the newline character(s) used with formatted service and host check output. Based on previous testing, Nagios treats LF newlines (without a leading space) within the `$LONGSERVICEOUTPUT$` macro as literal values instead of parsing them for display purposes.
Using DOS EOL values with fmt.Fprintf() (or fmt.Fprintln()) gives expected formatting results in the Nagios Core web UI, but results in double newlines in Nagios XI output (see GH-109). Using a UNIX EOL with a single leading space appears to give the intended results for both Nagios Core and Nagios XI.
Variables ¶
var ( // ErrPanicDetected indicates that client code has an unhandled panic and // that this library detected it before it could cause the plugin to // abort. This error is included in the LongServiceOutput emitted by the // plugin. ErrPanicDetected = errors.New("plugin crash/panic detected") // ErrPerformanceDataMissingLabel indicates that client code did not // provide a PerformanceData value in the expected format; the label for // the label/value pair is missing. ErrPerformanceDataMissingLabel = errors.New("provided performance data missing required label") // ErrPerformanceDataMissingValue indicates that client code did not // provide a PerformanceData value in the expected format; the value for // the label/value pair is missing. ErrPerformanceDataMissingValue = errors.New("provided performance data missing required value") // ErrNoPerformanceDataProvided indicates that client code did not provide // the expected PerformanceData value(s). ErrNoPerformanceDataProvided = errors.New("no performance data provided") // ErrInvalidPerformanceDataFormat indicates that a given performance data // metric is not in a supported format. ErrInvalidPerformanceDataFormat = errors.New("invalid performance data format") // ErrInvalidRangeThreshold indicates that a given range threshold is not in a supported format. ErrInvalidRangeThreshold = errors.New("invalid range threshold") // ErrMissingValue indicates that an expected value was missing. ErrMissingValue = errors.New("missing expected value") // ErrEncodedPayloadNotFound indicates that an encoded payload was not // found during an extraction attempt. ErrEncodedPayloadNotFound = errors.New("encoded payload not found") // ErrEncodedPayloadInvalid indicates that an encoded payload was found // during extraction but was found to be invalid. ErrEncodedPayloadInvalid = errors.New("encoded payload invalid") // ErrEncodedPayloadInvalid indicates that a regular expression used to // identify an encoded payload was found to be invalid. ErrEncodedPayloadRegexInvalid = errors.New("encoded payload regex invalid") )
Sentinel error collection. Exported for potential use by client code to detect & handle specific error scenarios.
Functions ¶
func AnnotateError ¶ added in v0.16.0
func AnnotateError(errorAdviceMap ErrorAnnotationMappings, errs ...error) []error
AnnotateError adds additional human-readable explanation for errors encountered during plugin execution. This additional context is intended to help sysadmins remediate common issues detected by plugins.
This function receives an optional map of error type to advice and one or more errors. If the map argument is nil or empty a default advice map is used. If an empty error collection or a collection of nil error values are provided for evaluation then nil is returned.
Each error is evaluated for a match in its chain within the given advice map. If no advice map is given then the default advice map is used.
If an error match is found then the advice is appended to the error via error wrapping. This process is repeated for each applicable error in the given error chain. The error is unmodified if no advice is found or if the error is already annotated with advice for the specific error.
This updated error collection is returned to the caller.
The original error collection is returned unmodified if no annotations were deemed necessary.
func DecodeASCII85Payload ¶ added in v0.17.0
func DecodeASCII85Payload(encodedInput []byte, leftDelimiter string, rightDelimiter string) ([]byte, error)
DecodeASCII85Payload decodes given Ascii85 encoded input or an error if one occurs during decoding. If provided, the left and right delimiters are trimmed from the given input before decoding is performed.
This function is not intended to extract an Ascii encoded payload from surrounding text.
func EncodeASCII85Payload ¶ added in v0.17.0
EncodeASCII85Payload encodes the given input as Ascii85. If no input is provided, an empty string is returned.
If specified, the given left and right delimiters are used to enclose the encoded payload. If not specified, no delimiters are used.
func ExitCodeToStateLabel ¶ added in v0.15.0
ExitCodeToStateLabel returns the corresponding plugin state label for the given plugin exit code. If an invalid value is provided the StateUNKNOWNLabel value is returned.
func ExtractAndDecodeASCII85Payload ¶ added in v0.17.0
func ExtractAndDecodeASCII85Payload(text string, customRegex string, leftDelimiter string, rightDelimiter string) (string, error)
ExtractAndDecodeASCII85Payload extracts and decodes a Ascii85 encoded payload from given input text.
If not provided, a default regular expression for the Ascii85 encoding format is used to perform matching/extraction.
If specified, delimiters are removed during the extraction process.
NOTE: While technically optional, the use of delimiters for matching an encoded payload is *highly* recommended; without delimiters, reliability of payload matching is *greatly* reduced (LOTS of false positives).
The extracted content is the original unencoded payload before Ascii85 encoding was performed. Depending on the type of the original data, the retrieved payload may require additional processing (e.g., JSON vs plaintext).
func ExtractEncodedASCII85Payload ¶ added in v0.17.0
func ExtractEncodedASCII85Payload(text string, customRegex string, leftDelimiter string, rightDelimiter string) (string, error)
ExtractEncodedASCII85Payload extracts an Ascii85 encoded payload from given text input using specified delimiters.
If not provided, a default regular expression for the Ascii85 encoding format is used to perform matching/extraction.
If specified, delimiters are removed during the extraction process.
NOTE: While technically optional, the use of delimiters for matching an encoded payload is *highly* recommended; reliability of payload matching is *greatly* reduced without using delimiters.
The extracted payload is Ascii85 encoded and will need to be decoded before the original content is accessible.
func StateLabelToExitCode ¶ added in v0.15.0
StateLabelToExitCode returns the corresponding plugin exit code for the given plugin state label. If an invalid value is provided the StateUNKNOWNExitCode value is returned.
func SupportedExitCodes ¶ added in v0.15.0
func SupportedExitCodes() []int
SupportedExitCodes returns a list of valid plugin exit codes.
func SupportedStateLabels ¶ added in v0.15.0
func SupportedStateLabels() []string
SupportedStateLabels returns a list of valid plugin state labels.
Types ¶
type ErrorAnnotationMappings ¶ added in v0.16.0
ErrorAnnotationMappings is a collection of error to string values. Each error is linked to specific advice for how to remediate the issue. The advice is appended to the list of errors (if any) which occurred during plugin execution. If the sysadmin opted to hide the errors section then no error output (and no advice) will be displayed.
func DefaultErrorAnnotationMappings ¶ added in v0.16.0
func DefaultErrorAnnotationMappings() ErrorAnnotationMappings
DefaultErrorAnnotationMappings provides a default collection of error to string values which associate suggested advice with known/common error conditions.
This collection is intended to serve as a starting point for plugin authors to further extend or override as needed.
type ExitCallBackFunc ¶ added in v0.4.0
type ExitCallBackFunc func() string
ExitCallBackFunc represents a function that is called as a final step before application termination so that branding information can be emitted for inclusion in the notification. This helps identify which specific application (and its version) that is responsible for the notification.
type PerformanceData ¶ added in v0.8.0
type PerformanceData struct { // Label is the text string used as a label for a specific performance // data point. The label length is arbitrary, but ideally the first 19 // characters are unique due to a limitation in RRD. There is also a // limitation in the amount of data that NRPE returns to Nagios. When // emitted by a Nagios plugin, single quotes are required if spaces are in // the label. // // The popular convention used by plugin authors (and official // documentation) is to use underscores for separating multiple words. For // example, 'percent_packet_loss' instead of 'percent packet loss', // 'percentPacketLoss' or 'percent-packet-loss'. Label string // Value is the data point associated with the performance data label. // // Value is in class [-0-9.] and must be the same UOM as Min and Max UOM. // Value may be a literal "U" instead, this would indicate that the actual // value couldn't be determined. Value string // UnitOfMeasurement is an optional unit of measurement (UOM). If // provided, consists of a string of zero or more characters. Numbers, // semicolons or quotes are not permitted. // // Examples: // // 1) no unit specified - assume a number (int or float) of things (eg, // users, processes, load averages) // 2) s - seconds (also us, ms) // 3) % - percentage // 4) B - bytes (also KB, MB, TB) // 5) c - a continuous counter (such as bytes transmitted on an interface) // // NOTE: nagios-plugins.org uses "some examples" wording, // monitoring-plugins.org uses "one of" wording to refer to the examples, // implying that *only* the listed examples are supported. Icinga 2 // documentation indicates that unknown UoMs are discarded (as if not // specified). UnitOfMeasurement string // Warn is in the range format (see the Section called Threshold and // Ranges). Must be the same UOM as Crit. An empty string is permitted. // // https://nagios-plugins.org/doc/guidelines.html#THRESHOLDFORMAT Warn string // Crit is in the range format (see the Section called Threshold and // Ranges). Must be the same UOM as Warn. An empty string is permitted. // // https://nagios-plugins.org/doc/guidelines.html#THRESHOLDFORMAT Crit string // Min is in class [-0-9.] and must be the same UOM as Value and Max. Min // is not required if UOM=%. An empty string is permitted. Min string // Max is in class [-0-9.] and must be the same UOM as Value and Min. Max // is not required if UOM=%. An empty string is permitted. Max string }
PerformanceData represents the performance data generated by a Nagios plugin.
Plugin performance data is external data specific to the plugin used to perform the host or service check. Plugin-specific data can include things like percent packet loss, free disk space, processor load, number of current users, etc. - basically any type of metric that the plugin is measuring when it executes.
func ParsePerfData ¶ added in v0.14.0
func ParsePerfData(rawPerfdata string) ([]PerformanceData, error)
ParsePerfData parses a raw performance data string into a collection of PerformanceData values. The expected input format is:
'label'=value[UOM];[warn];[crit];[min];[max]
Single quotes around the label are optional (if it does not contain spaces). Some fields are also optional. See the Nagios Plugin Dev Guidelines for additional details.
func (PerformanceData) String ¶ added in v0.11.0
func (pd PerformanceData) String() string
String provides a PerformanceData metric in format ready for use in plugin output.
func (PerformanceData) Validate ¶ added in v0.8.0
func (pd PerformanceData) Validate() error
Validate performs basic validation of PerformanceData fields using logic specified in the Nagios Plugin Dev Guidelines. An error is returned for any validation failures.
type Plugin ¶ added in v0.12.0
type Plugin struct { // LastError is the last error encountered which should be reported as // part of ending the service check (e.g., "Failed to connect to XYZ to // check contents of Inbox"). // // Deprecated: Use Errors field or AddError method instead. LastError error // Errors is a collection of one or more recorded errors to be displayed // in LongServiceOutput as a list when ending the service check. Errors []error // ExitStatusCode is the exit or exit status code provided to the Nagios // instance that calls this service check. These status codes indicate to // Nagios "state" the service is considered to be in. The most common // states are OK (0), WARNING (1) and CRITICAL (2). ExitStatusCode int // ServiceOutput is the first line of text output from the last service // check (i.e. "Ping OK"). ServiceOutput string // LongServiceOutput is the full text output (aside from the first line) // from the last service check. LongServiceOutput string // WarningThreshold is the value used to determine when the service check // has crossed between an existing state into a WARNING state. This value // is used for display purposes. WarningThreshold string // CriticalThreshold is the value used to determine when the service check // has crossed between an existing state into a CRITICAL state. This value // is used for display purposes. CriticalThreshold string // BrandingCallback is a function that is called before application // termination to emit branding details at the end of the notification. // See also ExitCallBackFunc. BrandingCallback ExitCallBackFunc // contains filtered or unexported fields }
Plugin represents the state of a monitoring plugin, including the most recent error and the final intended plugin state.
func NewPlugin ¶ added in v0.12.0
func NewPlugin() *Plugin
NewPlugin constructs a new Plugin value in the same way that client code has been using this library. We also record a default time performance data metric. This default metric is ignored if supplied by client code.
func (*Plugin) AddAnnotatedError ¶ added in v0.16.0
func (p *Plugin) AddAnnotatedError(errorAdviceMap ErrorAnnotationMappings, errs ...error)
AddAnnotatedError adds additional human-readable explanation for errors encountered during plugin execution. This additional context is intended to help sysadmins remediate common issues detected by plugins.
Each entry in the error chain for a given error is evaluated for a match in the provided error advice map. If an empty error collection or a collection of nil error values are provided for evaluation then nil is returned.
If a match is found and the error is not already annotated with specified advice then the advice is appended to the error (via wrapping). If no advice is found then the original error is unmodified.
Existing errors in the collection are unmodified. Given errors are appended (annotated or not) to the existing error collection.
NOTE: Deduplication of errors is *not* performed. The caller is responsible for ensuring that a given error (annotated or not) is not already recorded in the collection.
Another method is provided for callers which wish to skip insertion of an error if it is already present in the collection.
func (*Plugin) AddError ¶ added in v0.12.0
AddError appends provided errors to the collection.
NOTE: Deduplication of errors is *not* performed. The caller is responsible for ensuring that a given error is not already recorded in the collection.
func (*Plugin) AddPayloadBytes ¶ added in v0.17.0
AddPayloadBytes appends the given input in bytes to the payload buffer. It returns the length of input and a potential error.
The contents of this buffer will be included in the plugin's output as an encoded payload suitable for later retrieval/decoding.
func (*Plugin) AddPayloadString ¶ added in v0.17.0
AddPayloadString appends the given input string to the payload buffer. It returns the length of input and a potential error.
The contents of this buffer will be included in the plugin's output as an encoded payload suitable for later retrieval/decoding.
func (*Plugin) AddPerfData ¶ added in v0.12.0
func (p *Plugin) AddPerfData(skipValidate bool, perfData ...PerformanceData) error
AddPerfData adds provided performance data to the collection overwriting any previous performance data metrics using the same label.
Validation is skipped if requested, otherwise an error is returned if validation fails. Validation failure results in no performance data being appended. Client code may wish to disable validation if performing this step directly.
func (*Plugin) AddUniqueAnnotatedError ¶ added in v0.16.0
func (p *Plugin) AddUniqueAnnotatedError(errorAdviceMap ErrorAnnotationMappings, errs ...error)
AddUniqueAnnotatedError adds additional human-readable explanation for errors encountered during plugin execution. This additional context is intended to help sysadmins remediate common issues detected by plugins.
Each entry in the error chain for a given error is evaluated for a match in the provided error advice map. If an empty error collection or a collection of nil error values are provided for evaluation then nil is returned.
If a match is found and the error is not already annotated with specified advice then the advice is appended to the error (via wrapping). If no advice is found then the original error is unmodified.
Existing errors in the collection are unmodified.
Annotated errors are appended to the collection *unless* they are determined to already be present. This evaluation is performed using case-insensitive string comparison.
func (*Plugin) AddUniqueError ¶ added in v0.16.0
AddUniqueError appends provided errors to the collection if they are not already present. If a given error is already in the collection then it will be skipped.
Errors are evaluated using case-insensitive string comparison.
func (*Plugin) AnnotateRecordedErrors ¶ added in v0.16.0
func (p *Plugin) AnnotateRecordedErrors(errorAdviceMap ErrorAnnotationMappings)
AnnotateRecordedErrors adds additional human-readable explanation for errors encountered during plugin execution. This additional context is intended to help sysadmins remediate common issues detected by plugins.
Each error already recorded in the collection is evaluated for a match in the provided error advice map. If the existing error collection is empty then no annotations are performed.
If an error match is found *AND* the error is not already annotated with specified advice then the advice is appended to the error via error wrapping. This process is repeated for each applicable error in the given error chain.
If no advice is found then the error is unmodified. The existing error collection is replaced with this (potentially) updated collection of error chains.
NOTE: Deduplication of errors already recorded in the collection is *not* performed. The caller is responsible for ensuring that a given error is not already recorded in the collection.
func (*Plugin) EvaluateThreshold ¶ added in v0.13.0
func (p *Plugin) EvaluateThreshold(perfData ...PerformanceData) error
EvaluateThreshold causes the performance data to be checked against the Warn and Crit thresholds provided by client code and sets the ExitStatusCode of the plugin as appropriate.
func (*Plugin) HideErrorsSection ¶ added in v0.12.0
func (p *Plugin) HideErrorsSection()
HideErrorsSection indicates that client code has opted to hide the errors section, regardless of whether values were previously provided for display.
func (*Plugin) HideThresholdsSection ¶ added in v0.12.0
func (p *Plugin) HideThresholdsSection()
HideThresholdsSection indicates that client code has opted to hide the thresholds section, regardless of whether values were previously provided for display.
func (*Plugin) ReturnCheckResults ¶ added in v0.12.0
func (p *Plugin) ReturnCheckResults()
ReturnCheckResults is intended to provide a reliable way to return a desired exit code from applications used as Nagios plugins. In most cases, this method should be registered as the first deferred function in client code. See remarks regarding "masking" or "swallowing" application panics.
Since Nagios relies on plugin exit codes to determine success/failure of checks, the approach that is most often used with other languages is to use something like Using os.Exit() directly and force an early exit of the application with an explicit exit code. Using os.Exit() directly in Go does not run deferred functions. Go-based plugins that do not rely on deferring function calls may be able to use os.Exit(), but introducing new dependencies later could introduce problems if those dependencies rely on deferring functions.
Before calling this method, client code should first set appropriate field values on the receiver. When called, this method will process them and exit with the desired exit code and status output.
To repeat, if scheduled via defer, this method should be registered first; because this method calls os.Exit to set the intended plugin exit state, no other deferred functions will have an opportunity to run, so register this method first so that when deferred, it will be run last (FILO).
Because this method is (or should be) deferred first within client code, it will run after all other deferred functions. It will also run before a panic in client code forces the application to exit. As already noted, this method calls os.Exit to set the plugin exit state. Because os.Exit forces the application to terminate immediately without running other deferred functions or processing panics, this "masks", "swallows" or "blocks" panics from client code from surfacing. This method checks for unhandled panics and if found, overrides exit state details from client code and surfaces details from the panic instead as a CRITICAL state.
func (*Plugin) SetDetailedInfoLabel ¶ added in v0.12.0
SetDetailedInfoLabel overrides the default detailed info label text.
func (*Plugin) SetEncodedPayloadDelimiterLeft ¶ added in v0.17.0
SetEncodedPayloadDelimiterLeft uses the given value to override the default left delimiter used when encoding a provided payload. Specify an empty string if no left delimiter should be used.
This value is ignored if no payload is provided.
func (*Plugin) SetEncodedPayloadDelimiterRight ¶ added in v0.17.0
SetEncodedPayloadDelimiterRight uses the given value to override the default right delimiter used when encoding a provided payload. Specify an empty string if no right delimiter should be used.
This value is ignored if no payload is provided.
func (*Plugin) SetEncodedPayloadLabel ¶ added in v0.17.0
SetEncodedPayloadLabel overrides the default encoded payload label text.
func (*Plugin) SetErrorsLabel ¶ added in v0.12.0
SetErrorsLabel overrides the default errors label text.
func (*Plugin) SetOutputTarget ¶ added in v0.12.0
SetOutputTarget assigns a target for Nagios plugin output. By default output is emitted to os.Stdout. If given an invalid output target the default output target will be used instead.
func (*Plugin) SetPayloadBytes ¶ added in v0.17.0
SetPayloadBytes uses the given input in bytes to overwrite any existing content in the payload buffer. It returns the length of input and a potential error.
The contents of this buffer will be included in the plugin's output as an encoded payload suitable for later retrieval/decoding.
func (*Plugin) SetPayloadString ¶ added in v0.17.0
SetPayloadString uses the given input string to overwrite any existing content in the payload buffer. It returns the length of input and a potential error.
The contents of this buffer will be included in the plugin's output as an encoded payload suitable for later retrieval/decoding.
func (*Plugin) SetThresholdsLabel ¶ added in v0.12.0
SetThresholdsLabel overrides the default thresholds label text.
func (*Plugin) SkipOSExit ¶ added in v0.12.0
func (p *Plugin) SkipOSExit()
SkipOSExit indicates that the os.Exit(x) step used to signal to Nagios what state plugin execution has completed in (e.g., OK, WARNING, ...) should be skipped. If skipped, a message is logged to os.Stderr in place of the os.Exit(x) call.
Disabling the call to os.Exit is needed by tests to prevent panics in Go 1.16 and newer.
func (*Plugin) UnencodedPayload ¶ added in v0.17.0
UnencodedPayload returns the payload buffer contents in string format as-is without encoding applied.
type Range ¶ added in v0.13.0
Range represents the thresholds that the user can pass in for warning and critical, this format is based on the Nagios Plugin Dev Guidelines: Threshold and Ranges definition.
func ParseRangeString ¶ added in v0.13.0
ParseRangeString static method to construct a Range object from the string representation based on the Nagios Plugin Dev Guidelines: Threshold and Ranges definition.
func (Range) CheckRange ¶ added in v0.13.0
CheckRange returns true if an alert should be raised for a given performance data Value, otherwise false.
type ServiceState ¶ added in v0.7.0
type ServiceState struct { // Label maps directly to one of the supported Nagios state labels. Label string // ExitCode is the exit or exit status code associated with a Nagios // service check. ExitCode int }
ServiceState represents the status label and exit code for a service check.
func SupportedServiceStates ¶ added in v0.15.0
func SupportedServiceStates() []ServiceState
SupportedServiceStates returns a collection of valid plugin service states.