#!/usr/bin/perl -w
#
# Plugin to monitor BGP table summary statistics on a cisco router.
#
# Original Author: Peter Holzleitner
#
# Revision 1.1  2010/10/14 19:19
#
# Configuration variables:
#
# 	iosuser - username (default "")
# 	iospass - password (default "")
#
# Parameters:
#
# 	config    (required)
#
# Magic markers (optional - only used by munin-config and some
# installation scripts):
#%# family=auto


use Net::Telnet::Cisco;
use Sys::Syslog;


if ($0 =~ /^(?:|.*\/)cisco_bgp_([^_]+)$/) {
    $host  = $1;
    }

($^O eq "linux" || $^O eq "openbsd") && Sys::Syslog::setlogsock('unix');
openlog('munin.bgp', 'cons,pid', 'daemon');


my @BGP_nbr;
my @BGP_pfx;
my $tot_pfx;
my $iosuser = $ENV{iosuser} || "";
my $iospass = $ENV{iospass} || "";

&fetch_bgpstats($host, $iosuser, $iospass);


if ($ARGV[0] and $ARGV[0] eq "config") {
    print "host_name $host\n";
    print "graph_args --base 1024 -l 0 --vertical-label Prefixes\n";
    print "graph_title BGP Neighbour Statistics\n";
    print "graph_category network\n";
    print "graph_info This graph shows the number of BGP prefixes received by neighbour.\n";

    my($n, $i);  $n = scalar @BGP_nbr;  $i = 0;
    while($n--) {
	my $neigh = $BGP_nbr[$i++];
	print "n$i.label $neigh\n";
	}

#    print "total.label Total\n";
#    print "total.info Total number of prefixes in the BGP table\n";

    } else {

    my($n, $i);  $n = scalar @BGP_nbr;  $i = 0;
    while($n--) {
        my $pfx   = $BGP_pfx[$i++];
        print "n$i.value $pfx\n";
        }
#    print "total.value $tot_pfx\n";
    }




sub fetch_bgpstats
    {
    my $hostname = shift;
    my $username = shift;
    my $password = shift;
    my $session = Net::Telnet::Cisco->new(Host => $host);

    $session->login($username, $password);
    $session->cmd('terminal length 200');
    $session->cmd('terminal width 200');
    my @output = $session->cmd('show ip bgp summary');

# example output of router
# ------------------------
# [...]
# Neighbor        V          AS MsgRcvd MsgSent   TblVer  InQ OutQ Up/Down  State/PfxRcd
# 11.111.11.111   4      98765 12403694  509571 308911893    0    0 1d23h      329193
# 122.122.122.122 4       1234 13242856  383827 308911879    0    0 00:08:22   330761

    foreach(@output) {
        chomp; s/\r//g;
	$tot_pfx = $1 if /^BGP activity (\d+)\/(\d+) prefixes/;
        syslog('debug', "$hostname: $_\n");

	next unless /^(\d+\.\d+\.\d+\.\d+)\s+\d+\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+[0-9a-z:]+\s+(\d+)/;
	my ($neigh, $as, $pfx) = ($1, $2, $3);
        syslog('debug', "$neigh (AS $as)");
	push @BGP_nbr,  "$neigh (AS $as)";
	push @BGP_pfx,  $pfx;
	}
    }


# vim:syntax=perl:ts=8
