nagios

package module
v0.19.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2024 License: MIT Imports: 16 Imported by: 36

README

go-nagios

Shared Golang package for Nagios plugins

Latest Release Go Reference go.mod Go version Lint and Build Project Analysis

Table of contents

Overview

This package provides support and functionality common to monitoring plugins. While Nagios (Core and XI) are primary monitoring platform targets, the intent is to support (where feasible) all monitoring platforms compatible with Nagios plugins.

Status

While attempts are made to provide stability, this codebase is subject to change without notice and may break client code that depends on it. You are encouraged to vendor this package if you find it useful until such time that the API is considered stable.

Features

  • Nagios state constants
    • state labels (e.g., StateOKLabel)
    • state exit codes (e.g., StateOKExitCode)
  • Nagios CheckOutputEOL constant
    • provides a common newline format shown to produce consistent results for both Nagios Core and Nagios XI (and presumably other similar monitoring systems)
  • Nagios ServiceState type
    • simple label and exit code "wrapper"
    • useful in client code as a way to map internal check results to a Nagios service state value
  • Support for evaluating a given performance data value and setting the final plugin state exit code
  • Support for parsing a given performance data metric string and generating one or more PerformanceData values
  • Support for using a "branding" callback function to display application name, version, or other information as a "trailer" for check results provided to Nagios
    • this could be useful for identifying what version of a plugin determined the service or host state to be an issue
  • Panics from client code are captured and reported
    • panics are surfaced as CRITICAL state
    • service output and error details are overridden to make panics prominent
  • Optional support for emitting performance data metric for plugin output size
    • disabled by default
    • can be toggled on by client code as desired
  • Optional support for emitting performance data generated by plugins
    • if not overridden by client code and if using the provided nagios.NewPlugin() constructor, a default time performance data metric is emitted to indicate total plugin runtime
  • Support for collecting multiple errors from client code
  • Support for explicitly omitting Errors section
    • this section is automatically omitted if no errors were recorded (by client code or panic handling code)
  • Support for explicitly omitting Thresholds section
    • this section is automatically omitted if no thresholds were specified by client code
  • Automatically omit LongServiceOutput section if not specified by client code
  • Support for overriding text used for section headers/labels
  • Support for adding/embedding a compressed and encoded payload in plugin output
  • Support for decoding and decompressing encoded input (payload)
  • Support for extracting (without decoding & decompressing) an encoded payload from captured plugin output
  • Support for extracting, decoding and decompressing an encoded payload (into the original non-encoded form) from captured plugin output
  • Optional debug logging for plugin activity
    • debug log output is sent to stderr by default but can be redirected to a custom target
    • toggles are provided to enable debug logging for all plugin activity or for select types

Changelog

See the CHANGELOG.md file for the changes associated with each release of this application. Changes that have been merged to master, but not yet an official release may also be noted in the file under the Unreleased section. A helpful link to the Git commit history since the last official release is also provided for further review.

Examples

Add this line to your imports like so:

package main

import (
  "fmt"
  "log"
  "os"

  "github.com/atc0005/go-nagios"
)

and pull in a specific version of this library that you'd like to use.

go get github.com/atc0005/go-nagios@v0.9.0

Alternatively, you can use the latest stable tag available to get started:

go get github.com/atc0005/go-nagios@latest

See https://pkg.go.dev/github.com/atc0005/go-nagios for specific examples.

See https://pkg.go.dev/github.com/atc0005/go-nagios?tab=importedby for projects that are using this library.

License

From the LICENSE file:

MIT License

Copyright (c) 2020 Adam Chalkley

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Used by

See the Known importers lists below for a dynamically updated list of projects using either this library or the original project.

References

See also the Used by section for projects known to be using this package. Please report any additional projects that we've missed!

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 (DebugLoggingEnableAll)

This example demonstrates enabling debug logging for all plugin activity types.

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"

// This example demonstrates enabling debug logging for all plugin activity
// types.
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()

	// Enable debug logging for all activity types. This will produce the most
	// verbose output but provides a comprehensive view of this library's
	// behavior.
	//
	// By default, debug logging output is sent to stderr but this can be
	// overridden as needed by setting a custom debug logging output target.
	plugin.DebugLoggingEnableAll()

	// more stuff here involving performing the actual service check

	plugin.ServiceOutput = "one-line summary of plugin results "       //nolint:goconst
	plugin.LongServiceOutput = "more detailed output from plugin here" //nolint:goconst

	// more stuff here involving wrapping up the service check
}
Output:

Example (DebugLoggingEnableLoggingPluginActions)

This example demonstrate enabling debug logging for only the actions activity type. This activity type covers general plugin actions and provides the most verbose logging output. Debug logging output for other plugin activity types is muted.

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"

// This example demonstrate enabling debug logging for only the actions
// activity type. This activity type covers general plugin actions and
// provides the most verbose logging output. Debug logging output for other
// plugin activity types is muted.
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()

	// Enable debug logging for only the actions activity type. This activity
	// type covers general plugin actions and provides the most verbose
	// logging output. Debug logging output for other plugin activity types is
	// muted.
	//
	// By default, debug logging output is sent to stderr but this can be
	// overridden as needed by setting a custom debug logging output target.
	//
	// This can be a buffer, open file handle or other target which satisfies
	// the io.Writer interface.
	plugin.DebugLoggingEnableActions()

	// more stuff here involving performing the actual service check

	plugin.ServiceOutput = "one-line summary of plugin results "       //nolint:goconst
	plugin.LongServiceOutput = "more detailed output from plugin here" //nolint:goconst

	// more stuff here involving wrapping up the service check
}
Output:

Example (DebugLoggingEnableLoggingPluginOutputSize)

This example demonstrate enabling debug logging for only the plugin output calculation activity type. General plugin debug logging activity is muted.

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"

// This example demonstrate enabling debug logging for only the plugin output
// calculation activity type. General plugin debug logging activity is muted.
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()

	// Enable debug logging for only the plugin output calculation activity
	// type. General plugin debug logging activity is muted.
	//
	// By default, debug logging output is sent to stderr but this can be
	// overridden as needed by setting a custom debug logging output target.
	//
	// This can be a buffer, open file handle or other target which satisfies
	// the io.Writer interface.
	plugin.DebugLoggingEnablePluginOutputSize()

	// more stuff here involving performing the actual service check

	plugin.ServiceOutput = "one-line summary of plugin results "       //nolint:goconst
	plugin.LongServiceOutput = "more detailed output from plugin here" //nolint:goconst

	// more stuff here involving wrapping up the service check
}
Output:

Example (DebugLoggingSetCustomDebugLoggingOutputTarget)

This example demonstrates enabling debug logging for all plugin activity types and setting a custom debug logging target.

package main

import (
	"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"

// This example demonstrates enabling debug logging for all plugin activity
// types and setting a custom debug logging target.
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()

	// Enable debug logging of all activity types.
	//
	// By default, debug logging output is sent to stderr but this can be
	// overridden as needed by setting a custom debug logging output target.
	//
	// This can be a buffer, open file handle or other target which satisfies
	// the io.Writer interface.
	plugin.DebugLoggingEnableAll()

	fh, err := os.Open("myPlugin_debug_output.log")
	if err != nil {
		plugin.AddError(err)
		plugin.ExitStatusCode = nagios.StateUNKNOWNExitCode

		return
	}

	plugin.SetDebugLoggingOutputTarget(fh)

	// more stuff here involving performing the actual service check

	plugin.ServiceOutput = "one-line summary of plugin results "       //nolint:goconst
	plugin.LongServiceOutput = "more detailed output from plugin here" //nolint:goconst

	// more stuff here involving wrapping up the service check
}
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 (EnablePluginOutputSizeMetric)

This example demonstrates enabling the plugin output size metric. This optional metric is disabled by default.

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"

// This example demonstrates enabling the plugin output size metric. This
// optional metric is disabled by default.
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()

	// Enable emitting a plugin output size metric. This optional metric is
	// disabled by default.
	plugin.EnablePluginOutputSizePerfDataMetric()

	// more stuff here involving performing the actual service check

	plugin.ServiceOutput = "one-line summary of plugin results "       //nolint:goconst
	plugin.LongServiceOutput = "more detailed output from plugin here" //nolint:goconst

	// more stuff here involving wrapping up the service check
}
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.ExtractAndDecodePayload(
		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

Examples

Constants

View Source
const (
	MyPackageName    string = "go-nagios"
	MyPackagePurpose string = "Provide support and functionality common to monitoring plugins."
)

General package information.

View Source
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

View Source
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.

View Source
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.
	//
	// This regex matches:
	//
	// - Characters in the Ascii85 range (! to u).
	// - The special z character for five consecutive null bytes.
	// - Optional whitespace, which allows for flexibility in formatted or
	//   multiline encoded data.
	//
	// 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\x7A\s]+`
)
View Source
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

View Source
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")

	// ErrCompressedInputInvalid indicates that given input expected to be in
	// a compressed format is invalid.
	ErrCompressedInputInvalid = errors.New("compressed input 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 DecodePayload added in v0.18.0

func DecodePayload(encodedInput []byte, leftDelimiter string, rightDelimiter string) ([]byte, error)

DecodePayload decodes and (if applicable) decompresses given 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 encoded payload from surrounding text.

func EncodePayload added in v0.18.0

func EncodePayload(data []byte, leftDelimiter string, rightDelimiter string) string

EncodePayload compresses and encodes the given input for inclusion in plugin output. If no input is provided, an empty string is returned. If an error is encountered during compression the given input is encoded directly without compression.

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

func ExitCodeToStateLabel(exitCode int) string

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 ExtractAndDecodePayload added in v0.18.0

func ExtractAndDecodePayload(text string, customRegex string, leftDelimiter string, rightDelimiter string) (string, error)

ExtractAndDecodePayload extracts, decodes and decompresses an encoded payload from given input text.

If not provided, a default regular expression for the 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 final result is the original unencoded payload before compression and encoding was performed. Depending on the type of the original data, the retrieved payload may require additional processing (e.g., JSON vs plaintext).

func ExtractEncodedPayload added in v0.18.0

func ExtractEncodedPayload(text string, customRegex string, leftDelimiter string, rightDelimiter string) (string, error)

ExtractEncodedPayload extracts an encoded payload from given text input using specified delimiters.

If not provided, a default regular expression for the 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 encoded and will need to be decoded and then decompressed before the original content is accessible.

func StateLabelToExitCode added in v0.15.0

func StateLabelToExitCode(label string) int

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

type ErrorAnnotationMappings map[error]string

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

func (p *Plugin) AddError(errs ...error)

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

func (p *Plugin) AddPayloadBytes(input []byte) (int, error)

AddPayloadBytes appends the given input in bytes to the payload buffer. It returns the length of input and a potential error. Empty input is silently ignored.

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

func (p *Plugin) AddPayloadString(input string) (int, error)

AddPayloadString appends the given input string to the payload buffer. It returns the length of input and a potential error. Empty input is silently ignored.

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

func (p *Plugin) AddUniqueError(errs ...error)

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) DebugLoggingDisableActions added in v0.17.0

func (p *Plugin) DebugLoggingDisableActions()

DebugLoggingDisableActions disables debug logging of general "actions" or plugin activity. This is the most verbose debug logging output generated by this library.

func (*Plugin) DebugLoggingDisableAll added in v0.17.0

func (p *Plugin) DebugLoggingDisableAll()

DebugLoggingDisableAll changes the default state of all debug logging options for this library from any custom state back to the default state of disabled.

Any custom debug log output target remains as it was before calling this function.

func (*Plugin) DebugLoggingDisablePluginOutputSize added in v0.17.0

func (p *Plugin) DebugLoggingDisablePluginOutputSize()

DebugLoggingDisablePluginOutputSize disables debug logging of plugin output size calculations.

func (*Plugin) DebugLoggingEnableActions added in v0.17.0

func (p *Plugin) DebugLoggingEnableActions()

DebugLoggingEnableActions enables debug logging of general "actions" or plugin activity. This is the most verbose debug logging output generated by this library.

Once enabled, debug logging output is emitted to os.Stderr. This can be overridden by explicitly setting a custom debug output target.

func (*Plugin) DebugLoggingEnableAll added in v0.17.0

func (p *Plugin) DebugLoggingEnableAll()

DebugLoggingEnableAll changes the default state of all debug logging options for this library from disabled to enabled.

Once enabled, debug logging output is emitted to os.Stderr. This can be overridden by explicitly setting a custom debug output target.

func (*Plugin) DebugLoggingEnablePluginOutputSize added in v0.17.0

func (p *Plugin) DebugLoggingEnablePluginOutputSize()

DebugLoggingEnablePluginOutputSize enables debug logging of plugin output size calculations. This debug logging output produces minimal output.

Once enabled, debug logging output is emitted to os.Stderr. This can be overridden by explicitly setting a custom debug output target.

func (*Plugin) DebugLoggingOutputTarget added in v0.17.0

func (p *Plugin) DebugLoggingOutputTarget() io.Writer

DebugLoggingOutputTarget returns the user-specified debug output target or the default value if one was not specified.

func (*Plugin) EnablePluginOutputSizePerfDataMetric added in v0.19.0

func (p *Plugin) EnablePluginOutputSizePerfDataMetric()

EnablePluginOutputSizePerfDataMetric appends a performance data metric noting the total plugin output size.

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) OutputTarget added in v0.17.0

func (p *Plugin) OutputTarget() io.Writer

OutputTarget returns the user-specified plugin output target or the default value if one was not specified.

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) SetDebugLoggingOutputTarget added in v0.17.0

func (p *Plugin) SetDebugLoggingOutputTarget(w io.Writer)

SetDebugLoggingOutputTarget overrides the current debug logging target with the given output target. If the given output target is not valid the current target will be used instead. If there isn't a debug logging target already set then the default debug logging output target of os.Stderr will be used. This behavior is chosen for consistency with the current behavior of the Plugin.SetOutputTarget function.

NOTE: While an error message is logged when calling this function with an invalid target, calling this function does not change the default debug logging state from disabled to enabled. That step must be performed separately by either enabling all debug logging options OR enabling select debug logging options.

func (*Plugin) SetDetailedInfoLabel added in v0.12.0

func (p *Plugin) SetDetailedInfoLabel(newLabel string)

SetDetailedInfoLabel overrides the default detailed info label text.

func (*Plugin) SetEncodedPayloadDelimiterLeft added in v0.17.0

func (p *Plugin) SetEncodedPayloadDelimiterLeft(delimiter string)

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

func (p *Plugin) SetEncodedPayloadDelimiterRight(delimiter string)

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

func (p *Plugin) SetEncodedPayloadLabel(newLabel string)

SetEncodedPayloadLabel overrides the default encoded payload label text.

func (*Plugin) SetErrorsLabel added in v0.12.0

func (p *Plugin) SetErrorsLabel(newLabel string)

SetErrorsLabel overrides the default errors label text.

func (*Plugin) SetOutputTarget added in v0.12.0

func (p *Plugin) SetOutputTarget(w io.Writer)

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

func (p *Plugin) SetPayloadBytes(input []byte) (int, error)

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. If given empty input the payload buffer is reset without adding any content.

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

func (p *Plugin) SetPayloadString(input string) (int, error)

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. If given empty input the payload buffer is reset without adding any content.

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

func (p *Plugin) SetThresholdsLabel(newLabel string)

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

func (p *Plugin) UnencodedPayload() string

UnencodedPayload returns the payload buffer contents in string format as-is without encoding applied. If the payload buffer is empty an empty string is returned.

type Range added in v0.13.0

type Range struct {
	StartInfinity bool
	EndInfinity   bool
	AlertOn       string
	Start         float64
	End           float64
}

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

func ParseRangeString(input string) *Range

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

func (r Range) CheckRange(value string) bool

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.

Directories

Path Synopsis
cmd
testoutput
Small test client app to prototype library changes and assist with updating testdata input files.
Small test client app to prototype library changes and assist with updating testdata input files.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL