API docs
- exception mplugin.CheckError[source]
Bases:
RuntimeErrorAbort 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:
RuntimeErrorMaximum 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:
objectAbstract base class for all states.
Each state has two constant attributes:
textis the short text representation which is printed for example at the beginning of the summary line.codeis the corresponding exit code.
- 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
warningthreshold 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
criticalthreshold.
- 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
unknownstates.The –help or –version output should also result in
unknownstate.
- 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:
objectRepresents a threshold range.
The general format is
[@][start:][end].start:may be omitted ifstart==0.~:means that start is negative infinity. Ifendis omitted, infinity is assumed. To invert the match condition, prefix the range expression with@.See the Monitoring plugin guidelines for details.
- class mplugin.MultiArg(args: list[str] | str, fill: str | None = None, splitchar: str = ',')[source]
Bases:
objectA 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
- class mplugin.Cookie(statefile: str | None = None)[source]
-
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
LogTailfor 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).
- 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
- class mplugin.LogTail(path: str, cookie: Cookie)[source]
Bases:
objectAccess previously unseen parts of a growing file.
LogTail builds on
Cookieto 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.- 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:
objectPerformance 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.
Performanceallows 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 thanPerformance('size', 10, 'kB').See the Monitoring plugin guidelines for details.
- 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:
objectSingle measured value.
This module contains the
Metricclass whose instances are passed as value objects between most of mplugin’s core classes. Typically,Resourceobjects emit a list of metrics as result of theirprobe()methods.The value should be expressed in terms of base units, so Metric(‘swap’, 10240, ‘B’) is better than Metric(‘swap’, 10, ‘kiB’).
- property description: str | None
Human-readable, detailed string representation.
Delegates to the
Contextto format the value.- Returns:
describe()output orvalueunitif 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:
Resultobject- Raises:
RuntimeError – if no context has been associated yet
- performance() Performance | None[source]
Generates performance data according to the context.
- Returns:
Performanceobject- Raises:
RuntimeError – if no context has been associated yet
- class mplugin.Resource[source]
Bases:
objectAbstract base class for custom domain models.
Resourceis the base class for the plugin’s domain model. It shoul model the relevant details of reality that a plugin is supposed to check. TheCheckcontroller callsResource.probe()on all passed resource objects to acquire data.Plugin authors should subclass
Resourceand 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.
- 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')]
- class mplugin.Result(state: ServiceState, hint: str | None = None, metric: Metric | None = None)[source]
Bases:
objectEvaluation outcome consisting of state and explanation.
A Result object is typically emitted by a
Contextobject and represents the outcome of an evaluation. It contains aServiceStateas well as an explanation. Plugin authors may subclass Result to implement specific features.- state: ServiceState
- class mplugin.Results(*results: Result)[source]
Bases:
objectContainer 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
Summaryimplementations compact and readable.The constructor accepts an arbitrary number of result objects and adds them to the container.
- by_state: dict[ServiceState, list[Result]]
- add(*results: Result) Self[source]
Adds more results to the container.
Besides passing
Resultobjects in the constructor, additional results may be added after creating the container.- Raises:
ValueError – if result is not a
Resultobject
- property most_significant_state: ServiceState
The “worst” state found in all results.
- Returns:
ServiceStateobject- 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
Resultobjects or empty list if no results are present
- property first_significant: Result
Selects one of the results with most significant state.
- Returns:
Resultobject- Raises:
IndexError – if no results are present
- class mplugin.Summary[source]
Bases:
objectCreates 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:
results –
Resultscontainer- 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:
results –
Resultscontainer- Returns:
status line
- class mplugin.Context(name: str, fmt_metric: str | Callable[[Metric, Context], str] | None = None)[source]
Bases:
objectCreates 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:
name – A context name that is matched by the context attribute of
Metricfmt_metric – string or callable to convert context and associated metric to a human readable string
- evaluate(metric: Metric, resource: Resource) Result | ServiceState[source]
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
- 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:
Performanceobject or None
- describe(metric: Metric) str | None[source]
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
- 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- 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
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: Metric, resource: Resource) Performance[source]
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
- 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-vflags.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
2and3enable logging with info or debug levels.
- class mplugin.Check(*objects: Resource | Context | Summary | Results, name: str | None = None)[source]
Bases:
objectController logic for check execution.
The class
Checkorchestrates the the various stages of check execution. Interfacing with the outside system is done via a separateRuntimeobject.When a check is called (using
Check.main()orCheck.__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.- contexts: _Contexts
- main(verbose: Any = None, timeout: Any = None, colorize: bool = False) NoReturn[source]
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)colorize – Use ANSI colors to colorize the logging output
- property state: ServiceState
Overall check state.
The most significant (=worst) state seen in
resultsto far.unknownif no results have been collected yet. Corresponds withexitcode. 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
Summaryobject. 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 withcheck_.version – The version number of the plugin. If provided, it will be included in the parser description. In addition, an option
-V,--versionis 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,--verboseoption. 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 as365.25days)months,month,M(defined as30.44days)weeks,week,wdays,day,dhours,hour,hr,hminutes,minute,min,mseconds,second,sec,smilliseconds,millisecond,msec,msmicroseconds,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 daysor as a number.- Returns:
The timespan in seconds