#  SubNetIO.pm - a FlowScan-derived class for reporting on traffic I/O
#  Copyright (C) 1999-2001  Dave Plonka
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

# $Id: SubNetIO.pm,v 1.27 2001/02/28 20:17:40 dplonka Exp $
# Dave Plonka <plonka@doit.wisc.edu>

use strict;

package SubNetIO;

require 5;
require Exporter;

use CampusIO 1.053;

@SubNetIO::ISA=qw(CampusIO Exporter);
# convert the RCS revision to a reasonable Exporter VERSION:
'$Revision: 1.27 $' =~ m/(\d+)\.(\d+)/ && (( $SubNetIO::VERSION ) = sprintf("%d.%03d", $1, $2));

=head1 NAME

SubNetIO - a FlowScan module for reporting on campus traffic I/O by subnet

=head1 SYNOPSIS

   $ flowscan SubNetIO

or in F<flowscan.cf>:

   ReportClasses SubNetIO

=head1 DESCRIPTION

SubNetIO is a flowscan report for reporting on flows of traffic in and
out of specific subnets within a site or campus.  It is implemented as
a class derived from CampusIO, so you run either CampusIO or SubNetIO,
not both, since SubNetIO inherits all the functionality of CampusIO.
For instance, in your F<flowscan.cf>:

   ReportClasses SubNetIO

=head1 CONFIGURATION

C<SubNetIO>'s configuration file is F<SubNetIO.cf>.  This configuration
file is located in the directory in which the F<flowscan> script
resides.

The SubNetIO configuration directives include:

=over 4

=item B<SubnetFiles>

This directive is required.  It is a a comma-seperated list of files
containing the definitions of the subnets on which you'd like to
report.
E.g.:

   # SubnetFiles our_subnets.boulder
   SubnetFiles bin/our_subnets.boulder

=item B<OutputDir>

This directive is required.
It is the directory in which RRD files will be written.
E.g.:

   # OutputDir /var/local/flows/graphs
   OutputDir graphs

=item B<Verbose>

This directive is optional.
If non-zero, it makes C<flowscan> more verbose with respect to messages
and warnings.  Currently the values C<1> and C<2> are understood, the
higher value causing more messages to be produced.
E.g.:

   # Verbose (OPTIONAL, non-zero = true)
   Verbose 1

=item B<TopN>

This directive is optional.  It's use requires the C<HTML::Table> perl
module.  C<TopN> is the number of entries to show in the tables that
will be generated in HTML top reports.  E.g.:

   # TopN (OPTIONAL)
   TopN 10

If you'd prefer to see hostnames rather than IP addresses in your top
reports, use the F<ip2hostname> script.  E.g.:

   $ ip2hostname -I *.*.*.*_*.html

=item B<ReportPrefixFormat>

This directive is optional.  It is used to specify the file name prefix
for the HTML "Top Talkers" reports.  You should use strftime(3) format
specifiers in the value, and it may also specify sub-directories.  If
not set, the prefix defaults to the null string, which means that,
every five minutes, subsequent reports will overwrite the previous.
E.g.:

   # Preserve one day of HTML reports using the time of day as the dir name:
   ReportPrefixFormat html/SubNetIO/%H:%M/

or:

   # Preserve one month by using the day of month in the dir name (like sar(1)):
   ReportPrefixFormat html/SubNetIO/%d/%H:%M_

=back

=cut

use Cflow qw(:flowvars 1.015); # for use in wanted sub
use RRDs;
use Boulder::Stream;
use IO::File;
use File::Basename;
use POSIX; # for mktime, strftime
use ConfigReader::DirectiveStyle;
use Net::Patricia 1.010;

my $c = new ConfigReader::DirectiveStyle;
$c->required('OutputDir');
$c->directive('SubnetFiles');
$c->directive('Verbose');
$c->directive('TopN');
$c->directive('ReportPrefixFormat');
$c->load("${FindBin::Bin}/SubNetIO.cf");

if (1 <= $c->value('Verbose')) {
   $SubNetIO::verbose = 1
}
if (2 <= $c->value('Verbose')) {
   $SubNetIO::Verbose = 1
}

# outputdir can be absolute or relative (to the flow file's directory):
$SubNetIO::outputdir = $c->value('OutputDir');

$SubNetIO::thingy; # this is a global set by report subroutine and used by the sort subs
$SubNetIO::thing = 'bytes';

@SubNetIO::subnet_files = split(m/\s*,\s*/, $c->value('SubnetFiles'));

$SubNetIO::TopN = $c->value('TopN');

# { initialize the Patricia Trie
$SubNetIO::patricia = new Net::Patricia;
die unless ref($SubNetIO::patricia);

@SubNetIO::subnets_files = <@SubNetIO::subnet_files>;
my($subnets_file, $stream, $cargo);
foreach $subnets_file (@SubNetIO::subnets_files) {
   print(STDERR "Loading \"$subnets_file\" ...\n") if -t;
   my $fh = new IO::File "<$subnets_file";
   $fh || die "open \"$subnets_file\", \"r\": $!\n";
   $stream = new Boulder::Stream $fh;
   while ($cargo = $stream->read_record) {
      my $subnet = $cargo->get('SUBNET');
      die unless $subnet;
      my $collision;
      if ($collision = $SubNetIO::patricia->match_string($subnet)) {
         warn "$subnet patricia->add skipped - collided with $collision->{SUBNET}\n";
	 next;
      }
      my $hr = { SUBNET => $subnet };
      if (!$SubNetIO::patricia->add_string($subnet, $hr)) {
         warn "$subnet patricia->add failed!\n";
      }
   }
   undef $fh
}

# }

sub new {
   my $self = {};
   my $class = shift;
   CampusIO::_init($self);
   return bless _init($self), $class
}

sub _init {
   my $self = shift;
   return $self
}

sub wanted {
   my $self = shift;
   my $ref;
   my $which; # 'in' or 'out'
   my $hr; # hashref to src/dst host stats

   my $rv = $self->SUPER::wanted;
   return($rv) unless $rv;
   
   if ('out' eq $self->{CampusIO}{which}) { # looks like it's an outbound flow
      $which = 'out';
      $cargo = $SubNetIO::patricia->match_integer($srcaddr);
      return($rv) unless ref($cargo);

      if (!($hr = $cargo->{src_pt}->match_integer($srcaddr))) {
         $hr = $cargo->{src_pt}->add_string($srcip, { addr => $srcip,
						      bytes => 0,
					              pkts => 0,
					              flows => 0 });
	 die unless ref($hr)
      }
   } else { # Hmm, this is an inbound flow...
      die unless 'in' eq $self->{CampusIO}{which};
      $which = 'in';
      $cargo = $SubNetIO::patricia->match_integer($dstaddr);
      return($rv) unless ref($cargo);

      if (!($hr = $cargo->{dst_pt}->match_integer($dstaddr))) {
         $hr = $cargo->{dst_pt}->add_string($dstip, { addr => $dstip,
						      bytes => 0,
					              pkts => 0,
					              flows => 0 });
	 die unless ref($hr)
      }
   }

   # keep subnet in/out stats:
   $cargo->{$which}{bytes} += $bytes;
   $cargo->{$which}{pkts} += $pkts;
   $cargo->{$which}{flows}++;

   # keep stats by src or dst address within subnet:
   $hr->{bytes} += $bytes;
   $hr->{pkts} += $pkts;
   $hr->{flows}++;

   return($rv)
}

sub perfile {
   my $self = shift;
   my $file = shift;
   $self->SUPER::perfile($file);
   if ('' eq ${SubNetIO::outputdir}) { # write to the same directory
      $self->{outputdir} = dirname($file)
   } elsif (${SubNetIO::outputdir} =~ m|^/|) { # write to the absolute directory
      $self->{outputdir} = ${SubNetIO::outputdir}
   } else { # write to the relative directory
      $self->{outputdir} = dirname($file) . '/' . ${SubNetIO::outputdir}
   }

   # (re-)initialize the patricia tries of active src and dst hosts
   $SubNetIO::patricia->climb(sub { $self->clear_node_users(@_) });
}

sub report {
   my $self = shift;
   $self->SUPER::report;
   $SubNetIO::patricia->climb(sub { $self->report_node(@_, $SubNetIO::TopN,
					     $c->value('ReportPrefixFormat')) })
}

sub clear_node {
   my $hr = shift(@_);
   die unless ref($hr);
   foreach my $which ('in', 'out') {
      foreach my $thingy ('bytes', 'pkts', 'flows') {
         $hr->{$which}{$thingy} = 0
      }
   }
}

sub DESTROY {
   my $self = shift;
   # zero the subnet counters (since they are class-level rather than
   # instance-level data objects)
   $SubNetIO::patricia->climb(\&clear_node);
   $self->SUPER::DESTROY
}

=head1 BUGS

=head1 AUTHOR

Dave Plonka <plonka@doit.wisc.edu>

Copyright (C) 1999-2001  Dave Plonka.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

=head1 VERSION

The version number is the module file RCS revision number (B<$Revision: 1.27 $>)
with the minor number printed right justified with leading zeroes to 3
decimal places.  For instance, RCS revision 1.1 would yield a package version
number of 1.001.

This is so that revision 1.10 (which is version 1.010), for example, will
test greater than revision 1.2 (which is version 1.002) when you want to
B<require> a minimum version of this module.

=cut

1
