From 82b4ba4c71af662242ef315544488213e9964c4c Mon Sep 17 00:00:00 2001 From: Pavel 'LEdoian' Turinsky Date: Wed, 10 Aug 2022 05:30:17 +0200 Subject: [PATCH] [WIP] Initial version --- checklib.py | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++ example.py | 14 +++++++++++ 2 files changed, 81 insertions(+) create mode 100644 checklib.py create mode 100644 example.py diff --git a/checklib.py b/checklib.py new file mode 100644 index 0000000..dc806fa --- /dev/null +++ b/checklib.py @@ -0,0 +1,67 @@ +import sys +import traceback +import argparse +from enums import Enum + +""" +CheckLib: a simple wrapper around Icinga checks dealing with common +code like correct error codes and output formatting + +The main class is `Check`, other classes are just helpers. +""" + +class Result(Enum): + """ + Enumeration of possible check results. + + The values are related return codes. + """ + OK = 0 + WARNING = 1 + CRITICAL = 2 + UNKNOWN = 3 + +class Check: + """ + The class representing the check. + + Expected usage is by invoking the `run` classmethod, which overtakes + the control, performs the check and returns the correct return + value. + + The sequence is following: + 1. run: Runs the check: + 1. __init__: initialization + - Creation of default values in the instance + - Preparation of argument parser (TODO: Do we want this here?) + 1. prepare_argparse: Optionally tweaks argparse's + ArgumentParser, e.g. adding more parameters + 1. self.args = argparse.parse_args(sys.argv) + 1. check(): the function to check state and populate + self.result, self.short_message and so on. + 1. sys.exit with the relevant exit code according to + self.result + - If anything fails, e.g. by raising an exception, + the run method returns the UNKNOWN result and + uses the traceback as message. + + Instead of using self.check, the default implementation invokes + measure method and compares its value to thresholds given either + by semi-standard arguments, or defaults defined in the class. + (If neither method is defined, the check fails. In other words, + you need to either implement measure, or override check.) + + FIXME: It is currently not documented, which attributes of the instance + are used. + """ + + @classmethod + def run(cls, *args, **kwargs): + """ + This method implements the checking start-to-end. + + The arguments, if any, are passed to the __init__ of the class. + """ + + try: + diff --git a/example.py b/example.py new file mode 100644 index 0000000..a792f02 --- /dev/null +++ b/example.py @@ -0,0 +1,14 @@ +from checklib import Check, Result + +class MyCheck(Check): + def check(self): + self.result.state = Result.UNKNOWN + self.result.short_message = 'I don\'t know :-)' + + def add_arguments(self): + pass + + # Collect argparse arguments at self.arguments + + # If defining __init__, call super().__init__ first -- it populates + # self.result, self.argumentparser and so on.