#! /usr/bin/perl
# anders@fupp.net
#
# History:
#
# 2011-08-17:	Update for Varnish 3.
# 2008-06-09:	Use correct data: sma_balloc - sma_bfree
# 2008-04-13:	Update for SMA_balloc, separate stats for the malloc allocator
#		Convert to Perl script, drop support for Varnish 1.0 and older
# 2007-09-19:	Initial shell version
#
# Shows the amount of virtual memory allocated by Varnish for storing cache
# objects

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

%stat = ();
$ENV{PATH} = "/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin";

sub popstat {
	foreach $line (`varnishstat -1`) {
	chomp($line);
		if ($line =~ /^([\w\.]+)\s+(\d+)\s+/) {
			$key = $1;
			$val = $2;

			$stat{"$key"} = $val;
		}
	}
}

sub printconfig {
	printf "graph_title Virtual memory allocated\n";
	printf "graph_vlabel memory\n";
	printf "graph_category varnish\n";
	printf "graph_info This graph shows the amount of virtual memory allocated by Varnish for storing cache objects\n";
	printf "memory.label memory\n";
	printf "memory.type GAUGE\n";
	printf "memory.graph yes\n";
}

if ($ARGV[0] eq "autoconf") {
	print "yes\n";
} elsif ($ARGV[0] eq "config") {
	printconfig;
} else {
	popstat;

	print "memory.value ";
	if (defined $stat{"SMA.s0.nbytes"}) {
		print $stat{"SMA.s0.nbytes"};
	} elsif ($stat{"sm_balloc"} == 0) {
		print $stat{"sma_nbytes"};
	} else {
		print $stat{"sm_balloc"};
	}
	print "\n";
}
