#!/usr/bin/perl -w

# Parse output from bind9 rndc stats command
# Dobrica Pavlinusic, <dpavlin@rot13.org>
# http://www.rot13.org/~dpavlin/sysadm.html
#
# Usage: parse_bind9stat.pl [/var/log/stats.dump [/usr/sbin/rndc]]

use strict;

my $log = shift @ARGV || "/var/log/stats.dump";
my $rndc = shift @ARGV || "/usr/sbin/rndc";
my $delta="/var/tmp/";

system "$rndc stats";

my @counters = qw(success referral nxrrset nxdomain recursion failure);

my %total;
my %forward;
my %reverse;

my $tmp=$log;
$tmp=~s/\W/_/g;
$delta.=$tmp.".offset";

open(DUMP,$log) || die "$log: $!";

if (-e $delta) {
	open(D,$delta) || die "can't open delta file '$delta' for '$log': $!";
	my $offset=<D>;
	chomp $offset;
	close(D);
	my $log_size = -s $log;
	if ($offset <= $log_size) {
		seek(DUMP,$offset,0);
	}
}

while(<DUMP>) {
	next if /^(---|\+\+\+)/;
	chomp;
	my ($what,$nr,$direction) = split(/\s+/,$_,3);
	if (! $direction) {
		$total{$what} += $nr;
	} elsif ($direction =~ m/in-addr.arpa/) {
		$reverse{$what} += $nr;
	} else {
		$forward{$what} += $nr;
	}

}

open(D,"> $delta") || die "can't open delta file '$delta' for log '$log': $!";
print D tell(DUMP);
close(D);

close(DUMP);

foreach (@counters) {
	print $total{$_},"\n",$forward{$_},"\n",$reverse{$_},"\n";
}
