API docs

exception mplugin.CheckError[source]

Bases: RuntimeError

Abort check execution.

This exception should be raised if it becomes clear for a plugin that it is not able to determine the system status. Raising this exception will make the plugin display the exception’s argument and exit with an UNKNOWN (3) status.

exception mplugin.Timeout[source]

Bases: RuntimeError

Maximum check run time exceeded.

This exception is raised internally by mplugin if the check’s run time takes longer than allowed. Check execution is aborted and the plugin exits with an UNKNOWN (3) status.

mplugin.worst(states: list[ServiceState]) ServiceState[source]

Reduce list of states to the most significant state.

class mplugin.ServiceState(code: int, text: str)[source]

Bases: object

Abstract base class for all states.

Each state has two constant attributes: text is the short text representation which is printed for example at the beginning of the summary line. code is the corresponding exit code.

code: int

The Plugin API compliant exit code.

text: str

The short text representation which is printed for example at the beginning of the summary line.

mplugin.ok: ServiceState

The plugin was able to check the service and it appeared to be functioning properly.

mplugin.warning: ServiceState

The plugin was able to check the service, but it appeared to be above some warning threshold or did not appear to be working properly.

mplugin.critical: ServiceState

The plugin detected that either the service was not running or it was above some critical threshold.

mplugin.unknown: ServiceState

Invalid command line arguments were supplied to the plugin or low-level failures internal to the plugin (such as unable to fork, or open a tcp socket) that prevent it from performing the specified operation. Higher-level errors (such as name resolution errors, socket timeouts, etc) are outside of the control of plugins and should generally NOT be reported as unknown states.

The –help or –version output should also result in unknown state.

mplugin.state(exit_code: int) ServiceState[source]

Convert an exit code to a ServiceState.

Parameters:

exit_code – The exit code to convert. Must be 0, 1, 2, or 3.

Returns:

The corresponding ServiceState (ok, warn, critical, or unknown).

Raises:

CheckError – If exit_code is greater than 3.

class mplugin.Range(spec: str | int | float | Range | None = None)[source]

Bases: object

Represents a threshold range.

The general format is [@][start:][end]. start: may be omitted if start==0. ~: means that start is negative infinity. If end is omitted, infinity is assumed. To invert the match condition, prefix the range expression with @.

See the Monitoring plugin guidelines for details.

start: float
end: float
invert: bool
match(value: float) bool[source]

Decides if value is inside/outside the threshold.

Returns:

True if value is inside the bounds for non-inverted Ranges.

Also available as in operator.

property violation: str

Human-readable description why a value does not match.

class mplugin.MultiArg(args: list[str] | str, fill: str | None = None, splitchar: str = ',')[source]

Bases: object

A container class for handling multiple arguments that can be indexed and iterated.

This class is designed to be used as a type converter in argparse for arguments that accept comma-separated or otherwise delimited values. It provides convenient access to individual arguments with optional fill values for missing indices.

argp.add_argument(
    "--tw",
    "--ttot-warning",
    metavar="RANGE[,RANGE,...]",
    type=mplugin.MultiArg,
    default="",
)
Parameters:
  • args – The list of parsed argument strings.

  • fill – An optional default value to return for indices beyond the length of the args list. If not provided, the last argument is returned instead, or None if the list is empty.

  • splitchar

args: list[str]

The list of parsed argument strings.

fill: str | None

An optional default value to return for indices beyond the length of the args list. If not provided, the last argument is returned instead, or None if the list is empty.

class mplugin.Cookie(statefile: str | None = None)[source]

Bases: UserDict[str, Any]

Creates a persistent dict to keep state.

Cookies are used to remember file positions, counters and the like between plugin invocations. It is not intended for substantial amounts of data. Cookies are serialized into JSON and saved to a state file. We prefer a plain text format to allow administrators to inspect and edit its content. See LogTail for an application of cookies to get only new lines of a continuously growing file.

Cookies are locked exclusively so that at most one process at a time has access to it. Changes to the dict are not reflected in the file until Cookie.commit() is called. It is recommended to use Cookie as context manager to get it opened and committed automatically.

After creation, a cookie behaves like a normal dict.

Parameters:

statefile – file name to save the dict’s contents

Note

If statefile is empty or None, the Cookie will be oblivous, i.e., it will forget its contents on garbage collection. This makes it possible to explicitely throw away state between plugin runs (for example by a command line argument).

path: str | None
fobj: TextIOWrapper | None
open() Self[source]

Reads/creates the state file and initializes the dict.

If the state file does not exist, it is touched into existence. An exclusive lock is acquired to ensure serialized access. If open() fails to parse file contents, it truncates the file before raising an exception. This guarantees that plugins will not fail repeatedly when their state files get damaged.

Returns:

Cookie object (self)

Raises:

ValueError – if the state file is corrupted or does not deserialize into a dict

close() None[source]

Closes a cookie and its underlying state file.

This method has no effect if the cookie is already closed. Once the cookie is closed, any operation (like commit()) will raise an exception.

commit() None[source]

Persists the cookie’s dict items in the state file.

The cookies content is serialized as JSON string and saved to the state file. The buffers are flushed to ensure that the new content is saved in a durable way.

class mplugin.LogTail(path: str, cookie: Cookie)[source]

Bases: object

Access previously unseen parts of a growing file.

LogTail builds on Cookie to access new lines of a continuosly growing log file. It should be used as context manager that provides an iterator over new lines to the subordinate context. LogTail saves the last file position into the provided cookie object. As the path to the log file is saved in the cookie, several LogTail instances may share the same cookie.

path: str
cookie: Cookie
logfile: BufferedIOBase | None
stat: stat_result | None
class mplugin.Performance(label: str, value: Any, uom: str | None = None, warn: str | int | float | Range | None = None, crit: str | int | float | Range | None = None, min: float | None = None, max: float | None = None)[source]

Bases: object

Performance data (perfdata) representation.

Performance data are created during metric evaluation in a context and are written into the perfdata section of the plugin’s output. Performance allows the creation of value objects that are passed between other mplugin objects.

For sake of consistency, performance data should represent their values in their respective base unit, so Performance('size', 10000, 'B') is better than Performance('size', 10, 'kB').

See the Monitoring plugin guidelines for details.

label: str

short identifier, results in graph titles for example (20 chars or less recommended)

value: Any

measured value (usually an int, float, or bool)

uom: str | None

unit of measure – use base units whereever possible

warn: str | int | float | Range | None

warning range

crit: str | int | float | Range | None

critical range

min: float | None

known value minimum (None for no minimum)

max: float | None

known value maximum (None for no maximum)

mplugin.guarded(original_function: Any = None, verbose: Any = None) Any[source]

Runs a function mplugin’s Runtime environment.

guarded makes the decorated function behave correctly with respect to the monitoring 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 monitoring solution.

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.

class mplugin.Metric(name: str, value: Any, uom: str | None = None, min: float | None = None, max: float | None = None, context: str | None = None, contextobj: Context | None = None, resource: Resource | None = None)[source]

Bases: object

Single measured value.

This module contains the Metric class whose instances are passed as value objects between most of mplugin’s core classes. Typically, Resource objects emit a list of metrics as result of their probe() methods.

The value should be expressed in terms of base units, so Metric(‘swap’, 10240, ‘B’) is better than Metric(‘swap’, 10, ‘kiB’).

name: str
value: Any
uom: str | None
min: float | None
max: float | None
context: str
contextobj: Context | None
resource: Resource | None
replace(**attr: Unpack[_MetricKwargs]) Self[source]

Creates new instance with updated attributes.

property description: str | None

Human-readable, detailed string representation.

Delegates to the Context to format the value.

Returns:

describe() output or valueunit if no context has been associated yet

property valueunit: str

Compact string representation.

This is just the value and the unit. If the value is a real number, express the value with a limited number of digits to improve readability.

evaluate() Result | ServiceState[source]

Evaluates this instance according to the context.

Returns:

Result object

Raises:

RuntimeError – if no context has been associated yet

performance() Performance | None[source]

Generates performance data according to the context.

Returns:

Performance object

Raises:

RuntimeError – if no context has been associated yet

class mplugin.Resource[source]

Bases: object

Abstract base class for custom domain models.

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.

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

property name: str
probe() list[Metric] | Metric | Generator[Metric, None, None][source]

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.

A plugin can perform several measurements at once.

def probe(self):
    self.users = self.list_users()
    self.unique_users = set(self.users)
    return [
        Metric("total", len(self.users), min=0, context="users"),
        Metric("unique", len(self.unique_users), min=0, context="users"),
    ]

Alternatively, the probe() method can act as generator and yield metrics:

def probe(self):
    self.users = self.list_users()
    self.unique_users = set(self.users)
    yield Metric('total', len(self.users), min=0,
                            context='users')
    yield Metric('unique', len(self.unique_users), min=0,
                            context='users')]
Returns:

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

class mplugin.Result(state: ServiceState, hint: str | None = None, metric: Metric | None = None)[source]

Bases: object

Evaluation outcome consisting of state and explanation.

A Result object is typically emitted by a Context object and represents the outcome of an evaluation. It contains a ServiceState as well as an explanation. Plugin authors may subclass Result to implement specific features.

state: ServiceState
hint: str | None
metric: Metric | None
property resource: Resource | None

Reference to the resource used to generate this result.

property context: Context | None

Reference to the metric used to generate this result.

class mplugin.Results(*results: Result)[source]

Bases: object

Container for result sets.

Basically, this class manages a set of results and provides convenient access methods by index, name, or result state. It is meant to make queries in Summary implementations compact and readable.

The constructor accepts an arbitrary number of result objects and adds them to the container.

results: list[Result]
by_state: dict[ServiceState, list[Result]]
by_name: dict[str, Result]
add(*results: Result) Self[source]

Adds more results to the container.

Besides passing Result objects in the constructor, additional results may be added after creating the container.

Raises:

ValueError – if result is not a Result object

property most_significant_state: ServiceState

The “worst” state found in all results.

Returns:

ServiceState object

Raises:

ValueError – if no results are present

property most_significant: list[Result]

Returns list of results with most significant state.

From all results present, a subset with the “worst” state is selected.

Returns:

list of Result objects or empty list if no results are present

property first_significant: Result

Selects one of the results with most significant state.

Returns:

Result object

Raises:

IndexError – if no results are present

class mplugin.Summary[source]

Bases: object

Creates a summary formatter object.

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

ok(results: Results) str[source]

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: Results) str[source]

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: Results) list[str][source]

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

empty() Literal['no check results'][source]

Formats status line when the result set is empty.

Returns:

status line

class mplugin.Context(name: str, fmt_metric: str | Callable[[Metric, Context], str] | None = None)[source]

Bases: object

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 – A 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

name: str
fmt_metric: str | Callable[[Metric, Context], str] | None
evaluate(metric: Metric, resource: Resource) Result | ServiceState[source]

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

result(state: ServiceState, hint: str | None = None, metric: Metric | None = None) Result[source]

Create a Result object with the given state, hint, and metric.

Parameters:
  • state – The service state for the result.

  • hint – An optional hint message providing additional context.

  • metric – An optional Metric object associated with the result.

Returns:

A Result object containing the provided state, hint, and metric.

ok(hint: str | None = None, metric: Metric | None = None) Result[source]

Create a successful Result.

Parameters:
  • hint – Optional hint message providing additional context about the successful operation.

  • metric – Optional Metric object associated with this result.

Returns:

A Result object representing a successful operation.

warning(hint: str | None = None, metric: Metric | None = None) Result[source]

Create a warning result.

Parameters:
  • hint – Optional hint message to provide additional context for the warning.

  • metric – Optional metric associated with the warning.

Returns:

A Result object representing a warning.

critical(hint: str | None = None, metric: Metric | None = None) Result[source]

Create a critical result.

Parameters:
  • hint – Optional hint message providing additional context about the critical result.

  • metric – Optional metric object associated with this critical result.

Returns:

A Result object representing a critical state.

unknown(hint: str | None = None, metric: Metric | None = None) Result[source]

Create a Result object with an unknown status.

Parameters:
  • hint – Optional hint message providing additional context about why the result is unknown

  • metric – Optional Metric object associated with this result

Returns:

A Result object with unknown status

performance(metric: Metric, resource: Resource) Performance | None[source]

Derives performance data from a given metric.

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

def performance(self, metric: Metric, resource: Resource) -> Performance:
    return Performance(label=metric.name, value=metric.value)
def performance(
    self, metric: Metric, resource: Resource
) -> Performance | None:
    if not opts.performance_data:
        return None
    return Performance(
        metric.name,
        metric.value,
        metric.uom,
        self.warning,
        self.critical,
        metric.min,
        metric.max,
    )
Parameters:
  • metric – associated metric from which performance data are derived

  • resource – resource that produced the associated metric (may optionally be consulted)

Returns:

Performance object or None

describe(metric: Metric) str | None[source]

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

class mplugin.ScalarContext(name: str, warning: str | int | float | Range | None = None, critical: str | int | float | Range | None = None, fmt_metric: str | Callable[[Metric, Context], str] = '{name} is {valueunit}')[source]

Bases: Context

warn_range: Range
critical_range: Range
evaluate(metric: Metric, resource: Resource) Result[source]

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: Metric, resource: Resource) Performance[source]

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

mplugin.log: Logger[source]

mplugin integrates with the logging module from Python’s standard library. If the main function is decorated with guarded() (which is heavily recommended), the logging module gets automatically configured before the execution of the main() function starts. Messages logged to the mplugin logger (or any sublogger) are processed with mplugin’s integrated logging.

The verbosity level is set in the check.main() invocation depending on the number of -v flags.

When called with verbose=0, both the summary and the performance data are printed on one line and the warning message is displayed. Messages logged with warning or error level are always printed. Setting verbose to 1 does not change the logging level but enable multi-line output. Additionally, full tracebacks would be printed in the case of an uncaught exception. Verbosity levels of 2 and 3 enable logging with info or debug levels.

class mplugin.Check(*objects: Resource | Context | Summary | Results, name: str | None = None)[source]

Bases: object

Controller logic for check execution.

The class Check 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.

resources: list[Resource]
contexts: _Contexts
summary: Summary
results: Results
perfdata: list[str]
name: str
add(*objects: Resource | Context | Summary | Results)[source]

Adds domain objects to a check.

Parameters:

objects – one or more objects that are descendants from Resource, Context, Summary, or Results.

main(verbose: Any = None, timeout: Any = None, colorize: bool = False) NoReturn[source]

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)

  • colorize – Use ANSI colors to colorize the logging output

property state: ServiceState

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.

property summary_str: 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.

property verbose_str

Additional lines of output.

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

property exitcode: int

Overall check exit code according to the monitoring API.

Corresponds with state. Read-only property.

mplugin.setup_argparser(name: str | None, version: str | None = None, license: str | None = None, repository: str | None = None, copyright: str | None = None, description: str | None = None, epilog: str | None = None, verbose: bool = False) ArgumentParser[source]

Set up and configure an argument parser for a monitoring plugin according the Monitoring Plugin Guidelines.

This function creates a customized ArgumentParser instance with metadata and formatting suitable for monitoring plugins. It automatically prefixes the plugin name with check_ if not already present.

Parameters:
  • name – The name of the plugin. If provided and doesn’t start with check, it will be prefixed with check_.

  • version – The version number of the plugin. If provided, it will be included in the parser description. In addition, an option -V, --version is provided, which outputs the version number.

  • license – The license type of the plugin. If provided, it will be included in the parser description.

  • repository – The repository URL of the plugin. If provided, it will be included in the parser description.

  • copyright – The copyright information for the plugin. If provided, it will be included in the parser description.

  • description – A detailed description of the plugin’s functionality. If provided, it will be appended to the parser description after a blank line.

  • epilog – Additional information to display after the help message.

  • verbose – Provide a -v, --verbose option. The option can be specified multiple times, e. g. -vvv

Returns:

A configured ArgumentParser instance with RawDescriptionHelpFormatter, 80 character width, and metadata assembled from the provided parameters.

mplugin.timespan(spec: str | int | float) float[source]

Convert a timespan format string to seconds. If no time unit is specified, generally seconds are assumed.

The following time units are understood:

  • years, year, y (defined as 365.25 days)

  • months, month, M (defined as 30.44 days)

  • weeks, week, w

  • days, day, d

  • hours, hour, hr, h

  • minutes, minute, min, m

  • seconds, second, sec, s

  • milliseconds, millisecond, msec, ms

  • microseconds, microsecond, usec, μs, μ, us

This function can be used as type in the argparse.ArgumentParser.add_argument() method.

parser.add_argument(
    "-c",
    "--critical",
    default=5356800,
    help="Interval in seconds for critical state.",
    type=timespan,
)
Parameters:

timespan – The specification of the timespan as a string, for example 2.345s, 3min 45.234s, 34min, 2 months 8 days or as a number.

Returns:

The timespan in seconds

Indices and tables