#!@@PERL@@ -w
#
# Plugin to monitor usage of bind 9 servers
#
# Parameters:
#
# 	logfile      - Location of the query log
# 	statefile    - Where to put temporary statefile.
#
# Contributed by Nicolai Langfeldt
#
# $Log$
# Revision 1.8.2.2  2005/03/07 19:06:13  jimmyo
# sunos/memory repaired (SF#1143610).
#
# Revision 1.8.2.1  2005/02/16 18:03:46  jimmyo
# minor bugfix in generic/bind9.
#
# Revision 1.8  2004/12/10 18:51:43  jimmyo
# linux/apt* has been forced to LANG=C, to get predictable output.
#
# Revision 1.7  2004/12/10 14:21:39  jimmyo
# Patch generic/bind9 to report "unnamed" as "other" (Nicolas Stransky).
#
# Revision 1.6  2004/12/10 10:47:47  jimmyo
# Change name from ${scale} to ${graph_period}, to be more consistent.
#
# Revision 1.5  2004/12/09 22:12:54  jimmyo
# Added "graph_period" option, to make "graph_sums" usable.
#
# Revision 1.4  2004/12/09 20:16:29  jimmyo
# generic/bind9 now handles syslog format as well (by xavier).
#
# Revision 1.3  2004/09/14 20:29:20  jimmyo
# Added statefile parameter.
#
# Revision 1.2  2004/05/14 21:16:46  jimmyo
# "Upped" som plugins from contrib/manual to auto.
#
# Revision 1.1  2004/01/02 18:50:00  jimmyo
# Renamed occurrances of lrrd -> munin
#
# Revision 1.1.1.1  2004/01/02 15:18:07  jimmyo
# Import of LRRD CVS tree after renaming to Munin
#
# Revision 1.1  2003/12/18 21:45:47  jimmyo
# Plugin contributed by Nicolai Langfeldt
#
#
#%# family=contrib

use strict;

my $QUERYLOG=$ENV{logfile} || '/var/log/bind9/query.log';
my $STATEFILE=$ENV{statefile} || '@@PLUGSTATE@@/bind9.state';
my $OTHER=0;
my %IN;

sub get_state {
    open(Q,"< $STATEFILE") or die;
    while (<Q>) {
        chomp;
        my ($q,$n) = split(/\s+/,$_,2);
        $IN{$q}=$n unless defined($IN{$q});
    }
    close(Q);
}


sub do_stats {
    my $k; 

    open(Q,"< $QUERYLOG") or die "$!";
    while (<Q>) {
	chomp;
	if (/client \d+\.\d+.\d+.\d+\#\d+: query\: \S+ (\w+) (\w+)/) {
	    if ($1 eq 'IN' and $2 !~ /^TYPE/) {
		$IN{$2}++;
	    } else {
		$OTHER++;
	    }
	}
    }
    close(Q);

    get_state;

    open(Q,"> $STATEFILE") or die;
    foreach $k (keys %IN) {
	print "query_$k.value ",$IN{$k},"\n";
	print Q "$k ",$IN{$k},"\n";
    }
    close(Q);

    print "query_other.value ",$OTHER,"\n";
}


sub do_config {
    my $k;

    print "graph_title DNS Queries by type
graph_vlabel Queries / \${graph_period}
query_other.label Other
query_other.type DERIVE
query_other.min 0
query_other.draw AREA
";
    get_state;

    foreach $k (keys %IN) {
	print "query_$k.label $k
query_$k.type DERIVE
query_$k.min 0
query_$k.draw STACK
";
    }
};

if (defined($ARGV[0]) and ($ARGV[0] eq 'config')) {
    do_config;
    exit(0);
}

do_stats;


# vim:syntax=perl
