#!/bin/sh
# -*- sh -*-
#
# Wildcard-plugin to monitor disk IOs. To monitor a disk, link
# iostat_<disk> to this file. E.g.
#
#    ln -s /usr/local/libexec/munin/plugins/iostat_ \
#	/etc/munin/plugins/iostat_sd0
#
# ...will monitor sd0.
#
# To aggregate all disk traffic on the system, link iostat_aggregated
# to this file.
#
# Magic markers (optional - used by munin-config and some installation
# scripts):
#
#%# family=auto
#%# capabilities=autoconf suggest

DISK=${0##*iostat_}


if [ "$1" = "autoconf" ]; then
	if [ -x /usr/sbin/iostat -a -x /sbin/sysctl ]; then
		echo yes
		exit 0
	else
		echo "no (/usr/sbin/iostat or /sbin/sysctl not found)"
		exit 0
	fi
fi

if [ "$1" = "suggest" ]; then
	if [ -x /sbin/sysctl ]; then
		/sbin/sysctl hw.disknames | perl -ne '
			my @disks = split(/=|,/);
			for my $disk (@disks) {
				next if $disk =~ m{hw.disknames};
				my @d = split(/:/, $disk);
				print "$d[0]\n" if ($d[0] =~ m{[a-z]+\d+}
					and $d[1] =~ m/.{16}/);
			}
		'
		exit 0
	else
		exit 1
	fi
fi

if [ "$1" = "config" ]; then
	echo 'multigraph bytes'
	echo "graph_title $DISK IO Bytes/s"
	echo 'graph_args --base 1024'
	echo 'graph_vlabel Bytes/s'
	echo 'graph_category disk'
	echo "graph_info This graph shows IO statistics (total Bytes/s) for $DISK disk."
	# echo 'graph_scale yes'
	echo "kb.info Data transfered (Bytes/s) on the $DISK disk."
	echo 'kb.label Bytes transfered'
	echo 'kb.type DERIVE'
	# echo 'kb.graph no'
	echo 'kb.cdef kb,1024,*'
	echo 'kb.min 0'
	echo ''
	echo 'multigraph xfr'
	echo "graph_title $DISK transfers/s"
	echo 'graph_args --base 1000'
	echo 'graph_vlabel xfr/s'
	echo 'graph_category disk'
	echo "graph_info This graph shows IO statistics (transfers/s) for $DISK disk."
	# echo 'graph_scale yes'
	echo "xfr.info Disk transfers (IOPs) on the $DISK disk."
	echo 'xfr.label Disk transfers'
	echo 'xfr.type DERIVE'
	# echo 'xfr.cdef xfr,8,*'
	echo 'xfr.min 0'

	exit 0
fi

/usr/sbin/iostat -ID $DISK | awk '
	/[[:digit:]]+[[:space:]][[:digit:]]+[[:space:]][[[:digit:]]|\.]+/ {
	if (NF == 3) {
		print "multigraph bytes";
		print "kb.value", $1;
		print "";
		print "multigraph xfr";
		print "xfr.value", $2;
	}
}'

