Deprecated: this howto works for CheckMK v1.x – For CheckMK v2 you can find a howto here

Download mkp-File: check_rtmp-0.2.zip

Active Check Script

  • should return the few different states – 0, 1, 2, 3 for OK, WARN, CRIT, UNKOWN
  • must be placed in ~/local/lib/nagios/plugins

The Check_MK Plugin

  • like always must be placed in ~/local/share/check_mk/checks
  • and the WATO configuration in ~/local/share/check_mk/web/plugins/wato

Example Script – A Check for RTMP-Streams

This check will have a small speciality – we will have to use an extra library to be able to check if the given RTMP-stream is online. Unfortunately I haven’t found a really trustable source for a librtmp-RPM. So first we will have to build the prerequisites for Centos 7 – librtmp. This is normally not recommended and checks should not use any extra libraries – but in this case it’s not possible without this extra library.

Build librtmp for Centos 7

python-librtmp is provided by pip – but as mentioned it will need librtmp first. An easy howto can be found here http://blog.svnlabs.com/install-rtmpdump-in-centos/
TLDR: You need to download the latest rtmpdump-sources from https://rtmpdump.mplayerhq.hu/download and untar them and change to rtmp’s directory. Before we run ‚make‘ and ‚make install‘, we need to install libffi and openssl-devel:

yum install libffi
yum install openssl-devel

now run ‚make‘ and afterwards ‚make install‘ if there were no errors. Now we can install python-librtmp via pip

yum install python-pip

optionally you can upgrade pip:

pip install --upgrade pip

then we execute

pip install python-librtmp

librtmp files will be found in /usr/local/lib
NOTE: a check_mk-site needs the librtmp.so.0 in ~/local/lib – for scripting as another user, you’ll have to set LD_LIBRARY_PATH (e.g. export LD_LIBRARY_PATH=/usr/local/lib)

Special-NOTE

this can be handy for testing – place those few lines at the beginning while scripting as non-Check_MK user – Later it will not work or you have to change this a little because a Check_MK-site set’s its own LD_LIBRARY_PATH for the scripts!

#!/usr/bin/env python

import os, sys

if 'LD_LIBRARY_PATH' not in os.environ:
    os.environ['LD_LIBRARY_PATH'] = '/usr/local/lib'
    try:
        os.execv(sys.argv[0], sys.argv)
    except Exception, exc:
        print 'Failed re-exec:', exc
        sys.exit(1)
#
print 'Success:', os.environ['LD_LIBRARY_PATH']

import librtmp

Found at http://stackoverflow.com/questions/6543847/setting-ld-library-path-from-inside-python

The active check itself – check_rtmp

Place the active check in ~/local/lib/nagios/plugins and make it executable
not much to say about this script – it will just have the exit codes 0,2 and 3 – See NOTE above – the librtmp.so.0 must be placed in the site’s ~/local/lib folder, else Check_MK won’t be able to find the library

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

# Check_MK Check RTMP
#
# Copyright 2016, 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/>.

import os, sys, getopt, librtmp

def usage():
    sys.stderr.write(
"""
Check_MK RTMP Test

USAGE: check_rtmp [OPTIONS] RTMP-URL
       check_rtmp -h

ARGUMENTS:
       RTMP-URL      Valid RTMP URL e.g. rtmp://some.domain.com/foobar.stream

OPTIONS:
-h, --help                        Show this help message and exit
-t INTEGER, --timeout INTEGER     Timeout for trying to connect in seconds (default: 30)
-l BOOL, --live BOOL              Set to False if not a livestream (default: True)
-v, --verbose                     Verbose mode: print more info
""")

short_options = 'ht:t:l:v'
long_options = ['help', 'timeout=', 'live=', 'verbose' ]

try:
    opts, args = getopt.getopt(sys.argv[1:], short_options, long_options)

except getopt.GetoptError, e:
    sys.stderr.write("UNKOWN - Error in command options: %s\n" % e)
    sys.exit(3)

opt_verbose       = False
opt_timeout       = 30
opt_live          = True

try:
    for option, argument in opts:
        if option in [ '-v', '--verbose' ]:
             opt_verbose = True
        elif option in [ '-t', '--timeout' ]:
             opt_timeout = argument
        elif option in [ '-l', '--live' ]:
             opt_live = argument.title()
        elif option in [ '-h', '--help']:
             usage()
             sys.exit(0)

    if args:
       rtmp_url_tmp = ' '.join(map(str,args))
       if rtmp_url_tmp.startswith("rtmp://"):
           rtmp_url = rtmp_url_tmp
       else:
           sys.stderr.write("UNKNOWN - non RTMP URL given\n")
           sys.exit(3)
    else:
       sys.stderr.write("UNKNOWN - no RTMP URL given\n")
       sys.exit(3)

except Exception, e:
    if opt_debug:
        raise
    sys.stderr.write("UNKNOWN - Error while processing input: %s\n" % e)
    sys.exit(3)

if opt_verbose:
    print("Verbose enabled: %s" % str(opt_verbose))
    print("Timeout set to: %s" % str(opt_timeout))
    print("Is a live strem: %s" % str(opt_live))
    print("Given RTMP-URL: %s" % str(rtmp_url))

try:
    conn = librtmp.RTMP(rtmp_url, opt_live, opt_timeout)
    conn.connect()
    if conn.connected:
        stream = conn.read_packet()
        if stream.body is not None:
            conn.close()
            print("OK - stream is online")
            sys.exit(0)
except librtmp.RTMPError, e:
    sys.stderr.write("CRIT - error connecting to stream: %s\n" % e )
    sys.exit(2)
except librtmp.RTMPTimeoutError:
    sys.stderr.write("CRIT - connection timed out: %s\n" %e )
    sys.exit(2)

conn.close()

The Check_MK check – check_rtmp

Place this file in ~/local/share/check_mk/checks

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

# Check_MK Check RTMP
#
# Copyright 2016, 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/>.

NOTE: The params variable will have a dictionary as value – see later in the check_parameters_check_rtmp.py file

def check_rtmp_arguments(params):
    args = ""

    if "live" in params:
        args += "--live %s " % quote_shell_string(params["live"])
    else:
        args += "--live True "

    if "timeout" in params:
        args += "--timeout %s " % quote_shell_string(params["timeout"])
    else:
        args += "--timeout 30 "

    args += " %s" % quote_shell_string(params["rtmp_url"])
    #args += " %s" % params["rtmp_url"]

    return args
#enddef

NOTE: So this is interesting (again you won’t find much about this in the documentation of Check_MK) – the included active checks all have the variable $USER1$ but as we program our own check, we have to use $USER2$. Those variables are defined in your site’s ~/etc/icinga/resource.cfg

# $USER2$ ... ~/local/lib/nagios/plugins --- more info in ~/etc/icinga/resource.cfg
active_check_info['rtmp'] = {
    "command_line"           : '$USER2$/check_rtmp $ARG1$',
    "argument_function"      : check_rtmp_arguments,
    "service_description"    : lambda args: args["description"],
    "has_perfdata"           : False,
}

The check parameters – check_parameters_check_rtmp.py

We have to be able to configure the needed parameters via WATO – so we have to place this one in ~/local/share/check_mk/web/plugins/wato
NOTE: This file looks a little bit different to normal Check_MK check_parameters-files. You find the definitions for the included checks in ~/share/check_mk/web/plugins/wato/active_checks.py and not in check_parameters.py

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

# Check_MK Check RTMP
#
# Copyright 2016, 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/>.

group = "activechecks"

register_rule(group,
    "active_checks:rtmp",
    Dictionary(
        title = _("Check RTMP"),
        help = _("This check connects to a given rtmp-url and checks if online or not. "
                 "This check uses the active check <tt>check_rtmp</tt>. "),
        optional_keys = [ "live", "timeout" ],
        elements = [
            ( "description",
              TextUnicode(title = _("Service Description"),
                 help = _("The name of this active service to be displayed."),
                 allow_empty = False,
            )),
            ( "live",
              DropdownChoice(
                  title = _("Is this a live stream"),
                  help = _('default is Yes'),
                  choices = [
                     ( "True",  _("Yes") ),
                     ( "False", _("No") ),
                  ],
                  default_value = "yes",
              )
            ),
            ( "timeout",
              Integer(
                  title = _("Set timeout in seconds"),
                  help = _('default is 30'),
                  default_value = 30,
              )
            ),
            ( "rtmp_url",
              TextAscii(
                  title = _("Set the RTMP-URL"),
                  help = _('e.g. rtmp://some.domain/with-a.stream'),
                  allow_empty = False,
              )
            ),
        ]
    ),
    match = 'all'
)

So that’s it – you just created your own active check

Links

Zuletzt bearbeitet: Oktober 22, 2021

Autor

Kommentare

Kommentar verfassen

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