API docs
mplugin
- exception mplugin.CheckError[source]
Bases:
RuntimeErrorAbort check execution.
This exception should be raised if a plugin is unable to determine the system status. Raising this exception will cause the plugin to 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
mpluginif the runtime check takes longer than allowed. The check is aborted and the plugin exits with anUNKNOWN(3) status.
- class mplugin.ServiceState(code: int, text: str)[source]
Bases:
objectAbstract base class for all states.
Each state has two constant attributes:
codeis the corresponding exit code.textis the short text representation which is printed for example at the beginning of the summary line.
- Parameters:
code – The Plugin API compliant exit code. Must be
0,1,2or3.text – The short text representation that is printed, for example, at the beginning of the summary line.
- text: str
The short text representation that is printed, for example, at the beginning of the summary line.
- static worst(states: list[ServiceState]) ServiceState[source]
Reduce list of states to the most significant state.
- static 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,2or3.- Returns:
The corresponding ServiceState (
ok,warn,critical, orunknown).- Raises:
CheckError – If exit_code is greater than 3.
- 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
--helpor--versionoutput should also result inunknownstate.
- class mplugin.Range(spec: str | int | float | Range | None = None, invert: bool | None = None, start: float | None = None, end: float | 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 also
See the Monitoring Plugin Guidelines Repository or the Monitoring Plugins Development Guidelines for details.
- Parameters:
spec – may be either a string, a float, or another Range object.
invert – If the true, the value exceeds the threshold if it is INSIDE the range between start and end (including the endpoints).
start – The (inclusive) start point on a numeric scale (possibly negative or negative infinity).
end – The (inclusive) end point on a numeric scale (possibly negative or positive infinity).
- start: float
The (inclusive) start point on a numeric scale (possibly negative or negative infinity).
- invert: bool
If the true, the value exceeds the threshold if it is INSIDE the range between start and end (including the endpoints).
- 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 also
See the Monitoring Plugin Guidelines Repository or the Monitoring Plugins Development Guidelines for details.
- Parameters:
label – The short identifier, results in graph titles for example (20 chars or less recommended).
value – The measured value (usually an
int,float, orbool).uom – The unit of measure – use base units whereever possible.
warn – The warning range.
crit – The critical range.
min – The known value minimum (
Nonefor no minimum).max – The known value maximum (
Nonefor 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 | Context | None = None, resource: Resource | None = None)[source]
Bases:
objectSingle measured value. Structured representation for data points.
Instances of ths class 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 thanMetric('swap', 10, 'kiB').- Parameters:
name – A short internal identifier for the value – appears also in the performance data.
value – A data point. This value vsually has a boolen or numeric type, but other types are also possible.
uom – unit of measure, preferrably as ISO abbreviation like
s.min – The minimum value or
Noneif there is no known minimum.max – The maximum value or
Noneif there is no known maximum.context – The name of the associated
Context(defaults to the metric’s name if left out).
- value: Any
A data point. This value vsually has a boolen or numeric type, but other types are also possible.
- uom: str | None
unit of measure, preferrably as ISO abbreviation like
s.
- 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() list[Performance][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.
Domain model for data acquisition.
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.Outcomes from evaluating metrics in contexts.
The
Resultclass is the base class for all evaluation results. TheResultsclass (plural form) provides a result container with access functions and iterators.Plugin authors may create their own
Resultsubclass to accomodate for special needs.- 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.
Create status line from results.
This module contains the
Summaryclass which serves as base class to get a status line from the check’sResults. A Summary object is used byCheckto 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.
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.
Metadata about metrics to perform data evaluation.
This module contains the
Contextclass, which is the base for all contexts.ScalarContextis an important specialization to cover numeric contexts with warning and critical thresholds. TheCheckcontroller selects a context for eachMetricby 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
ScalarContextin the majority of cases. Sometimes is better to subclassContextinstead to implement custom evaluation or performance data logic.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 | Sequence[Performance] | Generator[Performance, Any, None] | 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
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.cli
Helper classes and functions to setup the Command Line Interface (cli) of monitoring plugins.
- class mplugin.cli.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
- mplugin.cli.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
argparse.ArgumentParserinstance with metadata and formatting suitable for monitoring plugins. It automatically prefixes the plugin name withcheck_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.persistence
Offers classes to persist the state between check runs.
- class mplugin.persistence.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.persistence.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
mplugin.testing
Helper classes and methods for testing monitoring plugins.
- class mplugin.testing.MockResult(sys_exit_mock: Mock, stdout: StringIO | None, stderr: StringIO | None)[source]
Bases:
objectA class to collect the result of a mocked execution.
- property state: ServiceState
- mplugin.testing.run_with_bin(args: list[str], bin_dir: Path) CompletedProcess[str][source]
Run a command with a modified PATH environment variable.
Prepends the specified binary directory to the PATH environment variable before running the subprocess, allowing executables in that directory to be found first during command resolution.
- Parameters:
args – List of command arguments to execute
bin_dir – Directory to prepend to the PATH environment variable
- Returns:
Completed process object with stdout and stderr as strings
mplugin.timespan
Offers classes and functions to make it easier and more efficient to work with time spans.
- mplugin.timespan.convert_timespan_to_sec(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:
spec – 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
- mplugin.timespan.TIMESPAN_FORMAT_HELP
This string can be included in the Command Line Interface help text.
- class mplugin.timespan.Timespan(start: int | float | datetime | None = None, end: int | float | datetime | None = None, timespan_from_now: int | float | None = None)[source]
Bases:
objectA class to represent a time interval between two datetime objects.
The Timespan class manages a time period defined by a start and end datetime. It supports multiple ways to initialize the timespan, including explicit start/end times or a duration from the current moment.
- Parameters:
start – The start datetime. Can be a datetime object, Unix timestamp (int/float), or None to use current time. Default is None.
end – The end datetime. Can be a datetime object, Unix timestamp (int/float), or None to use current time. Default is None.
timespan_from_now – Duration in seconds from the current moment to define the timespan. If specified, end is set to now and start is calculated backwards. Cannot be used together with start or end parameters. Default is None.
- Raises:
ValueError – If both
start/endandtimespan_from_nowparameters are specified.
Examples
Create a timespan from explicit start and end times:
ts = Timespan(start=datetime(2024, 1, 1), end=datetime(2024, 1, 2))
Create a timespan for the last hour:
ts = Timespan(timespan_from_now=3600)
Compare timespans with numeric values:
if ts > 3600: # more than 1 hour print("Long timespan")
Convert to different types:
duration_seconds = float(ts) duration_rounded = int(ts)