#! /usr/bin/perl
# Nagios plugin to monitor FreeBSD swap meta memory usage
# If you experience "swap zone exhausted, increase kern.maxswzone", you may
# want to use this plugin
#
# anders@fupp.net, 2009-09-07

use Getopt::Std;

getopts('c:w:');

sub usage {
	print "Usage: check_swapmeta -w <warning %> -c <critical %>\n";
	exit(0);
}

if ($opt_w =~ /^(\d+)%$/) {
	$warnlim = $1;
}
if ($opt_c =~ /^(\d+)%$/) {
	$critlim = $1;
}

if (!defined($warnlim) && !defined($critlim)) {
	usage;
}

$ENV{PATH} = "/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin";

foreach $line (`vmstat -z`) {
	if ($line =~ /^SWAPMETA:\s+\d+,\s+(\d+),\s+(\d+)/) {
		$swmlimit = $1;
		$swmused = $2;
		last;
	}
}
#print "swmlimit=$swmlimit swmused=$swmused\n";
$pctfree = ($swmlimit-$swmused)/$swmlimit*100;

if ($pctfree < $critlim) {
	print "Swapmeta lower than critical limit $critlim: ";
	printf("%.2f", $pctfree);
	print "% free\n";
	exit(2);
} elsif ($pctfree < $warnlim) {
	print "Swapmeta lower than warning limit $warnlim: ";
	printf("%.2f", $pctfree);
	print "% free\n";
	exit(1);
} else {
	print "Swapmeta OK: ";
	printf("%.2f", $pctfree);
	print "% free\n";
	exit(0);
}
