#!/bin/bash
#
# Script to monitor PowerDNS performance
#
# Parameters understood:
#
#       config   (required)
#       autoconf (optional - used by munin-config)
#%# family=auto
#%# capabilities=autoconf

pdns_control="/usr/bin/pdns_control"
command="$pdns_control show"
state_file=$MUNIN_PLUGSTATE/pdns_rel.state

if [ "$1" = "autoconf" ]; then
        if [ -e "$pdns_control" ]; then
                echo yes
                exit 0
        else
                echo "no (missing $pdns_control)"
                exit 0
        fi
fi

if [ "$1" = "config" ]; then
        echo 'graph_title Power DNS Packet Cache Performance'
        echo 'graph_args -l 0 --upper-limit 100 --base 1000'
        echo 'graph_vlabel %'
        echo 'graph_category dns'
        echo 'graph_info This graph shows the Power DNS packet cache performance on the machine.'
        echo 'packetcache_hitrate.label packet cache hitrate'
        echo 'packetcache_hitrate.type GAUGE'
        echo 'packetcache_hitrate.min 0'
        echo 'packetcache_hitrate.max 100'
        echo 'packetcache_hitrate.info Hits on the packets cache'
        exit 0
fi

hits=$($command packetcache-hit)
queries=$($command udp-queries)
if [ -f "$state_file" ]; then
        old_hits=$(head -n1 "$state_file")
        old_queries=$(tail -n1 "$state_file")
fi

if [ -f "$state_file" ] && [ "$(stat --format=%Y "$state_file")" -gt "$(date --date="7 minutes ago" +%s)" ] ; then
        d_hits=$((hits - old_hits))
        d_queries=$((queries - old_queries))
        if [ $d_queries -gt 0 ] ; then
           echo packetcache_hitrate.value $(( d_hits * 100 / d_queries ))
        fi
fi

echo "$hits" > "$state_file"
echo "$queries" >> "$state_file"
