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
resultsandperfdataattributes are populated with the outcomes. In most cases, you should not use __call__ directly but invokemain(), which delegates check execution to theRuntimeenvironment.
-
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¶ Resultscontainer that allows accessing theResultobjects 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, orResults.
-
main(verbose=None, timeout=None)¶ All-in-one control delegation to the runtime environment.
Get a
Runtimeinstance 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
Timeoutexception 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
resultsto far.Unknownif no results have been collected yet. Corresponds withexitcode. 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
Summaryobject. 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.
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 thefmt_metricattribute. It can either be a string or a callable. See thedescribe()method for how formatting is done.Parameters: -
describe(metric)¶ Provides human-readable metric description.
Formats the metric according to the
fmt_metricattribute. Iffmt_metricis a string, it is evaluated as format string with all metric attributes in the root namespace. Iffmt_metricis callable, it is called with the metric and this context as arguments. Iffmt_metricis 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
Okin 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: ResultorServiceStateobject
-
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: Perfdataobject orNone
-
-
class
nagiosplugin.context.ScalarContext(name, warning=None, critical=None, fmt_metric='{name} is {valueunit}', result_cls=<class 'nagiosplugin.result.Result'>)¶ Ready-to-use
Contextsubclass 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, andresult_cls, are described in theContextbase class.Parameters: -
evaluate(metric, resource)¶ Compares metric with ranges and determines result state.
The metric’s value is compared to the instance’s
warningandcriticalranges, 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: Resultobject
-
performance(metric, resource)¶ Derives performance data.
The metric’s attributes are combined with the local
warningandcriticalranges to get a fully populatedPerformanceobject.Parameters: - metric – metric from which performance data are derived
- resource – not used
Returns: Performanceobject
-
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: results – ResultscontainerReturns: status line
-
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.
guardedmakes 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
mainfunction.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.