nagios

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2021 License: MIT Imports: 3 Imported by: 36

README

go-nagios

Shared Golang package for Nagios plugins

Latest Release Go Reference Validate Codebase Validate Docs Lint and Build using Makefile Quick Validation

Table of contents

Status

Alpha quality.

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.

Overview

This package contains common types and package-level variables used when developing Nagios plugins. The intent is to reduce code duplication between various plugins and help reduce typos associated with literal strings.

Features

  • Nagios state constants
    • state labels (e.g., StateOKLabel)
    • state exit codes (e.g., StateOKExitCode)
  • ExitState type with ReturnCheckResults method
    • used to process and return all applicable check results to Nagios for further processing/display
    • supports "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
    • captures panics from client code
      • surfaces these panics as CRITICAL state and overrides service output and error details to make any panics prominent

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

Use only the provided constants

Assuming that you're using Go Modules, add this line to your imports like so:

package main

import (
  "fmt"
  "log"
  "os"

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

Then in your code, reference the data types as you would from any other package:

fmt.Println("OK: All checks have passed")
os.Exit(nagios.StateOKExitCode)

Alternatively, you can also use the provided state "labels" (constants) to avoid using literal string state values:

fmt.Printf("%s: All checks have passed\r\n", nagios.StateOKLabel)
os.Exit(nagios.StateOKExitCode)

When you next build your package this one should be pulled in.

Use ReturnCheckResults method

Assuming that you're using Go Modules, add this line to your imports like so:

package main

import (
  "fmt"
  "log"
  "os"

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

then in your code, create an instance of ExitState and immediately defer ReturnCheckResults(). If you don't, any other deferred functions will not run.

Here we're optimistic and we are going to note that all went well.


    var nagiosExitState = nagios.ExitState{
        LastError:         nil,
        ExitStatusCode:    nagios.StateOKExitCode,
    }

    defer nagiosExitState.ReturnCheckResults()

    // more stuff here

    nagiosExitState.ServiceOutput = certs.OneLineCheckSummary(
        nagios.StateOKLabel,
        certChain,
        certsSummary.Summary,
    )

    nagiosExitState.LongServiceOutput := certs.GenerateCertsReport(
        certChain,
        certsExpireAgeCritical,
        certsExpireAgeWarning,
    )

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.

Use ReturnCheckResults method with a branding callback

Assuming that you're using Go Modules, add this line to your imports like so:

package main

import (
  "fmt"
  "log"
  "os"
  "strings"

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

then 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.

func main() {

    var nagiosExitState = nagios.ExitState{
        LastError:         nil,
        ExitStatusCode:    nagios.StateOKExitCode,
    }

    defer nagiosExitState.ReturnCheckResults()

    // ...

    if config.EmitBranding {
      // If enabled, show application details at end of notification
      nagiosExitState.BrandingCallback = Branding("Notification generated by ")
    }

    // ...

}

the Branding function might look something like this:

// 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.
func Branding(msg string) func() string {
    return func() string {
        return strings.Join([]string{msg, Version()}, "")
    }
}

but you could just as easily create an anonymous function as the callback:

func main() {

    var nagiosExitState = nagios.ExitState{
        LastError:         nil,
        ExitStatusCode:    nagios.StateOKExitCode,
    }

    defer nagiosExitState.ReturnCheckResults()

    if config.EmitBranding {
        // If enabled, show application details at end of notification
        nagiosExitState.BrandingCallback = func(msg string) func() string {
            return func() string {
                return "Notification generated by " + msg
            }
        }("HelloWorld")
    }

    // ...

}

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.

References

Documentation

Overview

Package nagios provides common types and package-level variables for use with Nagios plugins.

OVERVIEW

This package contains common types and package-level variables. The intent is to reduce code duplication between various plugins that we maintain.

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`)

• `ExitState` type with `ReturnCheckResults` method used to process and return all applicable check results to Nagios for further processing/display

HOW TO USE

Assuming that you're using Go Modules (https://blog.golang.org/using-go-modules), add this line to your imports like so:

package main

import (
"fmt"
"log"
"os"

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

Then in your code reference the data types as you would from any other package:

fmt.Println("OK: All checks have passed")
os.Exit(nagios.StateOK)

When you next build your package this one should be pulled in.

See the README for this project for further examples.

Package nagios is a small collection of common types and package-level variables intended for use with various plugins to reduce code duplication.

Index

Constants

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 CheckOutputEOL string = "\r\n"

CheckOutputEOL is the newline used with formatted service and host check output. Based on previous testing, Nagios treats LF newlines within the `$LONGSERVICEOUTPUT$` macro as literal values instead of parsing them for display purposes. Using DOS EOL values with `fmt.Printf()` gives the results that we're looking for with that output and (presumably) host check output as well.

Variables

This section is empty.

Functions

This section is empty.

Types

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 ExitState added in v0.4.0

type ExitState 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").
	LastError 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
}

ExitState represents the last known execution state of the application, including the most recent error and the final intended plugin state.

func (*ExitState) ReturnCheckResults added in v0.4.0

func (es *ExitState) 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.

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.

Jump to

Keyboard shortcuts

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