#!/bin/sh
#
# A wrapper program to make running strace on ZXTM easier

# 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 "trace 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;

$| = 1;

# The program to use depends on the OS
my $os = `uname`;
chomp( $os );
my( $strace, $times, $verbose, $follow );
$os = "MacOSX" if $os eq 'Darwin';


if( $os eq 'Linux' ) {
   $strace   = 'strace';
   $times    = '-ttT';
   $verbose  = '-s 2048';
   $follow   = '-f';
} elsif( $os eq 'FreeBSD' || $os eq 'MacOSX' ) {
   $strace   = 'ktrace';
   $times    = '';
   $verbose  = '';
   $follow   = '-i';
} elsif( $os eq 'SunOS' ) {
   $strace   = 'truss';
   $times    = '-d';
   $verbose  = '-a -e -vall -rall -wall';
   $follow   = '-f';
} elsif( $os eq 'HP-UX' ) {
   $strace   = 'tusc';
   $times    = '-T ""';
   $verbose  = '-r all -w all';
   $follow   = '-f';
} elsif( $os eq 'AIX' ) {
   $strace   = 'truss';
   $times    = '-d';
   $verbose  = '-rall -wall';
   $follow   = '-f';
} else {
   die "Sorry, I don't know how to trace processes in this OS ($os)\n";
}

# Check for trace program in path
my $found = 0;
foreach my $entry ( split /:/, $ENV{PATH} ) {
   if( -x "$entry/$strace" ) {
      $found = 1;
      last;
   }
}
if( ! $found ) {
   print STDERR "ERROR: The '$strace' program could not be found in your path.\n";
   print STDERR "ERROR: Please refer to your OS documentation for instructions on how to install it\n";
   exit 1;
}

my $cmd = "$strace $times";
my $usage = 0;
my $options = 0;
my @progs = (); # Defaults to the child processes
my $onechild = 0;
my %childpids = ();
my $pidfile = "$ENV{ZEUSHOME}/zxtm/internal/pid";

foreach my $arg ( @ARGV ) {
   if( $options ) {
      $options = 0;
      $cmd .= ' ' . $arg;
   } elsif( $arg eq '--verbose' ) {
      $cmd .= ' ' . $verbose;
   } elsif( $arg eq '--follow' ) {
      $cmd .= ' ' . $follow;
   } elsif( $arg eq '--options' ) {
      $options = 1;
   } elsif( $arg eq '--parent' ) {
      push @progs, "parent";
   } elsif( $arg eq '--children' ) {
      push @progs, "child";
   } elsif( $arg eq '--child' ) {
      $onechild = 1;
   } elsif( $arg =~ /--child=([\d,]+)/ ) {
       %childpids = map { $_ => 1 } split( ',', $1 );
   } elsif( $arg eq '--eventd' ) {
      push @progs, 'zeus.eventd';
   } elsif( $arg eq '--flipper' ) {
      push @progs, 'zeus.flipper';
   } elsif( $arg eq '--sysd' ) {
      push @progs, 'zeus.sysd';
   } elsif( $arg eq '--admin' ) {
      $pidfile = "$ENV{ZEUSHOME}/admin/internal/pid";
   } elsif( $arg eq '--configd' ) {
      # The configd process is a stand alone process, so mark as a parent
      push @progs, "parent";
      $pidfile = "$ENV{ZEUSHOME}/zxtm/internal-configd/pid";
   } elsif( $arg eq '--monitor' ) {
      push @progs, 'zeus.monitor';
   } elsif( $arg eq '--help' ) {
      $usage = 1;
      last;
   } else {
      warn "Unknown parameter '$arg'\n";
      $usage = 2;
      last;
   }
}
@progs = ( "child" ) if ! scalar @progs;

$usage = 2 if( $options );

if( $usage ) {
   my $text = <<TEXT;
Usage: $0 [optional arguments]

This utility provides a system call trace of the traffic manager. This
can be useful for tracking down support issues.

Arguments:
    --verbose             Be more verbose in the output
    --options PARAMETERS  Add these extra parameters to the command run

Choosing the process to trace:
    --children            Trace all the child processes [the default]
    --child               Trace only one child process
    --child=pid[,pid]*    Trace only child with process id in pid list
    --parent              Trace the parent controller process
    --eventd              Trace the zeus.eventd process
    --flipper             Trace the zeus.flipper process
    --admin               Trace the zeus.admin process
    --monitor             Trace the zeus.monitor process
    --sysd                Trace the zeus.sysd process
    --configd             Trace the zeus.configd process
    --follow              Follow new processes created by fork()
TEXT

   if( $usage == 1 ) {
      print $text;
      exit 0;
   } else {
      print STDERR $text;
      exit 1;
   }
}

# Find parent process
my @stat = stat( $pidfile );
if( ! -f $pidfile ) {
   die "Pidfile not found - are you sure the traffic manager is running?\n";
}
if(( $stat[4] != $< ) && $< ) {
   die "You do not have permissions to trace processes - try running as root\n";
}

open( PIDFILE, "<$pidfile" ) or die "Cannot read pidfile: $!\n";
my $pidline = <PIDFILE> || "";
my( $parentpid, $name ) = $pidline =~ /^(\d+)\s*(.*)/;
$name ||= "$ENV{ZEUSHOME}/zxtm/bin/zeus.zxtm";
close( PIDFILE );
die "Cannot read pidfile - are you sure the traffic manager is running?\n" unless( $parentpid );

kill( 0, $parentpid ) || die "Cannot signal pid $parentpid - are you sure the traffic manager is running?\n";

my @pids;
foreach my $prog ( @progs ) {
   if( $prog eq 'parent' ) {
      print "Tracing parent process $parentpid\n";
      push( @pids, $parentpid );
   } else {
      my $progname = $prog eq 'child' ? $name : $prog;

      my $cmd = "ps -ef";
      $cmd = "ps -axjwww" if( $os eq 'FreeBSD' || $os eq 'MacOSX' );
      $cmd = "ps -efwww" if( $os eq 'Linux' );
      my $procs = `$cmd`;
      foreach ( split( "\n", $procs )) {
         my( $procpid, $ppid ) = /\w+\s+(\d+)\s+(\d+)\s+.*?\s$progname/;
         next unless( $parentpid && $procpid );
         if( $parentpid == $ppid ) {
            if( 0 != scalar( keys( %childpids ) ) ) {
               if( $childpids{$procpid} ) {
                  push( @pids, $procpid );
               }
            } else {
               push( @pids, $procpid );
            }
         }
      }

      # Should not happen
      die "Cannot find the process to trace\n" unless( @pids );

      if( @pids > 1 ) {
         print "There are " . scalar( @pids ) . " $prog processes\n";
         if( $onechild ) {
            @pids = ( $pids[ int( rand( @pids )) ] )
         }
      }

      if( @pids > 1 ) {
         print "Tracing $prog processes: ", join( ', ', @pids ), "\n";
      } else {
         print "Tracing $prog process $pids[0]:\n";
      }
   }

   if( scalar @pids > 1 && ( $os eq 'FreeBSD' || $os eq 'MacOSX' ) ) {
      @pids = ( $pids[ int( rand( @pids )) ] );
      print "($os: can only trace one process: $pids[0])\n";
      last;
   }
}

if( @pids > 1 ) {
   if( $os eq 'Linux' ) {
      $cmd .= ' -p ' . join( ' -p ', @pids );
   } else {
      $cmd .= ' -p ' . join( ' ', @pids );
   }
} else {
   $cmd .= " -p $pids[0]";
}

# FreeBSD writes to an intermediate file and needs us to run kdump at the same time
if( $os eq 'FreeBSD' || $os eq 'MacOSX' ) {
   my $file_arg = ' -f ktrace.' . $pids[0];
   $cmd .= $file_arg . ' & sleep 1 ; kdump -l -T' . $file_arg;
   foreach( qw( INT TERM ABRT BUS )) {
      $SIG{$_} = sub { system( "ktrace -c -p $pids[0]" );
                       unlink( "ktrace.$pids[0]" ); };
   }
}

print "* command is: $cmd\n";

open( TRACE, "$cmd 2>&1 |" ) or die "Can't start tracing program: $!\n";
while( <TRACE> ) {
   print;
}
close( TRACE );

if( $os eq 'FreeBSD' || $os eq 'MacOSX' ) {
   unlink( "ktrace.$pids[0]" );
   system( "ktrace -c -p $pids[0]" );
}
