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

BEGIN { unshift( @INC, "$ENV{ZEUSHOME}/zxtmadmin/lib/perl" ); }
use POSIX qw( strftime );

use strict;

$| = 1;

# The program to use depends on the OS
my $os = `uname`;
chomp( $os );
my $hostname = `hostname`;
chomp( $hostname );
my( $strace, $times, $verbose, $follow );

# Date/Time constants
my @time_data = localtime( time() );
my( $sec,$min,$hour,$mday,$month,$year,$wday,$yday,$isdst ) = @time_data;

if( $os eq 'Linux' ) {
   $strace   = 'strace';
   $times    = '-ttT';
   $verbose  = '-s 2048';
   $follow   = '-f';
} elsif( $os eq 'SunOS' ) {
   $strace   = 'truss';
   $times    = '-d';
   $verbose  = '-a -e -vall -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 $configd = 0;
my $opt_outfile = "";
my $arg_outfile = "";
my $arg_outfile_count = 0;
my @progs = (); # Defaults to the child processes
my $onechild = 0;
my %childpids = ();
my $parent_pidfile = "$ENV{ZEUSHOME}/zxtm/internal/pid";
my $configd_pidfile = "$ENV{ZEUSHOME}/zxtm/internal-configd/pid";
my( $parent_pid, $parent_procname, $configd_pid, $configd_procname );

# Find parent process ID
if( ! -f $parent_pidfile ) {
   die "Pidfile not found - are you sure the traffic manager is running?\n";
}
my @stat = stat( $parent_pidfile );
if(( $stat[4] != $< ) && $< ) {
   die "You do not have permissions to trace processes - try running as root\n";
}
if( open( my $pid_fh, "<", $parent_pidfile ) ) {
   my $pidline = <$pid_fh> || "";
   close( $pid_fh );
   ( $parent_pid, $parent_procname ) = $pidline =~ /^(\d+)\s*(.*)/;
   $parent_procname ||= "$ENV{ZEUSHOME}/zxtm/bin/zeus.zxtm";
   if( !$parent_pid ) {
      die "Cannot read parent pidfile - are you sure the traffic manager is running?\n";
   }

   kill( 0, $parent_pid ) || die "Cannot signal parent pid $parent_pid - are you sure the traffic manager is running?\n";
} else {
   die "Cannot read parent pidfile: $!\n";
}

# Process args
foreach my $arg ( @ARGV ) {
   if( $options ) {
      $options = 0;
      if( $arg =~ /-o (\S+)/ ) {
         $opt_outfile = $1;
      }
      $cmd .= ' ' . $arg;
   } elsif( $arg eq '--verbose' ) {
      $cmd .= ' ' . $verbose;
   } elsif( $arg =~ /--file(=(\S+))?/ ) {
      $arg_outfile_count++;
      if( !defined( $2 ) ) {
         $arg_outfile = '<default>' if( !$arg_outfile );
      } else {
         $arg_outfile = $2;
      }
   } 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 '--aptimizer' ) {
      push @progs, 'zeus.aptimizer';
   } elsif( $arg eq '--autoscaler' ) {
      push @progs, 'zeus.autoscaler';
   } elsif( $arg eq '--eventd' ) {
      push @progs, 'zeus.eventd';
   } elsif( $arg eq '--flipper' ) {
      push @progs, 'zeus.flipper';
   } elsif( $arg eq '--ssld' ) {
      push @progs, 'zeus.ssld';
   } elsif( $arg eq '--sysd' ) {
      push @progs, 'zeus.sysd';
   } elsif( $arg eq '--admin' ) {
      push @progs, 'zeus.admin';
   } elsif( $arg eq '--configd' ) {
      push @progs, "zeus.configd";
      $configd = 1;
   } elsif( $arg eq '--monitor' ) {
      push @progs, 'zeus.monitor';
   } elsif( $arg eq '--help' ) {
      $usage = 1;
      last;
   } else {
      warn "Unknown parameter '$arg'\n";
      $usage = 2;
      last;
   }
}

# Handle options to print output to a file
if( $opt_outfile ) {
   if( $arg_outfile &&
     ( $arg_outfile ne '<default>' ) &&
     ( $arg_outfile ne $opt_outfile ) ) {
      print( "Error: Conflicting arguments detected: Multiple output files " .
           "specified '$arg_outfile', '$opt_outfile'\n" );
      exit( 1 );
   } elsif( $arg_outfile eq '<default>' ) {
      print "Warning: Multiple output file options detected, saved " .
            "file will be: $opt_outfile\n";
   }
} elsif( $arg_outfile ) {
   if( $arg_outfile eq '<default>' ) {
      # No filename specified, generate default
      my $date = sprintf( "%04d%02d%02d_%02d%02d",
                          $year + 1900, $month + 1, $mday, $hour, $min );
      my $default_filename = "$ENV{ZEUSHOME}/zxtm/log/trace_${hostname}_${date}";
      my $duplicate = "";
      my $num = 1;
      while ( -e "${default_filename}${duplicate}.txt" ) {
         $duplicate = "_$num";
         $num++;
      }
      $default_filename = $default_filename . $duplicate . ".txt";
      $cmd .= " -o $default_filename";
   } else {
      if( $arg_outfile_count > 1 ) {
         print "Warning: Multiple output file options detected, saved " .
               "file will be: $arg_outfile\n";
      }
      $cmd .= " -o $arg_outfile";
   }
}

@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
    --file[=filename]     Save the trace to a file instead of printing to the
                          console, with optional custom filename

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
    --admin               Trace the zeus.admin process
    --aptimizer           Trace the zeus.aptimizer process
    --autoscaler          Trace the zeus.autoscaler process
    --configd             Trace the zeus.configd process
    --eventd              Trace the zeus.eventd process
    --flipper             Trace the zeus.flipper process
    --monitor             Trace the zeus.monitor process
    --ssld                Trace the zeus.ssld process
    --sysd                Trace the zeus.sysd process
    --follow              Follow new processes created by fork()
TEXT

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

# Find configd process ID if required
if( $configd ) {
   if( ! -f $configd_pidfile ) {
      die "Pidfile not found - are you sure the traffic manager is running?\n";
   }
   my @stat = stat( $configd_pidfile );
   if(( $stat[4] != $< ) && $< ) {
      die "You do not have permissions to trace processes - try running as root\n";
   }
   if( open( my $pid_fh, "<", $configd_pidfile ) ) {
      my $pidline = <$pid_fh> || "";
      close( $pid_fh );
      ( $configd_pid, $configd_procname ) = $pidline =~ /^(\d+)\s*(.*)/;
      $configd_procname ||= "zeus.configd";
      if( !$configd_pid ) {
         die "Cannot read pidfile - are you sure the traffic manager is running?\n";
      }

      kill( 0, $configd_pid ) || die "Cannot signal configd pid $configd_pid - are you sure the traffic manager is running?\n";
   } else {
      die "Cannot read configd pidfile: $!\n";
   }
}

# Current processes
my $ps_cmd = ( $os eq 'Linux' ) ? "ps -efwww" : "ps -ef";
my $procs = `$ps_cmd`;

my $datetime = POSIX::strftime( "%d/%b/%Y:%H:%M:%S %z", @time_data );
print "Trace on $hostname at $datetime\n";

my %pid_hash;
foreach my $prog ( @progs ) {
   my @pid_array = ();
   if( $prog eq 'parent' ) {
      print "Tracing $prog process: $parent_pid\n";
      push( @pid_array, $parent_pid );
   } elsif( $prog eq "zeus.configd" ) {
      print "Tracing $prog process: $configd_pid\n";
      push( @pid_array, $configd_pid );
   } else {
      my $progname = $prog eq 'child' ? $parent_procname : $prog;
      foreach my $line ( split( "\n", $procs ) ) {
         my( $procpid, $ppid ) = $line =~ /\S+\s+(\d+)\s+(\d+)\s+.*?\s.*$progname/;
         if( $prog eq "zeus.admin" && $procpid ) {
            # zeus.admin is a standalone process like zeus.configd so $ppid
            # won't be the parent
            push( @pid_array, $procpid );
            next;
         }
         next unless( $parent_pid && $procpid );
         if( $parent_pid == $ppid ) {
            if( 0 != scalar( keys( %childpids ) ) ) {
               if( $childpids{$procpid} ) {
                  push( @pid_array, $procpid );
               }
            } else {
               push( @pid_array, $procpid );
            }
         }
      }

      my $size = scalar( @pid_array );
      if( !$size ) {
         # Should not happen
         print "Cannot find a $prog process to trace\n";
         next;
      } elsif( $size > 1 ) {
         print "There are $size $prog processes\n";
         if( $onechild ) {
            @pid_array = ( $pid_array[ int( rand( $size ) ) ] )
         }
      }

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

my @pids;
foreach my $prog ( keys( %pid_hash ) ) {
   push( @pids, @{$pid_hash{$prog}} );
}

if( !scalar( @pids ) ) {
   die "Cannot find any processes to trace";
}

if( $os eq 'Linux' ) {
   $cmd .= ' -p ' . join( ' -p ', @pids );
} else {
   $cmd .= ' -p ' . join( ' ', @pids );
}

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

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