Core API

The core API consists of all functions and classes which are called in a plugin’s main function. A typical main function is decorated with guarded() and creates a Check object. The check instance is fed with instances of Resource, Context, or Summary (respective custom subclasses). Finally, control is passed to the check’s main() method.

Note

All classes that plugin authors typically need are imported into the nagiosplugin name space. For example, use

import nagiosplugin
# ...
check = nagiosplugin.Check()

to get a Check instance.

nagiosplugin.check

Controller logic for check execution.

This module contains the Check class which orchestrates the the various stages of check execution. Interfacing with the outside system is done via a separate Runtime object.

When a check is called (using Check.main() or Check.__call__()), it probes all resources and evaluates the returned metrics to results and performance data. A typical usage pattern would be to populate a check with domain objects and then delegate control to it.

class nagiosplugin.check.Check(*objects)

Creates and configures a check.

Specialized objects representing resources, contexts, summary, or results are passed to the the add() method. Alternatively, objects can be added later manually.

__call__()

Actually run the check.

After a check has been called, the results and perfdata attributes are populated with the outcomes. In most cases, you should not use __call__ directly but invoke main(), which delegates check execution to the Runtime environment.

name

Short name which is used to prefix the check’s status output (as commonly found in plugins shipped with Nagios). It defaults to the uppercased class name of the first resource added. However, plugin authors may override this by assigning an user-defined name. If this attribute is None, status output will not be prefixed with a check name.

results

Results container that allows accessing the Result objects generated during the evaluation.

add(*objects)

Adds domain objects to a check.

Parameters:objects – one or more objects that are descendants from Resource, Context, Summary, or Results.
main(verbose=None, timeout=None)

All-in-one control delegation to the runtime environment.

Get a Runtime instance and perform all phases: run the check (via __call__()), print results and exit the program with an appropriate status code.

Parameters:
  • verbose – output verbosity level between 0 and 3
  • timeout – abort check execution with a Timeout exception after so many seconds (use 0 for no timeout)
exitcode

Overall check exit code according to the Nagios API.

Corresponds with state. Read-only property.

state

Overall check state.

The most significant (=worst) state seen in results to far. Unknown if no results have been collected yet. Corresponds with exitcode. Read-only property.

summary_str

Status line summary string.

The first line of output that summarizes that situation as perceived by the check. The string is usually queried from a Summary object. Read-only property.

verbose_str

Additional lines of output.

Long text output if check runs in verbose mode. Also queried from Summary. Read-only property.

Example: Skeleton main function

The following pseudo code outlines how Check is typically used in the main function of a plugin:

def main():
   check = nagiosplugin.Check(MyResource1(...), MyResource2(...),
                              MyContext1(...), MyContext2(...),
                              MySummary(...))
   check.main()

nagiosplugin.resource

Domain model for data acquisition.

Resource is the base class for the plugin’s domain model. It shoul model the relevant details of reality that a plugin is supposed to check. The Check controller calls Resource.probe() on all passed resource objects to acquire data.

Plugin authors should subclass Resource and write whatever methods are needed to get the interesting bits of information. The most important resource subclass should be named after the plugin itself.

class nagiosplugin.resource.Resource

Abstract base class for custom domain models.

Subclasses may add arguments to the constructor to parametrize information retrieval.

probe()

Query system state and return metrics.

This is the only method called by the check controller. It should trigger all necessary actions and create metrics.

Returns:list of Metric objects, or generator that emits Metric objects, or single Metric object

nagiosplugin.context

Metadata about metrics to perform data evaluation.

This module contains the Context class, which is the base for all contexts. ScalarContext is an important specialization to cover numeric contexts with warning and critical thresholds. The Check controller selects a context for each Metric by matching the metric’s context attribute with the context’s name. The same context may be used for several metrics.

Plugin authors may just use to ScalarContext in the majority of cases. Sometimes is better to subclass Context instead to implement custom evaluation or performance data logic.

class nagiosplugin.context.Context(name, fmt_metric=None, result_cls=<class 'nagiosplugin.result.Result'>)

Creates generic context identified by name.

Generic contexts just format associated metrics and evaluate always to Ok. Metric formatting is controlled with the fmt_metric attribute. It can either be a string or a callable. See the describe() method for how formatting is done.

Parameters:
  • name – context name that is matched by the context attribute of Metric
  • fmt_metric – string or callable to convert context and associated metric to a human readable string
  • result_cls – use this class (usually a Result subclass) to represent the evaluation outcome
describe(metric)

Provides human-readable metric description.

Formats the metric according to the fmt_metric attribute. If fmt_metric is a string, it is evaluated as format string with all metric attributes in the root namespace. If fmt_metric is callable, it is called with the metric and this context as arguments. If fmt_metric is not set, this default implementation does not return a description.

Plugin authors may override this method in subclasses to control text output more tightly.

Parameters:metric – associated metric
Returns:description string or None
evaluate(metric, resource)

Determines state of a given metric.

This base implementation returns Ok in all cases. Plugin authors may override this method in subclasses to specialize behaviour.

Parameters:
  • metric – associated metric that is to be evaluated
  • resource – resource that produced the associated metric (may optionally be consulted)
Returns:

Result or ServiceState object

performance(metric, resource)

Derives performance data from a given metric.

This base implementation just returns none. Plugin authors may override this method in subclass to specialize behaviour.

Parameters:
  • metric – associated metric from which performance data are derived
  • resource – resource that produced the associated metric (may optionally be consulted)
Returns:

Perfdata object or None

class nagiosplugin.context.ScalarContext(name, warning=None, critical=None, fmt_metric='{name} is {valueunit}', result_cls=<class 'nagiosplugin.result.Result'>)

Ready-to-use Context subclass for scalar values.

ScalarContext models the common case where a single scalar is to be evaluated against a pair of warning and critical thresholds.

name, fmt_metric, and result_cls, are described in the Context base class.

Parameters:
  • warning – Warning threshold as Range object or range string.
  • critical – Critical threshold as Range object or range string.
evaluate(metric, resource)

Compares metric with ranges and determines result state.

The metric’s value is compared to the instance’s warning and critical ranges, yielding an appropropiate state depending on how the metric fits in the ranges. Plugin authors may override this method in subclasses to provide custom evaluation logic.

Parameters:
  • metric – metric that is to be evaluated
  • resource – not used
Returns:

Result object

performance(metric, resource)

Derives performance data.

The metric’s attributes are combined with the local warning and critical ranges to get a fully populated Performance object.

Parameters:
  • metric – metric from which performance data are derived
  • resource – not used
Returns:

Performance object

Example ScalarContext usage

Configure a ScalarContext with warning and critical ranges found in ArgumentParser’s result object args and add it to a check:

c = Check(..., ScalarContext('metric', args.warning, args.critical), ...)

nagiosplugin.summary

Create status line from results.

This module contains the Summary class which serves as base class to get a status line from the check’s Results. A Summary object is used by Check to obtain a suitable data presentation depending on the check’s overall state.

Plugin authors may either stick to the default implementation or subclass it to adapt it to the check’s domain. The status line is probably the most important piece of text returned from a check: It must lead directly to the problem in the most concise way. So while the default implementation is quite usable, plugin authors should consider subclassing to provide a specific implementation that gets the output to the point.

class nagiosplugin.summary.Summary

Creates a summary formtter object.

This base class takes no parameters in its constructor, but subclasses may provide more elaborate constructors that accept parameters to influence output creation.

empty()

Formats status line when the result set is empty.

Returns:status line
ok(results)

Formats status line when overall state is ok.

The default implementation returns a string representation of the first result.

Parameters:resultsResults container
Returns:status line
problem(results)

Formats status line when overall state is not ok.

The default implementation returns a string representation of te first significant result, i.e. the result with the “worst” state.

Parameters:resultsResults container
Returns:status line
verbose(results)

Provides extra lines if verbose plugin execution is requested.

The default implementation returns a list of all resources that are in a non-ok state.

Parameters:resultsResults container
Returns:list of strings

nagiosplugin.runtime

Functions and classes to interface with the system.

This module contains the Runtime class that handles exceptions, timeouts and logging. Plugin authors should not use Runtime directly, but decorate the plugin’s main function with guarded().

nagiosplugin.runtime.guarded(*args, verbose=None)

Runs a function nagiosplugin’s Runtime environment.

guarded makes the decorated function behave correctly with respect to the Nagios plugin API if it aborts with an uncaught exception or a timeout. It exits with an unknown exit code and prints a traceback in a format acceptable by Nagios.

This function should be used as a decorator for the script’s main function.

Parameters:verbose – Optional keyword parameter to control verbosity level during early execution (before main() has been called). For example, use @guarded(verbose=0) to turn tracebacks in that phase off.