#! /usr/bin/perl
# anders@aftenposten.no, 2007-04-11
# Show the cache hit ratio in Squid

#use Sys::Hostname;
#use Time::HiRes qw( time );
#use IO::Socket;
use Net::SNMP;

# ----- config -----
$oid=".1.3.6.1.4.1.3495.1.3.2.2.1.9.5";
$host="localhost";
$community="foobar";
$port=3401;
# ----- config -----

sub snmpgetvalue {
	my $response = $session->get_request($oid);
	if (!defined($response->{$oid})) {
		return undef;
	} else {
		return $response->{$oid};
	}
}

sub printvalues {
	my $label = shift;

	my ($session, $error) = Net::SNMP->session(
		-hostname => $host,
		-community => $community,
		-port => $port
	);
	if (defined ($session)) {
		my $response = $session->get_request($oid);

		if (!defined($response->{$oid})) {
			print "$label.value 0\n";
			print "misses.value 100\n";
		} else {
			my $value=$response->{$oid};
			print "$label.value $value\n";
			print "misses.value " . (100-$value) . "\n";
		}
	} else {
		die("Can not connect to SNMP agent on $host:$port");
	}
}

if ($ARGV[0] && $ARGV[0] eq "autoconf") {
	print "yes\n";
} elsif ($ARGV[0] && $ARGV[0] eq "config") {
	print "graph_title Cache hit/miss ratio\n";

        print "graph_args --upper-limit 100 -l 0\n";
        print "graph_vlabel % of requests\n";
        print "graph_category squid\n";
        print "graph_info This graph shows the ratio of requests found in the cache and not\n";
        print "graph_order hits misses\n";
        print "graph_scale no\n";

        print "hits.label hits\n";
        print "hits.type GAUGE\n";
        print "hits.graph yes\n";
        print "hits.min 0\n";
        print "hits.max 100\n";
        print "hits.draw AREA\n";

        print "misses.label misses\n";
        print "misses.type GAUGE\n";
        print "misses.graph yes\n";
        print "misses.min 0\n";
        print "misses.max 100\n";
        print "misses.draw STACK\n";
} else {
	printvalues("hits");
}
