#!/bin/sh
#
# Wildcard-plugin to monitor Xen virtual network interfaces. To monitor an
# interface, link vif_<domain> to this file. E.g.
#
# ln -s /usr/share/node/node/plugins-auto/vif_ /etc/munin/node.d/vif_dom1
#
# ...will monitor the virtual interface of Xen domain dom1.
#
# Magic markers (optional - used by munin-config and some installation
# scripts):
#
#%# family=auto
#%# capabilities=autoconf suggest


INTERFACE=`basename $0 | sed 's/^vif_//g'`

XM=/usr/sbin/xm

if [ "$1" = "autoconf" ]; then
	if [ -d /proc/xen -a -x $XM ]; then
		echo yes
		exit 0
	else
		echo "no (/proc/xen not found)"
		exit 1
	fi
fi

if [ "$1" = "suggest" ]; then
	if [ -d /proc/xen -a -x /usr/sbin/xm ]; then
		$XM list | egrep -v "^(Name|Domain-0)" | cut -f1 -d" " | sed 's/ //g'
		exit 0
	else
		exit 1
	fi
fi

if [ "$1" = "config" ]; then

	echo "graph_order down up" 
	echo "graph_title vif $INTERFACE traffic"
	echo 'graph_args --base 1000'
	echo 'graph_vlabel bps in (-) / out (+)'
	echo 'down.label received'
        echo 'down.type COUNTER'
        echo 'down.graph no'
        echo 'down.cdef down,8,*'
        echo 'up.label bps'
	echo 'up.type COUNTER'
	echo 'up.negative down'
	echo 'up.cdef up,8,*'
	exit 0
fi;

# get interface name from domain name
if [ -f /var/run/xen-vifs/$INTERFACE ]
then
  REAL_INTERFACE=$(cat /var/run/xen-vifs/$INTERFACE)
else
  exit
fi

# Escape dots in the interface name (eg. vlans) before using it as a regex
awk -v interface="$REAL_INTERFACE" \
    'BEGIN { gsub(/\./, "\\.", interface) } \
    $1 ~ "^" interface ":" {
        split($0, a, /: */); $0 = a[2]; \
        print "down.value " $9 "\nup.value " $1 \
    }' \
    /proc/net/dev

