check

package module
v0.5.0-rc1 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2023 License: GPL-2.0 Imports: 12 Imported by: 26

README

go-check

GitHub release (latest by date) GoDoc Test Status GitHub go.mod Go version GitHub

go-check is a library to help with development of monitoring plugins for tools like Icinga.

See the documentation on pkg.go.dev for more details and examples.

Usage

Simple Example

package main

import (
	"github.com/NETWAYS/go-check"
)

func main() {
	config := check.NewConfig()
	config.Name = "check_test"
	config.Readme = `Test Plugin`
	config.Version = "1.0.0"

	_ = config.FlagSet.StringP("hostname", "H", "localhost", "Hostname to check")

	config.ParseArguments()

	// Some checking should be done here, when --help is not passed
	check.Exitf(check.OK, "Everything is fine - answer=%d", 42)
    // Output:
    // OK - Everything is fine - answer=42
}

Exit Codes

check.Exitf(OK, "Everything is fine - value=%d", 42) // OK, 0

check.ExitRaw(check.Critical, "CRITICAL", "|", "percent_packet_loss=100") // CRITICAL, 2

err := fmt.Errorf("connection to %s has been timed out", "localhost:12345")

check.ExitError(err) // UNKNOWN, 3

Timeout Handling

checkPluginTimeoutInSeconds := 10
go check.HandleTimeout(checkPluginTimeoutInSeconds)

Thresholds

warnThreshold, err := check.ParseThreshold("~:3")

if err != nil {
    return t, err
}

if warnThreshold.DoesViolate(3.6) {
    fmt.Println("Not great, not terrible.")
}

Perfdata

var pl perfdata.PerfdataList

pl.Add(&perfdata.Perfdata{
    Label: "process.cpu.percent",
    Value: 25,
    Uom:   "%",
    Warn:  50,
    Crit:  90,
    Min:   0,
    Max:   100})

fmt.Println(pl.String())

Results

allStates = []int{0,2,3,0,1,2}

switch result.WorstState(allStates...) {
case 0:
    rc = check.OK
case 1:
    rc = check.Warning
case 2:
    rc = check.Critical
default:
    rc = check.Unknown
}

Partial Results

o := Overall{}
o.Add(0, "Something is OK")

pr := PartialResult{
    State:  check.OK,
    Output: "My Subcheck",
}

o.AddSubcheck(pr)

fmt.Println(o.GetOutput())

// states: ok=1
// [OK] Something is OK
// \_ [OK] My Subcheck

Examples

A few plugins using go-check:

License

Copyright (c) 2020 NETWAYS GmbH

This library is distributed under the GPL-2.0 or newer license found in the COPYING file.

Documentation

Index

Examples

Constants

View Source
const (
	// OK means everything is fine
	OK = 0
	// Warning means there is a problem the admin should review
	Warning = 1
	// Critical means there is a problem that requires immediate action
	Critical = 2
	// Unknown means the status can not be determined, probably due to an error or something missing
	Unknown = 3
)

Variables

View Source
var (
	PosInf = math.Inf(1)
	NegInf = math.Inf(-1)
)
View Source
var AllowExit = true

AllowExit lets you disable the call to os.Exit() in ExitXxx() functions of this package.

This should be used carefully and most likely only for testing.

View Source
var PrintStack = true

PrintStack prints the error stack when recovering from a panic with CatchPanic()

Functions

func BaseExit

func BaseExit(rc int)

func BoundaryToString

func BoundaryToString(value float64) (s string)

BoundaryToString returns the string representation of a Threshold boundary.

func CatchPanic

func CatchPanic()

CatchPanic is a general function for defer, to capture any panic that occurred during runtime of a check

The function will recover from the condition and exit with a proper UNKNOWN status, while showing error and the call stack.

Example
defer CatchPanic()

panic("something bad happened")
Output:

[UNKNOWN] - Golang encountered a panic: something bad happened
would exit with code 3

func ExitError

func ExitError(err error)

ExitError exists with an Unknown state while reporting the error

Example
err := fmt.Errorf("connection to %s has been timed out", "localhost:12345")
ExitError(err)
Output:

[UNKNOWN] - connection to localhost:12345 has been timed out (*errors.errorString)
would exit with code 3

func ExitRaw added in v0.2.0

func ExitRaw(rc int, output ...string)

ExitRaw prints the plugin output with the state prefixed and exits the program.

Example:

OK - everything is fine
Example
ExitRaw(OK, "Everything is fine")
Output:

[OK] - Everything is fine
would exit with code 0

func Exitf added in v0.2.0

func Exitf(rc int, output string, args ...interface{})

Exitf prints the plugin output using formatting and exits the program.

Output is the formatting string, and the rest of the arguments help adding values.

Also see fmt package: https://golang.org/pkg/fmt

Example
Exitf(OK, "Everything is fine - value=%d", 42)
Output:

[OK] - Everything is fine - value=42
would exit with code 0

func FormatFloat added in v0.3.0

func FormatFloat(value float64) string

FormatFloat returns a string representation of floats, avoiding scientific notation and removes trailing zeros.

func HandleTimeout

func HandleTimeout(timeout int)

Helper for a goroutine, to wait for signals and timeout, and exit with a proper code

func StatusText

func StatusText(status int) string

StatusText returns the string corresponding to a state

Example
fmt.Println(StatusText(OK), StatusText(Warning), StatusText(Critical), StatusText(Unknown))
Output:

OK WARNING CRITICAL UNKNOWN

Types

type Config

type Config struct {
	Name          string
	Readme        string
	Version       string
	Timeout       int
	Verbose       bool
	Debug         bool
	PrintVersion  bool
	DefaultFlags  bool
	DefaultHelper bool
	FlagSet       *flag.FlagSet
}
Example
config := NewConfig()
config.Name = "check_test"
config.Readme = `Test Plugin`
config.Version = "1.0.0"

_ = config.FlagSet.StringP("hostname", "H", "localhost", "Hostname to check")

config.ParseArguments()

// Some checking should be done here

Exitf(OK, "Everything is fine - answer=%d", 42)
Output:

[OK] - Everything is fine - answer=42
would exit with code 0

func NewConfig

func NewConfig() *Config

func (*Config) EnableTimeoutHandler

func (c *Config) EnableTimeoutHandler()

Start the timeout and signal handler in a goroutine

func (*Config) ParseArguments

func (c *Config) ParseArguments()

func (*Config) ParseArray

func (c *Config) ParseArray(arguments []string)

type Threshold

type Threshold struct {
	Inside bool
	Lower  float64
	Upper  float64
}

Defining a threshold for any numeric value

Format: [@]start:end

Threshold Generate an alert if x... 10 < 0 or > 10, (outside the range of {0 .. 10}) 10: < 10, (outside {10 .. ∞}) ~:10 > 10, (outside the range of {-∞ .. 10}) 10:20 < 10 or > 20, (outside the range of {10 .. 20}) @10:20 ≥ 10 and ≤ 20, (inside the range of {10 .. 20})

Reference: https://www.monitoring-plugins.org/doc/guidelines.html#THRESHOLDFORMAT

func ParseThreshold

func ParseThreshold(spec string) (t *Threshold, err error)

Parse a Threshold from a string.

See Threshold for details.

func (Threshold) DoesViolate

func (t Threshold) DoesViolate(value float64) bool

Compares a value against the threshold, and returns true if the value violates the threshold.

func (Threshold) String

func (t Threshold) String() (s string)

String returns the plain representation of the Threshold

Directories

Path Synopsis
examples
check_example command
check_example2 command
result tries to
result tries to

Jump to

Keyboard shortcuts

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