注意点:docker容器里面依赖的需要是JDK而不是JRE,JRE没有jstack工具
#!/bin/bash
if [ $# -le 0 ]; then
echo "usage: $0 <pid> [line-number]"
exit 1
fi
# java home
if test -z $JAVA_HOME
then
JAVA_HOME='/usr/bin'
fi
# pid
pid=$1
echo "input pid is $pid, then use docker java pid"
# line number
linenum=$2
if test -z $linenum
then
linenum=15
fi
# docker java pid
pid=$(top -bn1 | grep java | awk '{print $1}')
echo "docker java pid is $pid"
# checking pid
if test -z "$($JAVA_HOME/bin/jps -l | cut -d '' -f 1 | grep $pid)"
then
echo "process of $pid is not exists"
fi
# file position
threadsfile=$PWD/threads$pid.dump
echo "threadsfile position is $threadsfile"
stackfile=$PWD/stack$pid.dump
echo "stackfile position is $stackfile"
threadstackfile=$PWD/threadstackfile$pid.dump
echo "threadstackfile position is $threadstackfile"
# generate java stack
$JAVA_HOME/bin/jstack -l $pid >> $stackfile
# generate process's thread file
ps -mp $pid -o THREAD,tid,time | sort -k2r | awk '{if ($1 !="USER" && $2 != "0.0" && $8 !="-") print $8;}' | xargs printf "%x\n" >> $threadsfile
# generate thread stack file
tids="$(cat $threadsfile)"
for tid in $tids
do
echo "------------------------------ ThreadId ($tid) ------------------------------"
cat $stackfile | grep 0x$tid -A $linenum
echo "------------------------------ ThreadId ($tid) ------------------------------" >> $threadstackfile
cat $stackfile | grep 0x$tid -A $linenum >> $threadstackfile
done
# rm -f $stackfile $threadsfile