#!/bin/bash
# -*- sh -*-

: << =cut

=head1 NAME

dm_cache_occupancy_ - Wildcard-plugin to dm-cache occupancy.

=head1 CONFIGURATION

This plugin does not normally require configuration.

The plugin may need to run as root to determine dm-cache status.
This is configured like this:

  [dm_cache_*]
	  user root

This is a wildcard plugin. To monitor a cached device-mapper volume,
link volume to this file. For example,

  ln -s /usr/share/munin/plugins/dm_cache_occupancy_ \
        /etc/munin/plugins/dm_cache_occupancy_vg_1122____lv_home

will monitor vg_1122-lv_home.

Please note that ____ (4 underscores) is replaced by - (dash) symbol.
This is workaround for http://munin-monitoring.org/ticket/1236

Cached volumes found in dmsetup status can be monitored.

=head1 AUTHOR

Original idea: Steinar H. Gunderson <sgunderson@bigfoot.com>
Found in Google by keywords "munin dm-cache"

Copyright (C) 2014 Vladimir Stackov <amigo.elite@gmail.com>

=head1 LICENSE

GPLv2

=head1 MAGIC MARKERS

 #%# family=auto
 #%# capabilities=autoconf suggest

=cut

CVOL=${0##*dm_cache_occupancy_}
#workaround for http://munin-monitoring.org/ticket/1236
CVOL=${CVOL/____/-}

case $1 in
	autoconf)
		env dmsetup status > /dev/null 2>&1
		if [[ $? -eq 0 ]]; then
			echo yes
			exit 0
		else
			echo "no (env dmsetup returned value > 0)"
			exit 0
		fi
		;;
	suggest)
		dmsetup status | grep ' cache ' | awk -F: '{print $1}'
		exit $?
		;;
	config)
		echo "graph_title $CVOL dm-cache cache occupancy"
		echo 'graph_args --base 1000'
		echo 'graph_vlabel blocks'
		echo 'graph_category disk'
		echo "graph_info This graph shows the dm-cache cache occupancy of the $CVOL cached volume."
		echo 'cache_used_metadata.label Used metadata'
		echo 'cache_used_metadata.info Used metadata blocks for cache'
		echo 'cache_total_metadata.label Total metadata'
		echo 'cache_total_metadata.info Total metadata blocks for cache'
		echo 'cache_used_blocks.label Used blocks'
		echo 'cache_used_blocks.info Used blocks in cache for cache'
		echo 'cache_total_blocks.label Total blocks'
		echo 'cache_total_blocks.info Total blocks in cache for cache'
		echo 'cache_dirty.label Dirty blocks'
		echo 'cache_dirty.info Dirty blocks for cache'

		exit 0
		;;
esac

dmstatus=$(dmsetup status $CVOL)

echo "cache_used_metadata.value $(echo $dmstatus | awk '{print $5}' | awk -F/ '{print $1}')"
echo "cache_total_metadata.value $(echo $dmstatus | awk '{print $5}' | awk -F/ '{print $2}')"
echo "cache_used_blocks.value $(echo $dmstatus | awk '{print $7}' | awk -F/ '{print $1}')"
echo "cache_total_blocks.value $(echo $dmstatus | awk '{print $7}' | awk -F/ '{print $2}')"
echo "cache_dirty.value $(echo $dmstatus | awk '{print $14}')"

