#!/bin/sh
#
# Copyright (C) 2010 Michele Petrazzo <michele.petrazzo@gmail.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; version 2 dated June,
# 1991.
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# Python (2.5+) version of the plugin to monitor ping times.
# Evolution from the standard shipped with munin by adding a ceil.
#
# Thanks to "Jimmy Olsen" for the base.
#
# Parameters:
#
#       ping_args      - Arguments to ping (default "-c 2")
#       ping_args2     - Arguments after the host name (required for Solaris)
#       ping           - Ping program to use
#       host           - Host to ping
#
# Arguments for Solaris:
#      ping_args      -s
#      ping_args2     56 2
#

file_host=`basename $0 | sed 's/^ping_ceil_//g'`
host=${host:-${file_host:-www.google.com}}
max_ping="250" # Leave empty if not need or an integer (in ms)

test -z "$ping" && ping="ping"
test -z "$ping_args" && ping_args="-c 2"

cmd="$ping $ping_args $ping_args2"

if [ "$1" = "config" ]; then
    echo "graph_title Ping times to $host"
    echo 'graph_args --base 1000 -l 0'
    echo 'graph_vlabel seconds'
    echo 'graph_category network'
    echo 'graph_info This graph shows ping RTT statistics.'
    echo "ping.label $host"
    echo "ping.info Ping RTT statistics for $host."
    echo 'ping.draw LINE2'
    echo 'packetloss.label packet loss'
    echo 'packetloss.graph no'
    exit 0
fi


(
cat << EOF
import os
from subprocess import Popen, PIPE
bash_cmd = "$cmd"
command = bash_cmd.split() + ["$host"]
max_ping = float("$max_ping") if "$max_ping" else 0

try:
    c = Popen(command, stdout=PIPE, stderr=PIPE)
except OSError:
    print "command error:", command
    raise

out, err = c.communicate()

for line in out.split("\n"):
    if "packet loss" in line:
        print "packetloss.value", line.split(",")[2].split()[0].replace("%", "")
    elif "rtt min/avg/max/mdev" in line:
        v = float(line.split("=")[1].split("/")[1])
        v = min(v, max_ping) if max_ping else v
        print "ping.value", "%.6f" % (v / 1000)

EOF
) | python

