Again documentation seems to be none-existent. So a lot of selfstudy by looking at existing checks and their files is needed. Also it seems active-checks cannot be fully migrated yet, as you will notice in the "Check-File" (there is no register.??? yet and we still have to use active_check_info)

In this example we use some MySQL Replication Delay Check that was initially created by nice people from Percona for Nagios :relieved:

Plugin Structure

For active-checks you in general should create four files:

└── local
    ├── bin
    ├── lib
    │   ├── check_mk -> python3/cmk
    │   └── nagios
    │       └── check_pmp_check_mysql_replication_delay.sh           # Active-Check-File: file which actively checks something on a host
    └── share
        └── check_mk
            ├── checkman
            │   └── check_pmp_check_mysql_replication_delay          # Checkman-File: file with info about the check
            ├── checks
            │   └── check_pmp_check_mysql_replication_delay.py       # Check-File: file which calls the active-check-file with some parameters.
            └── web
                └── plugins
                    └── wato
                        └── check_pmp_check_mysql_replication_delay_parameters.py    # Check-Parameters-UI-File: file which create the WATO-UI page for configuring the parameters of the check

Active-Check-File

The check itself can be written in any language – in this case it’s a shell-script. It should only return some meaningful message and exit with 0 (OK), 1 (WARN), 2 (CRIT) or 3 (UNKNOWN). If you want some eye-candy graphs, the message returned also should include some "perfdata". For example if the script exits with 0 the output should look similar to:

OK 0 seconds of replication delay | replication_delay=0;300;600;0;

You can find more about the perfdata-format here http://docs.pnp4nagios.org/pnp-0.6/perfdata_format

The check-script check_pmp_check_mysql_replication_delay.sh

#!/bin/sh

# ########################################################################
# This program is part of $PROJECT_NAME$
# License: GPL License (see COPYING)
# Authors:
#  Baron Schwartz, Roman Vynar
# ########################################################################

#set -x

# ########################################################################
# Redirect STDERR to STDOUT; Nagios doesn't handle STDERR.
# ########################################################################
exec 2>&1

# ########################################################################
# Set up constants, etc.
# ########################################################################
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
STATE_DEPENDENT=4

# ########################################################################
# Run the program.
# ########################################################################
main() {
   # Get options
   OPT_ENSURE_SBM=0
   MIN_DELAY_SET=0
   for o; do
      case "${o}" in
         -c)              shift; OPT_CRIT="${1}"; shift; ;;
         --defaults-file) shift; OPT_DEFT="${1}"; shift; ;;
         -H)              shift; OPT_HOST="${1}"; shift; ;;
         -l)              shift; OPT_USER="${1}"; shift; ;;
         -L)              shift; OPT_LOPA="${1}"; shift; ;;
         -m)              shift; OPT_MIN="${1}"; MIN_DELAY_SET=1; shift; ;;
         -p)              shift; OPT_PASS="${1}"; shift; ;;
         -P)              shift; OPT_PORT="${1}"; shift; ;;
         -S)              shift; OPT_SOCK="${1}"; shift; ;;
         -s)              shift; OPT_SRVID="${1}"; shift; ;;
         -T)              shift; OPT_TABLE="${1}"; shift; ;;
         -u)              shift; OPT_UTC=1; ;;
         -w)              shift; OPT_WARN="${1}"; shift; ;;
         --master-conn)   shift; OPT_MASTERCONN="${1}"; shift; ;;
         --channel)       shift; OPT_CHANNEL="${1}"; shift; ;;
         --unconfigured)  shift; OPT_REPLNOTSET=1; ;;
         --ensure-sbm)    shift; OPT_ENSURE_SBM=1; ;;
         --version)       grep -A2 '^=head1 VERSION' "$0" | tail -n1; exit 0 ;;
         --help)          perl -00 -ne 'm/^  Usage:/ && print' "$0"; exit 0 ;;
         -*)              echo "Unknown option ${o}.  Try --help."; exit 1; ;;
      esac
   done
   OPT_WARN=${OPT_WARN:-300}
   OPT_CRIT=${OPT_CRIT:-600}
   OPT_MIN=${OPT_MIN:-0}
   if [ -e '/etc/nagios/mysql.cnf' ]; then
      OPT_DEFT="${OPT_DEFT:-/etc/nagios/mysql.cnf}"
   fi
   if is_not_sourced; then
      if [ -n "$1" ]; then
         echo "WARN spurious command-line options: $@"
         exit 1
      fi
   fi

   # Get replication delay from a heartbeat table or from SHOW SLAVE STATUS.
   get_slave_status $1
   if [ "${OPT_TABLE}" ]; then
      if [ -z "${OPT_UTC}" ]; then
         NOW_FUNC='UNIX_TIMESTAMP()'
      else
         NOW_FUNC='UNIX_TIMESTAMP(UTC_TIMESTAMP)'
      fi
      if [ "${OPT_SRVID}" == "MASTER" ]; then
        if [ "${MYSQL_CONN}" = 0 ]; then
          OPT_SRVID=$(awk '/Master_Server_Id/{print $2}' "${TEMP_SLAVEDATA}")
        fi
      fi
      SQL="SELECT MAX(${NOW_FUNC} - ROUND(UNIX_TIMESTAMP(ts))) AS delay
         FROM ${OPT_TABLE} WHERE (${OPT_SRVID:-0} = 0 OR server_id = ${OPT_SRVID:-0})"
      LEVEL=$(mysql_exec "${SQL}")
      MYSQL_CONN=$?
   else
      if [ "${MYSQL_CONN}" = 0 ]; then
         LEVEL=$(awk '/Seconds_Behind_Master/{print $2}' "${TEMP_SLAVEDATA}")
      fi
   fi

   # LEVEL must be checked if really an integer or NULL - if not it means there were multiple channels
   # e.g. if there are 4 channels the LEVEL would be "0 0 0 0" which creates later problems and
   # even more problems in the perfdata string - e.g. the rrd process of check_mk goes bonkers
   # and messes up the whole check_mk server
   if [ "$MYSQL_CONN" = 0 ]; then
       PATTERN="^[0-9]+$|NULL"
       if ! [[ "$LEVEL" =~ $PATTERN ]]; then
           ADDITIONAL_NOTE="Multiple channels deteced - please check"
           MULTICHANNEL_DETECTED=1
           MYSQL_CONN=17
       fi
   fi

   # Check for SQL thread errors
   LAST_SLAVE_ERRNO=$(awk '/Last_SQL_Errno/{print $2}' "${TEMP_SLAVEDATA}")

   # Build the common perf data output for graph trending
   PERFDATA="replication_delay=${LEVEL:-0};${OPT_WARN};${OPT_CRIT};0;"

   # Test whether the delay is too long.
   if [ "$MYSQL_CONN" = 0 ]; then
      NOTE="${LEVEL:-0} seconds of replication delay"
      if [ "${LEVEL:-""}" = "NULL" ]; then
         test ${MIN_DELAY_SET} -eq 1 && \
         test ${LAST_SLAVE_ERRNO} -eq 0 && \
         test ${OPT_ENSURE_SBM} -eq 0 && \
            NOTE="OK NULL seconds of replication delay" || NOTE="UNK replica is stopped"
      elif [ -z "${LEVEL}" -a "${OPT_REPLNOTSET}" ]; then
         NOTE="UNK This server is not configured as a replica."
      # pt-slave-delayed slave
      elif [ ${MIN_DELAY_SET} -eq 1 ] && [ "${LEVEL:-0}" -lt "${OPT_MIN}" ]; then
         NOTE="CRIT (delayed slave) $NOTE | $PERFDATA"
      elif [ "${LEVEL:-0}" -gt "${OPT_CRIT}" ]; then
         NOTE="CRIT $NOTE | $PERFDATA"
      elif [ "${LEVEL:-0}" -gt "${OPT_WARN}" ]; then
         NOTE="WARN $NOTE | $PERFDATA"
      else
         NOTE="OK $NOTE | $PERFDATA"
      fi
   else
      NOTE="UNK could not determine replication delay"

      # check if MULTICHANNEL_DETECTED is set
      if ! [ -z "$MULTICHANNEL_DETECTED" ]; then
          NOTE="${NOTE} - ${ADDITIONAL_NOTE}"
      fi
   fi
   echo $NOTE
}

# ########################################################################
# Execute a MySQL command.
# ########################################################################
mysql_exec() {
   mysql ${OPT_DEFT:+--defaults-file="${OPT_DEFT}"} \
      ${OPT_LOPA:+--login-path="${OPT_LOPA}"} \
      ${OPT_HOST:+-h"${OPT_HOST}"} ${OPT_PORT:+-P"${OPT_PORT}"} \
      ${OPT_USER:+-u"${OPT_USER}"} ${OPT_PASS:+-p"${OPT_PASS}"} \
      ${OPT_SOCK:+-S"${OPT_SOCK}"} -ss -e "$1"
}

# ########################################################################
# Determine whether this program is being executed directly, or sourced/included
# from another file.
# ########################################################################
is_not_sourced() {
   [ "${0##*/}" = "check_pmp_check_mysql_replication_delay.sh" ] || [ "${0##*/}" = "bash" -a "$_" = "$0" ]
}

# ########################################################################
# Captures the "SHOW SLAVE STATUS" output into a temp file.
# ########################################################################
get_slave_status() {
  TEMP_SLAVEDATA=$(mktemp -t "${0##*/}.XXXXXX") || exit $?
  trap "rm -f '${TEMP_SLAVEDATA}' >/dev/null 2>&1" EXIT
  if [ -z "$1" ]; then
     if [ "${OPT_MASTERCONN}" ]; then
        # MariaDB multi-source replication
        mysql_exec "SHOW SLAVE '${OPT_MASTERCONN}' STATUS\G" > "${TEMP_SLAVEDATA}"
     elif [ "${OPT_CHANNEL}" ]; then
    mysql_exec "SHOW SLAVE STATUS FOR CHANNEL '${OPT_CHANNEL}'\G" > "${TEMP_SLAVEDATA}"
     else
        # Leverage lock-free SHOW SLAVE STATUS if available
        mysql_exec "SHOW SLAVE STATUS NONBLOCKING\G" > "${TEMP_SLAVEDATA}" 2>/dev/null ||
        mysql_exec "SHOW SLAVE STATUS NOLOCK\G" > "${TEMP_SLAVEDATA}" 2>/dev/null ||
        mysql_exec "SHOW SLAVE STATUS\G" > "${TEMP_SLAVEDATA}"
     fi
     MYSQL_CONN=$?
  else
     # This is for testing only.
     cat "$1" > "${TEMP_SLAVEDATA}" 2>/dev/null
     MYSQL_CONN=0
  fi
  # cat ${TEMP_SLAVEDATA}
}

# ########################################################################
# Execute the program if it was not included from another file.
# This makes it possible to include without executing, and thus test.
# ########################################################################
if is_not_sourced; then
   OUTPUT=$(main "$@")
   EXITSTATUS=$STATE_UNKNOWN
   case "${OUTPUT}" in
      UNK*)  EXITSTATUS=$STATE_UNKNOWN;  ;;
      OK*)   EXITSTATUS=$STATE_OK;       ;;
      WARN*) EXITSTATUS=$STATE_WARNING;  ;;
      CRIT*) EXITSTATUS=$STATE_CRITICAL; ;;
   esac
   echo "${OUTPUT}"
   exit $EXITSTATUS
fi

# ############################################################################
# Documentation
# ############################################################################
: <<'DOCUMENTATION'
=pod

=head1 NAME

check_pmp_check_mysql_replication_delay.sh - Alert when MySQL replication becomes delayed.

=head1 SYNOPSIS

  Usage: check_pmp_check_mysql_replication_delay.sh [OPTIONS]
  Options:
    -c CRIT         Critical threshold; default 600.
    --defaults-file FILE Only read mysql options from the given file.
                    Defaults to /etc/nagios/mysql.cnf if it exists.
    -H HOST         MySQL hostname.
    -l USER         MySQL username.
    -L LOGIN-PATH   Use login-path to access MySQL (with MySQL client 5.6).
    -m CRIT         Minimal threshold to ensure for delayed slaves; default 0.
    -p PASS         MySQL password.
    -P PORT         MySQL port.
    -S SOCKET       MySQL socket file.
    -s SERVERID     MySQL server ID of master, if using pt-heartbeat table. If
                    the parameter is set to "MASTER" the plugin will lookup the
                    server_id of the master
    -T TABLE        Heartbeat table used by pt-heartbeat.
    -u              Use UTC time to count the delay in case pt-heartbeat is run
                    with --utc option.
    -w WARN         Warning threshold; default 300.
    --master-conn NAME  Master connection name for MariaDB multi-source replication.
    --channel NAME  Master channel name for multi-source replication (MySQL 5.7.6+).
    --unconfigured  Alert when replica is not configured at all; default no.
    --ensure-sbm    Disallow Seconds_Behind_Master to be NULL for delayed slaves when -m is used
    --help          Print help and exit.
    --version       Print version and exit.
  Options must be given as --option value, not --option=value or -Ovalue.
  Use perldoc to read embedded documentation with more details.

=head1 DESCRIPTION

This Nagios plugin examines whether MySQL replication is delayed too much.  By
default it uses SHOW SLAVE STATUS, but the output of the Seconds_behind_master
column from this command is unreliable, so it is better to use pt-heartbeat from
Percona Toolkit instead.  Use the -T option to specify which table pt-heartbeat
updates.  Use the -s option to specify the master's server_id to compare
against; otherwise the plugin reports the maximum delay from any server. Use
the -s options with the value "MASTER" to have plugin lookup the master's server_id

If you want to run this check against the delayed slaves, e.g. those running
with pt-slave-delay tool, you may want to use -m option specifying the minimal
delay that should be ongoing, otherwise the plugin will alert critical.

=head1 PRIVILEGES

This plugin executes the following commands against MySQL:

=over

=item *

C<SHOW SLAVE STATUS [NONBLOCKING|NOLOCK]>

or

=item *

C<SELECT> from the C<pt-heartbeat> table.

=back

This plugin executes no UNIX commands that may need special privileges.

=head1 COPYRIGHT, LICENSE, AND WARRANTY

This program is copyright 2012-$CURRENT_YEAR$ Baron Schwartz, 2012-$CURRENT_YEAR$ Percona Inc.
Feedback and improvements are welcome.

THIS PROGRAM IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, version 2.  You should have received a copy of the GNU General
Public License along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.

=head1 VERSION

$PROJECT_NAME$ check_pmp_check_mysql_replication_delay.sh $VERSION$

=cut

DOCUMENTATION

#set +x

Don’t forget to make this file executable!

Check-File

This one is quite short because it only supplies the needed arguments and parameters for the active-check script. In this case it will look like:

#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-

# Check_MK check_pmp_check_mysql_replication_delay - adapted for CMK
#
# Copyright 2019, Clemens Steinkogler <c.steinkogler[at]cashpoint.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Changelog:
# 2019       - intial release for CMK
# 2021-10-07 - slight adjustments for CMKv2

# I use pycharm so that I can use the "Go To" -> "Declaration or Usages"
# Not sure if it's smart to keep this in productive checks else
# comment the following line(s) later after check works and is finished or if they create problems
from cmk.utils import quote_shell_string
from cmk.base.config import active_check_info
from cmk.utils.password_store import extract as get_password_from_store

def check_pmp_check_mysql_replication_delay_arguments(params):
    args = ""

    if "crit" in params:
        args += "-c %s " % params["crit"]
    # endif

    if "warn" in params:
        args += "-w %s " % params["warn"]
    # endif

    if "host" in params:
        args += "-H %s " % quote_shell_string(params["host"])
    # endif

    if "login" in params:
        args += "-l %s " % quote_shell_string(params["login"])
    # endif

    # unfortunately the password is still in clear-text in the "Service check command" in the check's details
    # not sure if that should be like that, after using CMK's "password-store" :| - documentation is very scarce
    if "password" in params:
        if get_password_from_store(params["password"][1]) is not None:
            args += "-p %s " % quote_shell_string(get_password_from_store(params["password"][1]))
        else:
            args += "-p %s " % quote_shell_string(params["password"][1])
        # endif
    # endif

    if "port" in params:
        args += "-P %s " % params["port"]
    # endif

    if "channel" in params:
        args += "--channel %s " % params["channel"]
    # endif

    return args
# enddef

# $USER2$ ... ~/local/lib/nagios/plugins --- more info in ~/etc/nagios/resource.cfg
active_check_info['check_pmp_check_mysql_replication_delay'] = {
    "command_line": '$USER2$/check_pmp_check_mysql_replication_delay.sh $ARG1$',
    "argument_function": check_pmp_check_mysql_replication_delay_arguments,
    "service_description": lambda args: args["description"],
    "has_perfdata": True,
}

Check-Parameters-UI-File

This one now looks for CMKv2 a little bit different in comparison to older CMK versions

#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-

# Check_MK check_pmp_check_mysql_replication_delay - adapted for CMK
#
# Copyright 2019, Clemens Steinkogler <c.steinkogler[at]cashpoint.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# for autotranslating stuff it seems
from cmk.gui.i18n import _
# we need Dictionary, TextUnicode and some other thingies
from cmk.gui.valuespec import (
    Dictionary,
    TextUnicode,
    Integer,
    TextAscii
)

from cmk.gui.plugins.wato import (
    rulespec_registry,
    HostRulespec
)

# we use the password-store (which is imho not that awesome - because, password is shown anyway in active-check
# commandline, or did I overlook anything? - sigh
from cmk.gui.plugins.wato.utils import (
    PasswordFromStore
)

# we import the RulespecGroupActiveChecks
from cmk.gui.plugins.wato.active_checks import RulespecGroupActiveChecks

def _valuespec_active_check_pmp_check_mysql_replication_delay():
    return Dictionary(
        title=_("Check MySQL Replication Delay"),
        help=_("This check alerts when MySQL replication becomes delayed"
               "This check uses the active check <tt>check_pmp_check_mysql_replication_delay</tt>. "),
        optional_keys=["port", "crit", "warn", "channel"],
        elements=[
            (
                "description",
                TextUnicode(
                    title=_("Service Description"),
                    help=_("The name of this active service to be displayed."),
                    allow_empty=False,
                )
            ),
            (
                "host",
                TextAscii(
                    title=_("Set Host to connect to"),
                    help=_('defaults to localhost'),
                    allow_empty=False,
                    default_value="localhost",
                )
            ),
            (
                "login",
                TextAscii(
                    title=_("Set User for connection"),
                    help=_('defaults to dba'),
                    allow_empty=False,
                    default_value="dba",
                )
            ),
            (
                "password",
                PasswordFromStore(
                    title=_("Set Password for connection"),
                    allow_empty=False
                )
            ),
            (
                "port",
                Integer(
                    title=_("Set MySQL Port"),
                    help=_('default 3306'),
                    default_value=3306,
                )
            ),
            (
                "channel",
                TextAscii(
                    title=_("Set Master channel name for multi-source replication"),
                    help=_('no default'),
                    allow_empty=False,
                )
            ),
            (
                "warn",
                Integer(
                    title=_("Warn threshold"),
                    help=_('default 300'),
                    default_value=300,
                )
            ),
            (
                "crit",
                Integer(
                    title=_("Crit threshold"),
                    help=_('default 600'),
                    default_value=600,
                )
            ),
        ]
    )
# enddef

rulespec_registry.register(
    HostRulespec(
        group=RulespecGroupActiveChecks,
        match_type="all",
        name="active_checks:check_pmp_check_mysql_replication_delay",
        valuespec=_valuespec_active_check_pmp_check_mysql_replication_delay,
    )
)

The parameter-ui-definitions for the included active-checks can be found at ~/lib/python3/cmk/gui/plugins/wato/active_checks.py – unfortunately it’s everything in on huge file.

Checkman-File

Now we get to the least important file. This one should contain only some info about the check. This file makes the check being listed in "Catalog of check plugins" in CMK

You may have noticed that the check files unnecessarily are all prefixed with check_ – this is intentional because checkman files MUST begin with this prefix to be correctly detected by CMK to be assosciated to their corresponding active-check – have a look at ~/lib/python3/cmk/gui/wato/pages/check_catalog.py 😐

title: MySQL: Replication Delay Check
agents: active
catalog: app/mysql
license: GPL
distribution: check_mk
description:
 Checks for replication delay of defined databases
inventory:
 Creates one configured item

That’s it – now you should have a working active-check plugin. Now you can add for example a host example.test.mysql, configure a check-rule with some meaningful "Service Description" like "MySQL Replication Delay – status" and activate it.

Debugging

In case you have problems you should try to execute the active-check with the proper parameters needed. If with the active-check-script all is fine and you still see problems in CMK you may try to add some print() statements in the "Check-File" and execute the active check for example via:

# also not well documented and found via grepping through CMK code :| - see ~/lib/python3/cmk/base/automations/check_mk.py
#                             hostname           active-check plugin                     service-description
cmk --automation active-check example.test.mysql check_pmp_check_mysql_replication_delay "MySQL Replication Delay - status"

If everything is alright it should output

(0, u'OK 0 seconds of replication delay ')
Zuletzt bearbeitet: Oktober 11, 2021

Autor

Kommentare

Kommentar verfassen

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.