#!/bin/bash
##############################################################################
#    HPCC SYSTEMS software Copyright (C) 2023 HPCC Systems®.
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.
##############################################################################

usage()
{
    echo "Usage: doperf <pid> [time] [interval]"
    echo ""
    echo "doperf will capture stacks from <pid> at regular intervals, until [time] has elapsed"
    echo "or interrupted by signal, then generate a flame graph svg file from the captured stacks."
    echo ""
    echo "Requires the eu-stack utility (from elfutils), and perl."
    echo "May need to give eu-stack program ptrace permissions in order to work correctly"
    exit 1
}

if [[ $# -lt 1 ]] ; then
    usage
    exit 1
fi
 
exet=$(which eu-stack >/dev/null 2>&1)
rc=$?
if [[ $rc -ne 0 ]] ; then
    echo "Error, need eu-stack utility (elfutils pkg)"
    exit 1
fi
 
pid=$1
kill -0 $pid > /dev/null 2>&1
rc=$?
if [[ $rc -ne 0 ]] ; then
    echo "Error, pid ${pid} not found or not traceable"
    exit 1
fi
 
tx=60
if [[ $# -gt 1 ]] ; then
    tx=$2
fi

interval=0.2
if [[ $# -gt 2 ]] ; then
    interval=$3
fi

tx=`perl -l -e "print $tx / $interval"`

tmpdir=$(mktemp -d) 
cnt=1

#Add lines to suppress list to suppress any stack that includes a function matching the regex
cat <<EOF >${tmpdir}/suppress
_ZN6Waiter4waitEv - [^ ]*libccd.so
_ZN15CRoxieFileCache.*;_ZN22InterruptableSemaphore4waitEv
_ZN10PerfTracer
CRoxieWorker10threadmainEv - [^ ]*libccd.so;_ZN10RoxieQueue4waitEv
libjvm.so;
EOF

finish_perf()
{
  wait 2>/dev/null
  stackcollapse-elfutils.pl ${tmpdir}/stack.* > ${tmpdir}/folded
  grep -f ${tmpdir}/suppress -v ${tmpdir}/folded > ${tmpdir}/suppressed
  flamegraph.pl ${tmpdir}/suppressed
  rm -rf $tmpdir
  exit 0
}

trap finish_perf SIGINT SIGQUIT SIGTERM

while true
do
    kill -0 $pid > /dev/null 2>&1
    rc=$?
    if [[ $rc -ne 0 ]] ; then
        break
    fi
    if [[ ${cnt} -gt ${tx} ]] ; then
        break
    fi
    eu-stack -n 25 -r -m -p ${pid} > ${tmpdir}/stack.${cnt} 2>/dev/null &
    cnt=$((cnt+1))
    sleep $interval
    nj=$(jobs -p 2>/dev/null | wc -l)
    if [[ ${nj} -gt 5 ]] ; then
        wait -n 2>/dev/null
    fi
done

finish_perf