#!/bin/bash

# Copyright (c) 2010 - 2014, Hewlett-Packard Development Co., L.P. 

# Description: QueryExecutionProfiler

# This example script is governed by the same terms as other utilities
# in /opt/vertica/scripts. See ‘Additional Terms for Vertica Support
# Utilities’ in the Vertica Software License.

# Create Date: 5/3/11

################################################################
#### INITIALIZATION AND ARGUMENTS
################################################################

# This script gets the runtime execution engine profiling information for a query in real-time. It works by executing the query in the background, extracting the transaction id for the query, and then repeatedly dumping the profiling table's contents every interval seconds until the query is done. the outputs are dumped to a new file each time and then packaged into a single .tar.gz

dir="/tmp/runtime_profiling_directory"
txnid_file="txnid_file"
plans_file="plan_dump"
snapshot_ending="snapshots"

# Argument = -h -U username -w password -v -c -i interval -q query -p port

usage()
{
cat << EOF
usage: $0 options

This script takes profiling snapshots of the execution of a query at regular, user-defined intervals. The output is packed into a single file with the name query_profile_[date/time].tar.gz containing all relevant profiling data.

REQUIRED:
   -i      The period in seconds of sampling the execution engine profiling table. Use decimal values to represent fractions of a second.
   -q      The query to profile as a string enclosed in double quotes. The query statement should be prefaced with the keyword PROFILE. For example, "PROFILE SELECT answer FROM answer_table" or "PROFILE INSERT INTO answer_table VALUES(42)"

OPTIONS:
   -h      show this message
   -U      username
   -w      password
   -p      port
   -v      verbose
   -c      clean up tmp file, pack profiling snapshots into .tar.gz file, and terminate the executing query in the database. For use when the QueryExecutionProfiler was manually aborted due to a long-running or hung query.

EOF
}

USERNAME=
PASSWORD=
INTERVAL=
QUERY=
CLEANUP=
VERBOSE=
PORT=
while getopts “hU:w:vci:q:p:” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         U)
             USERNAME=$OPTARG
             ;;
         w)
             PASSWORD=$OPTARG
             ;;
         p)
             PORT=$OPTARG
             ;;
         i)
             INTERVAL=$OPTARG
             ;;
	 q)	     
             QUERY=$OPTARG
             ;;
         v)
             VERBOSE=1
             ;;
         c)
             CLEANUP=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done



if [[ -z $QUERY ]] || [[ -z $INTERVAL ]] 
then
     usage
     exit 1
fi

if ([[ -z $PASSWORD ]] && [[ -n $USERNAME ]]) || ([[ -n $PASSWORD ]] && [[ -z $USERNAME ]]) 
then 
     echo "Provide both username and password or neither."
     exit 1
fi

# set the $us and $pw for the username and password if they are set
us=""
pw=""
pt=""
if [[ -n $PASSWORD ]] && [[ -n $USERNAME ]]
then
   us="-U $USERNAME"
   pw="-w $PASSWORD"
fi

if [[ -n $PORT ]] 
then 
   pt="-p $PORT"
fi

myvsql="/opt/vertica/bin/vsql  -tA $pt $us $pw -c "
#myvsql="vsql  -tA $pt $us $pw -c "

################################################################
#### CLEAN UP AND EXIT 
################################################################


# if its a cleanup command, clean things up and exit
if [ -n "$CLEANUP" ]; then 
    # read out the txnid
    txnid=`grep -o 'transaction_id=[0-9]*' $dir/$txnid_file | grep -o '[0-9]*'`
    # if it doesn't exist, no need to continue
    if [ -z "$txnid" ]; then 
	if [ -n "$VERBOSE" ]; then
	    echo "No transaction id found when looking in $dir/$txnid_file. File may not exist or is malformed."
	fi
	exit
    fi

    # get the session name to close
    session_id="`$myvsql "select session_id from vs_sessions where transaction_id=$txnid";`"

    # if the session still exists, close it
    if [ -n "$session_id" ]; then 
       $myvsql " select close_session('$session_id')"  

       if [ -n "$VERBOSE" ]; then
	   echo "Closing session: $session_id";
       fi
    else
       if [ -n "$VERBOSE" ]; then
	   echo "No session id found. The session must have ended or been closed already."
       fi
    fi 

   # clean up txnid file
    rm $dir/$txnid_file
    rm $dir/$plans_file

   # archive profiling files
    DATE=`date +%Y%m%d%H%M%S`
    tar -czf ./query_profile_$DATE.tar.gz $dir/

   # clean the rest
   rm -rf $dir
   exit
fi


################################################################
#### CHECK INTERVAL AND QUERY
################################################################


# check arguments. if neither is defined, give usage instructions
if [ -z "$INTERVAL" ] || [ -z "$QUERY" ]; then
   usage
   exit
fi

# make sure first argument is a number
if ! [[ "$INTERVAL" =~ ^[0-9]*[.]?[0-9]+$ ]] ; then
   /bin/echo -e "$INTERVAL is not a valid interval value.\n"
   usage 
   exit
fi

# make sure second argument at least begins with PROFILE. We can't make sure it's a legit query though but we can at least make this simple check.
query_beginning=${QUERY:0:7}
if ! [[ `echo $query_beginning | tr [:lower:] [:upper:]` = "PROFILE" ]] ; then 
   /bin/echo -e "Query must being with the keyword PROFILE.\n"
   usage
   exit
fi

################################################################
#### BEGIN EXECUTION 
################################################################


# make sure the temp file is not there
rm -rf $dir
mkdir $dir
chmod 777 $dir
touch $dir/$txnid_file

# the query to run. send stderr to the temp file. throw away the stdout

$myvsql " $QUERY" 2>$dir/$txnid_file 1>/dev/null & 

# keep checking the temp file until we get the txnid
txnid=""
while [ -z "$txnid" ]; do  
   txnid=`grep -o 'transaction_id=[0-9]*' $dir/$txnid_file | perl -e '$i = <STDIN>; @arr = split("=",$i); print @arr[1]'`
   # also check if is an error. If so, dump error output and exit
   error_message=`grep -o 'ERROR' $dir/$txnid_file`
   if [ -n "$error_message" ]; then 
       echo `cat $dir/txnid_file`
       rm -rf $dir
       exit
   fi
   if [ -n "$VERBOSE" ]; then 
     echo "Waiting to get the transaction id";
   fi
done


# keep checking to see if the execution has started yet. 
is_executing=""

while [ -z "$is_executing" ];
do
   if [ -n "$VERBOSE" ]; then 
     echo "Checking to see if execution has begun";
   fi
   is_executing="`$myvsql "select is_executing from execution_engine_profiles where transaction_id=$txnid limit 1"`"; 
done

if [ "$is_executing" = "f" ] 
then
    echo "Sorry the query finished too quickly for this tool to profile its execution"
    exit
fi

# grab the plan 
$myvsql " select dump_ee_profiling_plans()" > $dir/$plans_file

# now create the plans file too
dirname="`dirname $0`"
python $dirname/profile_plans.py $txnid $dir $plans_file

counter=0;
while [ "$is_executing" ];
do
      $myvsql " select * from execution_engine_profiles where transaction_id = $txnid" > $dir/out_execution_engine_profiles_$counter
      # save the time of the snapshot
      time=`date +%s.%N`
      echo "$counter,$time" >> $dir/$txnid.$snapshot_ending
      if [ -n "$VERBOSE" ]; then 
         echo "Took profiling snapshot $counter at $time";
      fi
      sleep $INTERVAL

      # keep checking to see if the execution is over yet. keep logging profiling information until it is
      is_executing="`$myvsql " select is_executing from execution_engine_profiles where transaction_id=$txnid and is_executing='t' limit 1" | grep 't'`"; 
      counter=`expr $counter + 1`
done

# take a final snapshot at the end!
$myvsql " select * from execution_engine_profiles where transaction_id = $txnid" > $dir/out_execution_engine_profiles_$counter
# save the time of the snapshot
time=`date +%s.%N`
echo "$counter,$time" >> $dir/$txnid.$snapshot_ending

if [ -n "$VERBOSE" ]; then 
   echo "Took profiling snapshot $counter at $time (FINAL)";
fi

# clean up txnid file
rm $dir/$txnid_file
rm $dir/$plans_file

# archive profiling files
DATE=`date +%Y%m%d%H%M%S`
tar -czf ./query_profile_$DATE.tar.gz $dir/

# clean the rest
rm -rf $dir

