#!/usr/bin/perl -w

# Copyright (C) 2000-2014, Riverbed Technology, Inc. All rights reserved.
#
# This program is provided as part of the Stingray Server product
# available from Zeus Technology Limited.  It is intended to process error
# log files produced by the server and to provide an example to
# customers upon which further customisation can be undertaken.  This
# program, and any derived works may be used freely by customers for
# the purpose to which it is intended.
#
# This software is provided "as is" and any express or implied
# warranties, including but not limited to, the implied warranties of
# merchantability and fitness for a particular purpose are disclaimed.
# In no event shall Zeus Technology Limited. be liable for any direct,
# indirect, incidental, special, exemplary, or consequential damaged
# (including, but not limited to, procurement of substitute good or
# services; loss of use, data, or profits; or business interruption)
# however caused and on theory of liability.  Whether in contract,
# strict liability or tort (including negligence or otherwise) arising
# in any way out of the use of this software, even if advised of the
# possibility of such damage.
#
# For further information regarding this piece of software, please e-mail
# support@riverbed.com

=head1 NAME

errormailer - mail parts of the error logs to an admin

=head1 SYNOPSIS

B<errormailer> B<logfile> B<email address> [ B<--hour> I<x> | B<--min> I<x> ]

=head1 DESCRIPTION

This program is designed to search through the admin, web or user
specified error log files and locate any potentially important
information. This information is then e-mailed to whoever is
specified on the command line. The information this program "rips
out" of the log files is any line that has a level value of : B<WARN>,
B<SERIOUS> or B<FATAL>.

The most basic use of this program is just to specify which file you
wish to analyse and who to email the results to, e.g.

    errormailer /usr/local/zeus/log/web webmaster@your_domain.com

However this will analyse the whole log file which could take a long
time for a large file. Therefore you can specify how long back, from
now, to search, e.g.

    errormailer /usr/local/zeus/log/web webmaster@your_domain.com --hour 24

The above command will check the log file for any entries occurring in
the last day ( 24 hours ). You can also search using minutes which can
be useful if you think something important happened very recently, e.g.

    errormailer /usr/local/zeus/log/web webmaster@your_domain.com --min 5

The above command will search the log file for any relevant entries in
the last 5 minutes.

Probably the most constructive use of this program is to set it up as
a cronjob analysing, for example, the last 24 hours and mailing the
results to your webmaster. This can be achieved by executing the
following steps :

    crontab -u <name_of_user> -e

The above command will invoke the environment set text editor to
modify the crontab table for the user you specify ( to analyse the
.../zeus/log/web or admin files this will be the root crontab ). Next
add a line such as :

    59 23 * * * /usr/local/zeus/bin/errormailer /usr/local/zeus/web \
    webmaster@your_domain.com --hour 24

This will cause the errormailer to be called at 11:59pm. The correct
path to the errormailer must be specified. All command line
arguments are as described above.

Another use is to have it set up for customers. In the General
Configuration page of the webserver it is possible to set up
individual error logs for each website. If this has been set up it
is possible to run the errormailer on this log file an email
the results to the customer. E.g.

    errormailer /location_of_customers_log_file \
                customer@wherever.com --hour 24

This could also be automated as described above.

B<errormailer> is a component of the administration server package, and is 
located in I<$ZEUSHOME/admin/bin/> on an Administration Server machine.

=head1 OPTIONS

=over 8

=item B<--hour>

How many hours back (from now) to check

=item B<--min>

How many minutes back (from now) to check

=back

=head1 NOTES

B<errormailer> requires that perl be installed on your system.

=head1 COPYRIGHT

Copyright (C) 2000-2014 Zeus Technology Limited. All rights reserved.

=cut


use Time::Local;

sub help( $ ) {
   my $f = shift;

   ( print $f
     "Usage:\n",
     "\n",
     "  errormailer [OPTIONS] <logfile> <e-mail address>\n",
     "\n",
     "  --hour N                       check N hours back from present\n",
     "  --min N                        check N minutes back from present\n",
     "  --print                        output to stdout, don't send email\n",
   );
}

my $file;
my $to;
$starttime = 0;
$endtime   = time;

my $optionsValid = 1;

while( @ARGV > 0 ) {
   local $_ = shift;
   if( /^-/ && $optionsValid ) {
      if( /^--help$/ ) {
         help( *STDOUT );
         exit( 0 );
      } elsif( /^--?(hour|min)$/ ) {
         #
         # NB - these two options used to be -hour and -min, don't
         # break backwards compatibility.
         #
         # NB2: historically these two options have always appeared
         # AFTER the logfile and email address, don't break backwards
         # compatibility.
         #
         my $s = shift;
         die "$0: missing argument to '$_'\n" if ! defined $s;
         die "$0: invalid argument to '$_'\n" if $s =~ /\D/;
         $s *= ( /hour/ ? 60 * 60 : 60 );
         $starttime = $endtime - $s;
      } elsif( /^--print$/ ) {
         $print = 1;
      } elsif( /^--$/ ) {
         $optionsValid = 0;
      } else {
         die "$0: unknown option '$_'\n";
      }
   } else {
      if( ! defined $file ) {
         $file = $_;
      } elsif( ! defined $to ) {
         $to = $_;
      } else {
         die "$0: too many non-option arguments\n";
      }
   }
}

die "$0: no logfile specified\n" if ! defined $file;
die "$0: no destination address specified\n" if ! defined $to;

# use to filter out non-errors
%report = ( "WARN" => "1", "SERIOUS" =>  "1", "FATAL" =>  "1");

# use to hold list of errors before placing in email
@errorlist = ();

# need for converting zeus alphabetical month value into a numerical
# value
%months = (
	   Jan => 0,
	   Feb => 1,
	   Mar => 2,
	   Apr => 3,
	   May => 4,
	   Jun => 5,
	   Jul => 6,
	   Aug => 7,
	   Sep => 8,
	   Oct => 9,
	   Nov => 10,
	   Dec => 11,
	   );

# open file and check for errors
open(INFO, $file) or die "Can't open file '$file': $!\n";

while ( <INFO> ) {

    # ignore lines with incorrect formatting e.g. CGI errors
    next if ( ! /^\[\d\d\/...\/\d{4}:\d\d:\d\d:\d\d\s\+\d{4}\]/ );

    # convert zeus log time to seconds since 1970
    $line = $_;
    $line =~ s/\s.*//;
    $line =~ s/\[//;
    $line =~ s/\//:/g;
    @action = split(/:/, $line);
    $action[1] = $months { $action[1] };
    $time_of_log = timelocal($action[5], $action[4], $action[3],
			     $action[0], $action[1], $action[2]);

    # check if the date of the log entry falls within the limits
    # specified by the user
    next if ( ($time_of_log < $starttime) || ($time_of_log > $endtime ) );

    /^\[.*\] ([^:]*)/;
    #thus $1 is INFO, WARN, SERIOUS, FATAL

    # if there is an error put it in @errorlist
    if ( defined ( $report{ $1 } ) ) {
	push(@errorlist, $_);
    }
}

close(INFO);

# if no errors have been found stop the program before sending a useless
# message

if ( ! @errorlist ) {
    print "No errors were found\n";
    exit;
}

if( $print ) {
   open( MAIL, ">&STDOUT" ) or
     die "$0: redirection: $!";
} else {
   # find out where sendmail is located
   undef $sendmail;
   @sendmail_locations = ( "/usr/sbin/sendmail", "/usr/lib/sendmail" );
   for $which ( @sendmail_locations ) {
      if ( -e $which ) {
         $sendmail = $which;
      }
   }

   # if can't find where sendmail is located print an error and exit
   if (! defined ( $sendmail ) ) {
      print "Cannot find your sendmail file\n";
      exit;
   }

   # otherwise send mail
   open(MAIL, "|$sendmail $to >/dev/null 2>/dev/null") or
     die "Cannot find sendmail : $!\n";
}

print MAIL "From: Zeus_error_log_analyzer\n";
print MAIL "To: $to\n";
print MAIL "Subject: Error log entries for $file\n\n";
print MAIL join '', @errorlist;
close(MAIL);

