Commit e732d99e authored by nimrod's avatar nimrod
Browse files

Merge branch 'nagios-check'

parents 2b15bcdf 99a05584
Loading
Loading
Loading
Loading
+17 −3
Original line number Diff line number Diff line
@@ -4,7 +4,15 @@ __version__ = "0.1.0"
import argparse
import logging

import mnpw.nagios
import nagios
import requests


def notify(message):
    """Send a notification."""
    requests.post(
        "https://notify.shore.co.il/send", params={"message": message}
    )


def main():
@@ -32,14 +40,20 @@ def main():
    parser.add_argument(
        "-t",
        "--timeout",
        help=f"Command timeout (in seconds), defaults to {mnpw.nagios.DEFAULT_TIMEOUT}",  # noqa: E501
        help=f"Command timeout (in seconds), defaults to {nagios.DEFAULT_TIMEOUT}",  # noqa: E501
        type=int,
        default=mnpw.nagios.DEFAULT_TIMEOUT,
        default=nagios.DEFAULT_TIMEOUT,
    )
    args = parser.parse_args()
    if args.verbose:
        logging.basicConfig(level=logging.INFO)

    check = nagios.Check(args.command, args.arguments)
    try:
        check.run(args.timeout, args.dry_run)
    except Exception as ex:
        parser.error(str(ex))


if __name__ == "__main__":
    main()
+52 −0
Original line number Diff line number Diff line
"""Nagios check implementation."""

import enum
import subprocess

DEFAULT_TIMEOUT = 10  # In seconds.


class NagiosCode(enum.IntEnum):
    """Enum for agreed upon exit codes for a Nagios plugin."""

    OK = 0
    WARNING = 1
    CRITICAL = 2
    UNKNOWN = 3


class Check:
    """Nagios check using a plugin."""

    Command = None
    Arguments = []
    ExitCode = None
    Result = None
    Output = None
    PerfData = None
    AdditionalOutput = None
    StandardError = None

    def __init__(self, command, args):
        if not command:
            raise ValueError("Command is empty.")
        self.Command = command
        if args:
            self.Arguments = args

    def run(self, timeout=DEFAULT_TIMEOUT, dryrun=False):
        """Run the check (if it's hasn't run yet)."""
        if self.Result is not None:
            raise Exception("Check has already run.")
        try:
            proc = subprocess.run(
                [
                    self.Command,
                ]
                + self.Arguments,
                capture_output=True,
                check=False,
                text=True,
                timeout=timeout,
            )
        except FileNotFoundError:
            raise RuntimeError(f"Command {self.Command} not found.")
        except subprocess.TimeoutExpired:
            raise RuntimeError("Timeout exceeded.")