monitoringplugin

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2024 License: BSD-2-Clause Imports: 9 Imported by: 3

README

go-monitoringplugin

Go Go Reference

Description

Golang package for writing monitoring check plugins for nagios, icinga2, zabbix, checkmk, etc.

The package complies with the Monitoring Plugins Development Guidelines.

Example / Usage

package main

import "github.com/inexio/go-monitoringplugin/v2"

func main() {
	// Creating response with a default ok message, that will be displayed when
	// the checks exits with status ok.
	response := monitoringplugin.NewResponse("everything checked!")

	// Set output delimiter (default is \n)
	// response.SetOutputDelimiter(" / ")

	// Updating check plugin status and adding message to the output (status only
	// changes if the new status is worse than the current one).

	// check status stays ok
	response.UpdateStatus(monitoringplugin.OK, "something is ok!")
	// check status updates to critical
	response.UpdateStatus(monitoringplugin.CRITICAL,
		"something else is critical!")
	// check status stays critical, but message will be added to the output
	response.UpdateStatus(monitoringplugin.WARNING, "something else is warning!")

	// adding performance data
	p1 := monitoringplugin.NewPerformanceDataPoint("response_time", 10).
		SetUnit("s").SetMin(0)
	p1.NewThresholds(0, 10, 0, 20)
	if err := response.AddPerformanceDataPoint(p1); err != nil {
		// error handling
	}

	p2 := monitoringplugin.NewPerformanceDataPoint("memory_usage", 50.6).
		SetUnit("%").SetMin(0).SetMax(100)
	p2.NewThresholds(0, 80, 0, 90)
	if err := response.AddPerformanceDataPoint(p2); err != nil {
		// error handling
	}

	err = response.AddPerformanceDataPoint(
		monitoringplugin.NewPerformanceDataPoint("memory_usage", 50.6).
			SetUnit("%").SetMin(0).SetMax(100).
			SetThresholds(monitoringplugin.NewThresholds(0, 80.0, 0, 90.0)))
	if err != nil {
		// error handling
	}

	response.OutputAndExit()
	/* exits program with exit code 2 and outputs:
	CRITICAL: something is ok!
	something else is critical!
	something else is warning! | 'response_time'=10s;10;20;0; 'memory_usage'=50%;80;90;0;100
	*/
}

Documentation

Overview

Package monitoringplugin provides types for writing monitoring check plugins for nagios, icinga2, zabbix, etc.

Example (BasicUsage)
// Creating response with a default ok message, that will be displayed when
// the checks exits with status ok.
response := monitoringplugin.NewResponse("everything checked!")

// Set output delimiter (default is \n)
// response.SetOutputDelimiter(" / ")

// Updating check plugin status and adding message to the output (status only
// changes if the new status is worse than the current one).

// check status stays ok
response.UpdateStatus(monitoringplugin.OK, "something is ok!")
// check status updates to critical
response.UpdateStatus(monitoringplugin.CRITICAL,
	"something else is critical!")
// check status stays critical, but message will be added to the output
response.UpdateStatus(monitoringplugin.WARNING, "something else is warning!")

// adding performance data
p1 := monitoringplugin.NewPerformanceDataPoint("response_time", 10).
	SetUnit("s").SetMin(0)
p1.NewThresholds(0, 10, 0, 20)
if err := response.AddPerformanceDataPoint(p1); err != nil {
	// error handling
}

p2 := monitoringplugin.NewPerformanceDataPoint("memory_usage", 50.6).
	SetUnit("%").SetMin(0).SetMax(100)
p2.NewThresholds(0, 80, 0, 90)
if err := response.AddPerformanceDataPoint(p2); err != nil {
	// error handling
}

fmt.Println(response.GetInfo().RawOutput)
Output:

CRITICAL: something else is critical!
something else is warning!
something is ok! | 'response_time'=10s;10;20;0; 'memory_usage'=50.6%;80;90;0;100

Index

Examples

Constants

View Source
const (
	OK       = iota // OK check plugin status = OK
	WARNING         // WARNING check plugin status = WARNING
	CRITICAL        // CRITICAL check plugin status = CRITICAL
	UNKNOWN         // UNKNOWN check plugin status = UNKNOWN
)

Variables

This section is empty.

Functions

func StatusCode2Text

func StatusCode2Text(statusCode int) string

StatusCode2Text is used to map the status code to a string.

func String2StatusCode

func String2StatusCode(s string) int

String2StatusCode returns the status code for a string. OK -> 1, WARNING -> 2, CRITICAL -> 3, UNKNOWN and everything else -> 4 (case insensitive)

Types

type InvalidCharacterBehavior

type InvalidCharacterBehavior int

InvalidCharacterBehavior specifies how the monitoringplugin should behave if an invalid character is found in the output message. Does not affect invalid characters in the performance data.

const (
	// InvalidCharacterRemove removes invalid character in the output message.
	InvalidCharacterRemove InvalidCharacterBehavior = iota + 1
	// InvalidCharacterReplace replaces invalid character in the output message
	// with another character. Only valid if replace character is set
	InvalidCharacterReplace
	// InvalidCharacterRemoveMessage removes the message with the invalid
	// character. StatusCode of the message will still be set.
	InvalidCharacterRemoveMessage
	// InvalidCharacterReplaceWithError replaces the whole message with an error
	// message if an invalid character is found.
	InvalidCharacterReplaceWithError
	// InvalidCharacterReplaceWithErrorAndSetUNKNOWN replaces the whole message
	// with an error message if an invalid character is found. Also sets the
	// status code to UNKNOWN.
	InvalidCharacterReplaceWithErrorAndSetUNKNOWN
)

type OutputMessage

type OutputMessage struct {
	Status  int    `yaml:"status" json:"status" xml:"status"`
	Message string `yaml:"message" json:"message" xml:"message"`
}

OutputMessage represents a message of the response. It contains a message and a status code.

type PerformanceDataPoint

type PerformanceDataPoint[T cmp.Ordered] struct {
	Metric     string        `json:"metric" xml:"metric"`
	Label      string        `json:"label" xml:"label"`
	Value      T             `json:"value" xml:"value"`
	Unit       string        `json:"unit" xml:"unit"`
	Thresholds Thresholds[T] `json:"thresholds" xml:"thresholds"`
	Min        T             `json:"min" xml:"min"`
	Max        T             `json:"max" xml:"max"`
	// contains filtered or unexported fields
}

PerformanceDataPoint contains all information of one PerformanceDataPoint.

func NewPerformanceDataPoint

func NewPerformanceDataPoint[T cmp.Ordered](metric string, value T,
) *PerformanceDataPoint[T]

NewPerformanceDataPoint creates a new PerformanceDataPoint. Metric and value are mandatory but are not checked at this point, the performanceDatePoint's validation is checked later when it is added to the performanceData list in the function performanceData.add(*PerformanceDataPoint).

It is possible to directly add thresholds, min and max values with the functions SetThresholds(Thresholds), SetMin(int) and SetMax(int).

Usage:

PerformanceDataPoint := NewPerformanceDataPoint("memory_usage", 55).SetUnit("%")

func (*PerformanceDataPoint[T]) CheckThresholds

func (p *PerformanceDataPoint[T]) CheckThresholds() int

CheckThresholds checks if [Value] is violating the thresholds. See Thresholds.CheckValue.

func (*PerformanceDataPoint[T]) HasThresholds

func (p *PerformanceDataPoint[T]) HasThresholds() bool

HasThresholds checks if the thresholds are not empty.

func (*PerformanceDataPoint[T]) Name

func (p *PerformanceDataPoint[T]) Name() string

Name returns a human-readable name suitable for Response.UpdateStatus.

func (*PerformanceDataPoint[T]) NewThresholds

func (p *PerformanceDataPoint[T]) NewThresholds(warningMin, warningMax,
	criticalMin, criticalMax T,
) *Thresholds[T]

NewThresholds is a wrapper, which creates NewThresholds with same type as [Value], [SetThresholds] it and returns pointer to Thresholds.

func (*PerformanceDataPoint[T]) SetLabel

func (p *PerformanceDataPoint[T]) SetLabel(label string,
) *PerformanceDataPoint[T]

SetLabel adds a tag to the performance data point If one tag is added more than once, the value before will be overwritten

func (*PerformanceDataPoint[T]) SetMax

func (p *PerformanceDataPoint[T]) SetMax(max T) *PerformanceDataPoint[T]

SetMax sets maximum value.

func (*PerformanceDataPoint[T]) SetMin

func (p *PerformanceDataPoint[T]) SetMin(min T) *PerformanceDataPoint[T]

SetMin sets minimum value.

func (*PerformanceDataPoint[T]) SetThresholds

func (p *PerformanceDataPoint[T]) SetThresholds(thresholds Thresholds[T],
) *PerformanceDataPoint[T]

SetThresholds sets the thresholds for the performance data point

func (*PerformanceDataPoint[T]) SetUnit

func (p *PerformanceDataPoint[T]) SetUnit(unit string) *PerformanceDataPoint[T]

SetUnit sets the unit of the performance data point

func (*PerformanceDataPoint[T]) Validate

func (p *PerformanceDataPoint[T]) Validate() error

Validate validates a PerformanceDataPoint. This function is used to check if a PerformanceDataPoint is compatible with the documentation from [Monitoring Plugins Development Guidelines](https://www.monitoring-plugins.org/doc/guidelines.html) (valid name and unit, value is inside the range of min and max etc.)

type Response

type Response struct {
	// contains filtered or unexported fields
}

Response is the main type that is responsible for the check plugin Response. It stores the current status code, output messages, performance data and the output message delimiter.

func NewResponse

func NewResponse(defaultOkMessage string) *Response

NewResponse creates a new Response and sets the default OK message to the given string. The default OK message will be displayed together with the other output messages, but only if the status is still OK when the check exits.

func (*Response) AddPerformanceDataPoint

func (r *Response) AddPerformanceDataPoint(point anyDataPoint) error

AddPerformanceDataPoint adds a PerformanceDataPoint to the performanceData map, using performanceData.add(*PerformanceDataPoint).

Usage:

err := Response.AddPerformanceDataPoint(NewPerformanceDataPoint("temperature", 32, "°C").SetWarn(35).SetCrit(40))
if err != nil {
	...
}

func (*Response) CheckThresholds

func (r *Response) CheckThresholds(point anyDataPoint)

CheckThresholds checks if the value exceeds the given thresholds and updates the response.

func (*Response) GetInfo

func (r *Response) GetInfo() ResponseInfo

GetInfo returns all information for a response.

func (*Response) GetStatusCode

func (r *Response) GetStatusCode() int

GetStatusCode returns the current status code.

func (*Response) OutputAndExit

func (r *Response) OutputAndExit()

OutputAndExit generates the output string and prints it to stdout. After that the check plugin exits with the current exit code.

Example:

Response := NewResponse("everything checked!")
defer Response.OutputAndExit()

//check plugin logic...

func (*Response) OutputDelimiterMultiline

func (r *Response) OutputDelimiterMultiline()

OutputDelimiterMultiline sets the outputDelimiter to "\n". See Response.SetOutputDelimiter

func (*Response) PrintPerformanceData

func (r *Response) PrintPerformanceData(b bool)

PrintPerformanceData activates or deactivates printing performance data.

func (*Response) SetInvalidCharacterBehavior

func (r *Response) SetInvalidCharacterBehavior(
	behavior InvalidCharacterBehavior, replaceCharacter string,
) error

SetInvalidCharacterBehavior sets the desired behavior if an invalid character is found in a message. Default is InvalidCharacterRemove. replaceCharacter is only necessary if InvalidCharacterReplace is set.

func (*Response) SetOutputDelimiter

func (r *Response) SetOutputDelimiter(delimiter string)

SetOutputDelimiter is used to set the delimiter that is used to separate the outputMessages that will be displayed when the check plugin exits. The default value is a linebreak (\n). It can be set to any string.

Example:

Response.SetOutputDelimiter(" / ")
//this results in the output having the following format:
//OK: defaultOkMessage / outputMessage1 / outputMessage2 / outputMessage3 | performanceData

func (*Response) SetPerformanceDataJSONLabel

func (r *Response) SetPerformanceDataJSONLabel(jsonLabel bool)

SetPerformanceDataJSONLabel updates the JSON metric.

func (*Response) SortOutputMessagesByStatus

func (r *Response) SortOutputMessagesByStatus(b bool)

SortOutputMessagesByStatus sorts the output messages according to their status.

func (*Response) UpdateStatus

func (r *Response) UpdateStatus(statusCode int, statusMessage string)

UpdateStatus updates the exit status of the Response and adds a statusMessage to the outputMessages that will be displayed when the check exits. See updateStatusCode(int) for a detailed description of the algorithm that is used to update the status code.

func (*Response) UpdateStatusIf

func (r *Response) UpdateStatusIf(condition bool, statusCode int,
	statusMessage string,
) bool

UpdateStatusIf calls UpdateStatus(statusCode, statusMessage) if the given condition is true.

func (*Response) UpdateStatusIfNot

func (r *Response) UpdateStatusIfNot(condition bool, statusCode int,
	statusMessage string,
) bool

UpdateStatusIfNot calls UpdateStatus(statusCode, statusMessage) if the given condition is false.

func (*Response) UpdateStatusOnError

func (r *Response) UpdateStatusOnError(err error, statusCode int,
	statusMessage string, includeErrorMessage bool,
) bool

UpdateStatusOnError calls UpdateStatus(statusCode, statusMessage) if the given error is not nil.

func (*Response) WithDefaultOkMessage

func (r *Response) WithDefaultOkMessage(defaultOkMessage string) *Response

WithDefaultOkMessage changes the default OK message, see NewResponse.

type ResponseInfo

type ResponseInfo struct {
	StatusCode      int             `yaml:"status_code" json:"status_code" xml:"status_code"`
	PerformanceData []anyDataPoint  `yaml:"performance_data" json:"performance_data" xml:"performance_data"`
	RawOutput       string          `yaml:"raw_output" json:"raw_output" xml:"raw_output"`
	Messages        []OutputMessage `yaml:"messages" json:"messages" xml:"messages"`
}

ResponseInfo has all available information for a response. It also contains the RawOutput.

type Thresholds

type Thresholds[T cmp.Ordered] struct {
	WarningMin  T `json:"warningMin" xml:"warningMin"`
	WarningMax  T `json:"warningMax" xml:"warningMax"`
	CriticalMin T `json:"criticalMin" xml:"criticalMin"`
	CriticalMax T `json:"criticalMax" xml:"criticalMax"`
	// contains filtered or unexported fields
}

Thresholds contains all threshold values.

func NewThresholds

func NewThresholds[T cmp.Ordered](warningMin, warningMax, criticalMin,
	criticalMax T,
) Thresholds[T]

NewThresholds creates a new threshold.

func (*Thresholds[T]) CheckValue

func (c *Thresholds[T]) CheckValue(value T) int

CheckValue checks if the input is violating the thresholds.

func (*Thresholds[T]) HasCritical

func (c *Thresholds[T]) HasCritical() bool

HasCritical checks if a critical threshold is set.

func (*Thresholds[T]) HasWarning

func (c *Thresholds[T]) HasWarning() bool

HasWarning checks if a warning threshold is set.

func (*Thresholds[T]) IsEmpty

func (c *Thresholds[T]) IsEmpty() bool

IsEmpty checks if the thresholds are empty.

func (*Thresholds[T]) UseCritical

func (c *Thresholds[T]) UseCritical(useMin, useMax bool) *Thresholds[T]

UseCritical configures how to use CriticalMin and CriticalMax.

func (*Thresholds[T]) UseWarning

func (c *Thresholds[T]) UseWarning(useMin, useMax bool) *Thresholds[T]

UseWarning configures how to use WarningMin and WarningMax.

func (*Thresholds[T]) Validate

func (c *Thresholds[T]) Validate() error

Validate checks if the Thresholds contains some invalid combination of warning and critical values.

Jump to

Keyboard shortcuts

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