#!@@PERL@@ -w
# -*- perl -*-

=head1 NAME

bind9_rndc - Plugin to monitor usage of bind 9 servers using rndc stats

=head1 CONFIGURATION

The following environment variables are used by this plugin

  [bind_rndc]
    env.rndc		/usr/sbin/rndc
    env.querystats      /var/run/named.stats

The user/group that runs the plugin must have read access to the stats
file.  To change user or group (usually Munin plugins are run as
nobody) add this to the [bind_rndc] stanza if the "bind" user runs
BIND:

    user bind

On the BIND side put

  statistics-file "/var/run/named.stats";

in the options part of your named.conf or set the querystats variable
(see below) to where your named puts the statistics file by default.

You must also make sure the rndc.key file is readable by the user that
runs the plugin.

If using AppArmor, make sure the stats file is allowed
(On Ubuntu: add this line to /etc/apparmor.d/usr.sbin.named)

  /var/run/named/named.stats rw

=head1 FEATURES AND BUGS

Previous versions of this plugin allowed an empty "rndc" environment
setting to not do a explicit dump of stats to the stats file. This
version requires running rndc itself. This makes the method of finding
the correct stats in the file more reliable than before.

=head1 AUTHOR

Contributed by Laurent Facq 15/06/2004. Based on Nicolai Langfeldt's
bind9 plugin. Reworked by Dagfinn Ilmari Mannsåker. BIND 9.6 patch
from "Vrivellino". Reworked by guillomovitch and Kenyon Ralph.

=head1 LICENSE

License not documented.

=head1 MAGIC MARKERS

 #%# family=manual

=cut

use strict;

my $rndc = defined($ENV{rndc}) ? $ENV{rndc} : '/usr/sbin/rndc';
my $querystats = $ENV{querystats} || '/var/run/named.stats';
my %IN;

# attempt to create log file if it doesn't exist
if ( ! -r $querystats ) {
    system("$rndc stats");
}

# open the log file, and get its size
open(my $stats, '<', $querystats) or die "$0: $querystats: $!\n";
my $size = (stat $stats)[7];

# call rdnc and go directly to the correct offset
system("$rndc stats");
seek($stats , $size, 0);

# We want the last block like this in the file (bind 9.early)
#+++ Statistics Dump +++ (1087277501)
#success 106183673
#referral 2103636
#nxrrset 43534220
#nxdomain 47050478
#recursion 37303997
#failure 17522313
#--- Statistics Dump --- (1087277501)

# From BIND 9.5 or newer, this is the format:
#
# +++ Statistics Dump +++ (1222740363)
# ++ Incoming Requests ++
#                   13 QUERY
# ++ Incoming Queries ++
#                    9 A
#                    1 NS
#                    1 SOA
#                    1 MX
#                    1 TXT
# ++ Outgoing Queries ++
# ++ Name Server Statistics ++
#                   13 IPv4 requests received
#                   13 responses sent
#                   13 queries resulted in successful answer
#                    9 queries resulted in authoritative answer
#                    4 queries resulted in non authoritative answer
#                    4 queries caused recursion
#                    2 requested transfers completed
# ++ Zone Maintenance Statistics ++
#                    6 IPv4 notifies sent
# --- Statistics Dump ---

my $line;

# first line has expected content
$line = <$stats>;
die "unexpected content found"
  unless $line =~ m/^\+\+\+ Statistics Dump \+\+\+/;

# second line allows to guess format
$line = <$stats>;
chomp $line;
if ($line eq '++ Incoming Requests ++') {
    # new format

    %IN = (
           requests => 0,
           responses => 0,
           success => 0,
           auth_answer => 0,
           nonauth_answer => 0,
           nxrrset => 0,
           failure => 0,
           nxdomain => 0,
           recursion => 0,
           duplicates => 0,
           transfers => 0,
           rejections => 0,
          );

    # jump to server stats section
    while ($line ne '++ Name Server Statistics ++') {
        $line = <$stats>;
        chomp $line;
    }

    while ($line = <$stats>) {
        chomp $line;
        last if $line =~ /^\+\+/;
        next unless $line =~ /^\s+(\d+) (.*)$/;
        my $n = $1;
        my $msg = lc($2);

        if ($msg =~ m/requests.*received$/io) {
                $IN{requests} += $n;
        } elsif ($msg =~ m/responses.*sent$/io ) {
                $IN{responses} += $n;
        } elsif ($msg eq 'queries resulted in successful answer') {
                $IN{success} = $n;
        } elsif ($msg eq 'queries resulted in authoritative answer') {
                $IN{auth_answer} = $n;
        } elsif ($msg eq 'queries resulted in non authoritative answer') {
                $IN{nonauth_answer} = $n;
        } elsif ($msg eq 'queries resulted in nxrrset') {
                $IN{nxrrset} = $n;
        } elsif ($msg eq 'queries resulted in servfail') {
                $IN{failure} += $n;
        } elsif ($msg eq 'other query failures') {
                $IN{failure} += $n;
        } elsif ($msg eq 'queries resulted in nxdomain') {
                $IN{nxdomain} = $n;
        } elsif ($msg eq 'queries caused recursion') {
                $IN{recursion} = $n;
        } elsif ($msg eq 'duplicate queries received') {
                $IN{duplicates} = $n;
        } elsif ($msg eq 'recursive queries rejected') {
                $IN{rejections} = $n;
        }
}
} else {
        # old format
        $line =~ /^(\w+) (\d+)$/;
        $IN{$1} = $2;

    while (my $line = <$stats>) {
        chomp $line;
        next unless $line =~ /^(\w+) (\d+)$/;
        $IN{$1} = $2;
    }
}

close($stats);

if (defined($ARGV[0]) and ($ARGV[0] eq 'config')) {
    print "graph_title DNS Queries by status\n";
    print "graph_vlabel queries / \${graph_period}\n";
    print "graph_category BIND\n";

    for my $key (keys %IN) {
        print "query_$key.label $key\n";
        print "query_$key.type DERIVE\n";
        print "query_$key.min 0\n";
    }
} else {
    print "query_$_.value $IN{$_}\n" for keys %IN;
}
