#!/usr/bin/perl -w

=head1 NAME

btrfs_subvol_usage - Plugin to monitor usage of BTRFS subvolumes

=head1 CONFIGURATION

Must be run as root and you have to specify the path to the filesystem

[btrfs_usage]
user root
env.fsroot /path/to/btrfs/filesystem

=head1 MAGIC MARKERS

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

=head1 USAGE

Link/Copy this plugin to /etc/munin/plugins/ and restart the munin-node. 
 
=head1 AUTHOR

Alexander Knöbel <alex@belogy.de>

=head1 LICENSE

GPLv2

=cut

use strict;
use Munin::Plugin;

if ($ARGV[0] and $ARGV[0] eq 'autoconf') {
	if (-e "/sbin/btrfs") {
		print "yes\n";
	} else {
		print "no (/sbin/btrfs is missing)\n";
	}
	exit 0;
}

my @fsroot;
if ( !defined( $ENV{"fsroot"} ) ) {
	die "No fsroot given! See the manual at top of this plugin file.";
}
@fsroot = $ENV{"fsroot"};

# get subvolumes
my %subvols;
open(SVS, "btrfs subvolume list --sort=path @fsroot |")
	or die("Failed to run 'btrfs subvolume list': " . $!);
while (my $line = <SVS>) {
	chomp $line;
	$line =~ s/ID ([0-9]+) gen ([0-9]+) top level ([0-9]+) path (.+)//;
	$subvols{$1}->{id} = $1;
	$subvols{$1}->{name} = $4;
}
close SVS;

# get sizes from quota
open(QGS, "btrfs qgroup show @fsroot |")
	or die("Failed to run 'btrfs qgroup show': " . $!);
while (my $line = <QGS>) {
	chomp $line;
	$line =~ s|([0-9]+)/([0-9]+)\s+([0-9]+)\s+([0-9]+)||;
	if (defined($2) && defined($subvols{$2})) {
		$subvols{$2}->{rfer} = $3;
		$subvols{$2}->{excl} = $4;
	}
}
close QGS;

# print config
if ($ARGV[0] and $ARGV[0] eq 'config') {
	print "btrfs_usage\n";
	print "graph_title BTRFS Subvolume usage\n";
	print "graph_args --base 1024 --lower-limit 0\n";
	print "graph_vlabel Bytes\n";
	print "graph_category disk\n";

	for my $id (sort { $subvols{$a}->{name} cmp $subvols{$b}->{name} } keys %subvols) {
		print "$id.label " . $subvols{$id}->{name} . "\n";
		print "$id.type GAUGE\n";
		print "$id.draw LINE2\n";
	}

	exit 0;
}

# print usage
print "btrfs_subvol_usage\n";
for my $id (sort { $subvols{$a}->{name} cmp $subvols{$b}->{name} } keys %subvols) {
	print "$id.value " . $subvols{$id}->{rfer} . "\n";
}
