#!/usr/bin/perl -w
#
# Plugin to monitor memory usage.
#
# Parameters:
#
# 	config   (required)
# 	autoconf (optional - only used by lrrd-config)
#
# $Log: memory.in,v $
# Revision 1.5  2003/11/07 17:43:16  jimmyo
# Cleanups and log entries
#
#
#
# Magic markers (optional - only used by lrrd-config and some
# installation scripts):
#%# family=auto
#%# capabilities=autoconf


if ($ARGV[0] and $ARGV[0] eq "autoconf")
{
	if (-r "/proc/meminfo")
	{
		print "yes\n";
		exit 0;
	}
	else
	{
		print "no (/proc/meminfo not found)\n";
		exit 1;
	}
}

my $totmem = undef;
my %mems = ();
my @memline = ();
my @swapline = ();

&fetch_meminfo (\%mems, \@memline, \@swapline);

if (@memline)
{
	$totmem = $memline[1];
}
else
{
	$totmem = $mems{'MemTotal'}*1024;
}

if ($ARGV[0] and $ARGV[0] eq "config")
{
	print "graph_args --base 1024 -l 0 --vertical-label Bytes --upper-limit ", $totmem, "\n";
	print "graph_title Memory usage\n";
	print "graph_order apps buffers cached free swap\n";
	print "apps.label apps\n";
	print "apps.draw AREA\n";
	print "buffers.label buffers\n";
	print "buffers.draw STACK\n";
	print "swap.label swap\n";
	print "swap.draw STACK\n";
	print "cached.label cache\n";
	print "cached.draw STACK\n";
	print "free.label unused\n";
	print "free.draw STACK\n";
	if (exists $mems{'Committed_AS'})
	{
		print "committed.label committed\n";
		print "committed.draw LINE2\n";
		print "committed.warn ", ($mems{SwapTotal}+$mems{MemTotal})*1024, "\n";
	}
	exit 0;
}


if (@memline)
{
	print "apps.value ", ($memline[1]-$memline[4])-$memline[5], "\n";
	print "free.value ", $memline[2], "\n";
	print "buffers.value ", $memline[4], "\n";
	print "cached.value ", $memline[5], "\n";
	print "swap.value ", $swapline[1], "\n";
}
else
{
	print "apps.value ", ($mems{MemTotal}-$mems{MemFree}-$mems{Buffers}-$mems{Cached}-$mems{SwapCached})*1024, "\n";
	print "free.value ", $mems{MemFree}*1024, "\n";
	print "buffers.value ", $mems{Buffers}*1024, "\n";
	print "cached.value ", ($mems{Cached}+$mems{SwapCached})*1024, "\n";
	print "swap.value ", ($mems{SwapTotal}-$mems{SwapFree})*1024, "\n";
}

if (exists $mems{'Committed_AS'})
{
	print "committed.value ", $mems{'Committed_AS'}*1024 , "\n";
}

sub fetch_meminfo
{
	my ($mems, $memline, $swapline) = @_;
	open (IN, "/proc/meminfo") || die "Could not open /proc/meminfo for reading: $!";
	while (<IN>)
	{
		if (/^Mem:\s+(.+)$/)
		{
			push @{$memline}, split /\s+/, $1;
		}
		elsif (/^Swap:\s+(.+)$/)
		{
			push @{$swapline}, split /\s+/, $1;
		}
		elsif (/^(\w+):\s*(\d+)\s+kb/i)
		{
			$mems->{$1} = $2;
		}
	}
	close (IN);
}
# vim:syntax=perl
