#!/bin/sh
#
# 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

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

#!perl -w 
#line 26

BEGIN { unshift @INC, "$ENV{ZEUSHOME}/zxtm/lib/perl",
     "$ENV{ZEUSHOME}/zxtmadmin/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;
use IPC::Open3;
use Time::HiRes qw( usleep clock_gettime CLOCK_MONOTONIC );
use POSIX qw( setsid strftime uname );

use strict;

# this function attaches gdb to a process, prints the backtrace and detaches again
sub gdbbt($);
sub dump_stack($);
sub dbxbt($);


# try to kill a process, first with SIGTERM, then with SIGKILL:
sub killproc($);

my $leeway = 5; # seconds
my $debug = 0 ;
my $dbg_cmd = '';
my $kill = 0;
my $verbose = 0;
my $always_backtrace = 0;
my $quiet = 0;
my $cmdfile = undef;
my $pid = "";
my $isLinux = 0;

setsid();

my( $uname ) = uname();
# Use gdb if isLinux is true.
$isLinux = ( $uname eq 'Linux' || $uname eq 'FreeBSD' );

if( !$isLinux && ($uname ne 'SunOS') ) {
   die "Platform $uname is not supported\n";
}

# Arg parsing (primitive):
while( my $a = shift( @ARGV ) ) {
   if( $a eq '-t' ) {
      $leeway = shift( @ARGV );
      if( !defined( $leeway ) || $leeway !~ /^\d+$/ ) {
         print STDERR "Expected numeric argument to -t\n";
         exit( -1 );
      } elsif( $leeway <= 1 ) {
         print STDERR "Running procmon with a timeout of $leeway second(s) ".
                      "may cause false positives.\nPlease use a timeout of ".
                      "more than 1 second.\n";
         exit( -1 );
      }
   } elsif( $a eq '-p' ) {
      $pid = shift( @ARGV );
   } elsif( $a eq '-d' ) {
      $debug = 1;
      $dbg_cmd = ( $isLinux ) ? 'full' : '-v -l';
   } elsif ( $a eq '-k' ) {
      $kill = 1; # no mercy
   } elsif ( $a eq '-v' ) {
      $verbose = 1;
   } elsif ( $a eq '-a' ) {
      $always_backtrace = 1;
   } elsif ( $a eq '-q' ) {
      $quiet = 1;
   } elsif ( $a eq '-x' ) {
      $cmdfile = shift( @ARGV );
      if( !defined( $cmdfile ) || !-r $cmdfile ) {
         print STDERR "Please provide a valid filename with gdb commands\n";
         exit( -1 );
      }
   } elsif( $a eq '-h' || $a eq '--help' ) {
      print <<EOM;
  Monitors zeus.zxtm parent and child processes.  If any of them appear to hang,
  their backtrace is obtained and (optionally) they are killed.

  Usage: procmon [-t time] [-x file] [-d] [-a] [-q] [-k] [-h] [-v]
          -t: specify time period to allow processes before considering
              them to be hanging (default: 5 seconds, must be greater than 1s)
          -d: assume debug binary, try to get a full backtrace
          -a: always print a backtrace, even if the process was hanging when last checked
          -q: suppress process still hanging message
          -x: specify file with commands for gdb ( Linux only ).
          -k: kill a hanging process after obtaining its backtrace (use at your own risk)
          -v: be verbose about process status
          -h: print this message and exit
EOM
      exit( 0 );
   }
}

my $pidfile = "$ENV{ZEUSHOME}/zxtm/internal/pid";

if( !-r $pidfile ) {
   print STDERR "Cannot read $pidfile -- is the software running?\n";
   exit( -1 );
}

# We must be root, or the ZXTM install user
if( $< ) {
   my @stat = stat( $pidfile );
   die "Cannot stat zxtm symlink: $!\n" unless( @stat );
   if( $stat[4] != $< ) {
      die "You must run this program as root, or as the user who originally installed the Stingray Traffic Manager\n";
   }
}

my $f = "$ENV{ZEUSHOME}/zxtm/internal/status";
my $statusfh = undef;

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

# Turn off output buffering
$| = 1;

my @last_status = (); # undef means was last ok, 1 means was last hanging
my $momentago;
my $m_momentago;
# supervisor loop:
while( 1 ) {
   if( !-r $pidfile ) {
      print STDERR "Cannot read $pidfile - exiting\n";
      exit( -1 );
   }
   seek( $statusfh, 0, 0 );

   my $tstamp = time();
   my $m_tstamp = clock_gettime( CLOCK_MONOTONIC );
   if( defined( $momentago ) ) {
      if( $verbose ) {
         print "m_tstamp = $m_tstamp, m_momentago = $m_momentago, tstamp = $tstamp, momentago = $momentago\n";
      }
      # '2' because two stacktraces could take a little time
      if( $tstamp > $momentago + 2 || $tstamp < $momentago ) {
         # The real-time clock appears to have jumped, but after waking up
         # from a hang (e.g. if we got swapped out), both the realtime and
         # monotonic clocks appear to have jumped.  The monotonic clock
         # doesn't jump when the real-time clock jumps, so that can be used
         # to tell the difference between hangs and clock jumps.
         my $tstamp_f = strftime( "[%d/%b/%Y:%H:%M:%S %z]\t", localtime( $tstamp ) );
         if( $m_tstamp > $m_momentago + 2 ) {
            printf( "$tstamp_f procmon hung for %.3f seconds\n", ($m_tstamp - $m_momentago) );
         } else {
            my $momentago_f = strftime( "[%d/%b/%Y:%H:%M:%S %z]\t", localtime( $momentago ) );
            print( "$momentago_f Clock jump detected -> $tstamp_f (delta: " . ($tstamp - $momentago) . ")\n" );
         }
         $momentago = $tstamp;
         $m_momentago = $m_tstamp;
         sleep( 1 );
         next;
      }
   }
   $momentago = $tstamp;
   $m_momentago = $m_tstamp;
   my $allowed = $m_tstamp - $leeway; # give some seconds of leeway
   my $datetime = strftime( "[%d/%b/%Y:%H:%M:%S %z]\t", localtime( $tstamp ) );

   my $raw = '';
   my $r = sysread( $statusfh, $raw, 2*4*(1024+1) ); # anybody have more than 1k cpus?

   if( $r & 0x1 ) {
      die "Expected even number of bytes\n";
   }
   my @values = unpack( "L*", $raw );
   # remove the second int (it's storing the aptimizer_bandwidth):
   splice( @values, 1, 1 );
   if( scalar( @values ) & 0x1 ) {
      die "Expected even number of unsigned ints\n";
   }
   if( $verbose ) {
      print "Allowed: $allowed -- @values\n";
   }
   my $upper = scalar( @values ) / 2;
   for( my $idx = 0; $idx < $upper; ++$idx ) {
      my $pid = $values[$idx+$upper];
      if( $values[$idx] < $allowed ) {
         # if it was already hanging last time, don't backtrace again (unless forced)
         if( $last_status[$idx] && !$always_backtrace ) {
            if( ! $quiet ) {
               print "$datetime Process $pid still appears to be hanging\n";
            }
         } else {
            print "$datetime Process $pid appears to be hanging\n";
            if( dump_stack( $pid ) ) {
               select( undef, undef, undef, 0.01);
               print "\tSlept 0.01s, dumping stack again:\n";
               dump_stack( $pid );
            }
            if( !$kill || !killproc( $pid ) ) {
               $last_status[$idx] = 1;
            }
            last; # start over, other processes may have recovered by the time gdb is done
         }
      } else {
         if( $last_status[$idx] ) {
            print "$datetime Process $pid has recovered\n";
         }
         $last_status[$idx] = undef;
      }
   }
   sleep( 1 );
}

close( $statusfh );
exit 0;

sub dump_stack($)
{
   my $pid = shift;
   if( kill(0, $pid) ) {
      ( $isLinux ) ? gdbbt( $pid ) : dbxbt( $pid );
   } else {
      print "process $pid not found\n";
      return 0;
   }
   return 1;
}

# --// helper function to get the gdb backtrace:
sub gdbbt($)
{
   my( $pid ) = @_;
   if( !defined( $pid ) || $pid !~ /^\d+$/ ) {
      return;
   }
   my $gdb = `which gdb` || "";
   chomp( $gdb );
   if( $gdb ) {
      my( $chld_out, $chld_in );
      my @gdbargs = ( '-q', '-n',
                   "$ENV{ZEUSHOME}/zxtm/bin/zeus.zxtm", "-pid", $pid );
      if( defined( $cmdfile ) ) {
         push( @gdbargs, '-x', $cmdfile );
      }
      my $gpid = open3( $chld_in, $chld_out, 0, $gdb, @gdbargs );
      if( defined( $gpid ) ) {
         if( !defined( $cmdfile ) ) {
            print( $chld_in <<"EOM" );
handle SIGPIPE nostop noprint
handle SIGHUP nostop noprint
thread apply all bt $dbg_cmd
detach
quit
EOM

         }
         while( my $r = <$chld_out> ) {
            print( $r );
         }
         close( $chld_out );
         close( $chld_in );
         print "\n";
         waitpid( $gpid, 0 );
      } else {
         print STDERR "Failed to exec gdb: $!\n";
      }
   } else {
      print STDERR "Please install gdb to produce backtrace\n";
   }
}

# --// helper function to get the pstack backtrace:
sub dbxbt($)
{
   my( $pid ) = @_;
   if( !defined( $pid ) || $pid !~ /^\d+$/ ) {
      return;
   }
   my $dbx = `which dbx` || "";
   if( $debug && $dbx ) {
      my( $chld_out, $chld_in );
      my @dbxargs = ( '-q', "$ENV{ZEUSHOME}/zxtm/bin/zeus.zxtm", $pid );
      my $dbxpid = open3( $chld_in, $chld_out, 0, "dbx", @dbxargs );
      if( defined( $dbxpid ) ) {
         print( $chld_in <<"EOM" );
where $dbg_cmd
detach
quit
EOM
         while( my $r = <$chld_out> ) {
            print( $r );
         }
         close( $chld_out );
         close( $chld_in );
         print "\n";
         waitpid( $dbxpid, 0 );
      } else {
         print STDERR "Failed to exec dbx: $!\n";
      }
   } else {
      my $perl = <<"EOF";
open PSTACK, "|pstack -F $pid" or die "Cannot execute pstack: \$!\n";
local \$SIG{PIPE} = sub{ die "SIGPIPE recieved while running pstack\n"; };

while( my \$r = <PSTACK> ) {
   print \$r;
}
close PSTACK;
print STDERR "Error occurred while running pstack: ErrorNo: \$?" if( \$? );
EOF

      eval( $perl );
   }
}

sub killproc($)
{
   my( $pid ) = @_;
   if( !defined( $pid ) || $pid !~ /^\d+$/ ) {
      return undef;
   }
   my $killed = kill( 'TERM', $pid );
   if( $killed ) {
      usleep(10000);
      if( !kill( 0, $pid ) ) { # if we can't signal it any longer, it's dead
         print "Process $pid terminated\n";
         return 1;
      } else {
         print "*** Failed to terminate process $pid, trying to kill it...\n";
         $killed = kill( 'KILL', $pid );
         usleep(10000);
         if( $killed ) {
            if( !kill( 0, $pid ) ) { # if we can't signal it any longer, it's dead
               print "Process $pid killed\n";
               return 1;
            } else {
               print "*** Failed to kill process $pid\n";
            }
         } else {
            print "*** Failed to signal process $pid\n";
         }
      }
   } else {
      print "*** Failed to signal process $pid\n";
   }
   return undef;
}
