1 #!/usr/local/bin/perl -l
    2 
    3 use constant OK       => 0;
    4 use constant WARNING  => 1;
    5 use constant CRITICAL => 2;
    6 use constant UNKNOWN  => 3;
    7 
    8 my $dir = "Maildir";
    9 my $patt = 'X-Rutgers-OriginatingTime (\d+)';
   10 
   11 my ($threshold, $log_filename);
   12 
   13 if ($#ARGV != 1) {
   14     print "Usage: $0 THRESHOLD LOG_OUTPUT_FILE";
   15     exit;
   16 } else {
   17     ($threshold, $log_filename) = @ARGV;
   18 }
   19 
   20 nagios_exit(UNKNOWN, "No Inbound Data") unless my @files = (<$dir/cur/*>, <$dir/new/*>);
   21 @files = sort {(stat($b))[9] <=> (stat($a))[9]} @files;     # sort by file creation-date descending
   22 
   23 my ($msg_filename, $sent);
   24 {
   25     local $/ = undef;   # Makes file contents read in as string ($/ is the split-string for streams)
   26     # open msg file, get time with regexp, then filter out files that don't contain the pattern
   27     @file_cont = grep { $_->[1] } map { [$_, (<F> =~ /$patt/)] if open F, "<$_" } @files;
   28     nagios_exit(UNKNOWN, "No Inbound Data") if ($#file_cont == 0);
   29     ($msg_filename, $sent) = @{@file_cont->[0]};
   30 }
   31 
   32 my $arrv = (stat($msg_filename))[9];
   33 my $latency = $arrv - $sent;
   34 
   35 my $latency_log;
   36 
   37 if ($latency > $threshold) { 
   38     nagios_exit(WARNING, "Latency too high ($latency > $threshold)");
   39 } elsif ($latency <= $threshold) {
   40     nagios_exit(OK, "Latency OK - $latency seconds");
   41 } else {
   42     nagios_exit(UNKNOWN, "Cannot read data");
   43 }
   44 
   45 sub nagios_exit {
   46     my ($ret, $msg) = @_;
   47 
   48     if (!defined($latency) || $ret == UNKNOWN) {    
   49         output_log(-1); # log latency as -1 if we can't read files or data
   50     } elsif ($latency < 0) {
   51         output_log(0);  # round negative times to zero
   52     } else {
   53         output_log($latency);
   54     }
   55 
   56     print $msg;
   57     exit $ret;
   58 }
   59 
   60 sub output_log {
   61     my $latency_log = shift;
   62         
   63     # Currently doesn't report errors with opening or writing to the log file.
   64     return unless open LOG, ">> $log_filename"; 
   65 
   66     use Time::localtime;
   67     my $tm = localtime();
   68     my $stamp = join('-', ($tm->year+1900, $tm->mon+1, $tm->mday))
   69         . ' ' . join(':', ($tm->hour, $tm->min, $tm->sec));
   70     print LOG "$stamp,$latency_log";
   71     close(LOG);
   72 }