#!/bin/sh
#
# Show monitor shared memory status

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/..
    cd ..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
   echo "$0 FATAL: ZEUSHOME not set"
   exit 1
fi

# Try to get all needed commands in our PATH
PATH=/sbin:/usr/sbin:$PATH

# Restart ourselves in perl
exec $ZEUSHOME/perl/miniperl -x $0 ${1+"$@"}

#!perl -w
#line 31

# Don't use 'strict', if you do, we need to pull the zeus perl paths,
# and there isn't overly much point
#use strict;

BEGIN {
   # make sure we have all the perl modules we need
   unshift( @INC, "$ENV{ZEUSHOME}/zxtmadmin/lib/perl",
            "$ENV{ZEUSHOME}/admin/lib/perl",
            "$ENV{ZEUSHOME}/zxtm/lib/perl",
            "$ENV{ZEUSHOME}/perl" );
}

# Perl doesn't seem to have a decent built-in mmap (there's a module, but who
# knows whether that's installed).  We use PerlIO's :mmap which means we have to
# re-read the shared mem over and over

use PerlIO;

my $f;
my $sleeptime = 20;
my $verbose = 0;

# Arg parsing (primitive):
while( my $a = shift( @ARGV ) ) {

   if( $a eq '-t' ) {
      $sleeptime = shift( @ARGV );
      if( !defined( $sleeptime ) || $sleeptime !~ /^\d+$/ ) {
         print STDERR "Expected numeric argument to -t\n";
         exit( -1 );
      }
      print "Delay: ${sleeptime}\n";
   } elsif( $a eq '-f' ) {
      $f = shift( @ARGV );
   } elsif( $a eq '-v' ) {
      $verbose = 1;
   } elsif( $a eq '--help' || $a eq '-h' ) {
      print "Usage: moncheck [-t delay] [-f .../zxtm/internal/monitors] [-v]\n";
      exit 0;
   } else {
      die "$0: Unknown argument: $a\n";
   }
}

if( !defined( $f ) ) {
   $f = "$ENV{ZEUSHOME}/zxtm/internal/monitors";
}

my $monfh = undef;

if( !open( $monfh, "<:mmap", $f ) ) {
   die "Cannot open $f: $!";
}

my $poolf = "$ENV{ZEUSHOME}/zxtm/internal/pools";
my $poolfh = undef;

if( !open( $poolfh, "<:mmap", $poolf ) ) {
   die "Cannot open $poolf: $!";
}

my $format = "I!i!i!I!I!I!I!";
my $structlen = length( pack( $format ) );

my $poolformat = "I!I!I!";
my $poolstructlen = length( pack( $poolformat ) );

#print "size of node info in shared mem: $structlen\n";
my $siz = -s $f;
if( $siz % $structlen ) {
   die "Expected file size to be multiple of $structlen, got $siz (remainder: " . $siz%$structlen . ")";
}
my $entries = $siz / $structlen;


my %reasons = (
               0 => 'no_error',
               1 => 'connect_timeout',  # the connect timed out
               2 => 'connect_fail'   ,  # the connect failed
               3 => 'read_timeout'   ,  # timeout while waiting to read data
               4 => 'read_fail'      ,  # the read failed
               5 => 'write_fail'     ,  # a write failed
               6 => 'console_kill'   ,  # killed from the console
               7 => 'ssl_conn_error' ,  # An SSL protocol error occured
               8 => 'monitor_fail'   ,  # A monitor has failed
               9 => 'http_invalid'   ,  # The node returned invalid HTTP
               10 => 'http_503_error'   # The node returned a 503 response
              );

my $poolsiz = -s $poolf;
if( $poolsiz % $poolstructlen ) {
   die "Expected file size to be multiple of $poolstructlen, got $poolsiz (remainder: " . $poolsiz%$poolstructlen . ")";
}
my $poolentries = $poolsiz / $poolstructlen;


# main loop:
while( 1 ) {

   seek( $monfh, 0, 0 );

   my $raw = '';
   my $r = sysread( $monfh, $raw, $siz ); # read in the whole file

   if( !defined( $r ) || $r != $siz ) {
      die "read failed: " . ( defined( $r ) )? "got $r bytes, wanted $siz" : $!;
   }
   print time(), "\n";
   for( my $idx = 0; $idx < $entries; ++$idx ) {
      my $offset = $idx * $structlen;
      my $struct = substr( $raw, $offset, $structlen );
      my @values = unpack( $format, $struct );
      my( $lastfail ) = splice( @values, 3, 1 );
      if( $verbose && scalar( grep { $_ != 0 } @values ) || $lastfail != 0 || $values[0] != 0 ) {

         my $reason = $reasons{$lastfail} || 'unknown';

         printf( "Node Id %5d: -> %16s (%2u, flags: %u): %3d conns %3d reqs, ".
                 "first_failed: %10u, last_failed: %10u, failures: %5u \n",
                 $idx, $reason, $lastfail, @values );
      }
   }

   seek( $poolfh, 0, 0 );

   $raw = '';
   $r = sysread( $poolfh, $raw, $poolsiz ); # read in the whole file

   if( !defined( $r ) || $r != $poolsiz ) {
      die "read failed: " . ( defined( $r ) )? "got $r bytes, wanted $poolsiz" : $!;
   }


   print "\nPool State\n";
   print time(), "\n";
   for( my $idx = 0; $idx < $poolentries; ++$idx ) {
      my $offset = $idx * $poolstructlen;
      my $struct = substr( $raw, $offset, $poolstructlen );
      my @values = unpack( $poolformat, $struct );
      next if( 0 == $values[0] ); # not in use
      printf( "Pool Id: %5d: RR-counter= %u total_failtime= %u\n",
              $idx, $values[1], $values[2] );

   }

   sleep( $sleeptime );
}

close( $monfh );
exit( 0 );
