Skip to content

Instantly share code, notes, and snippets.

@sammso
Last active January 18, 2018 22:06
Show Gist options
  • Save sammso/c29a17dbbfa6fff3ea90920708843193 to your computer and use it in GitHub Desktop.
Save sammso/c29a17dbbfa6fff3ea90920708843193 to your computer and use it in GitHub Desktop.
jstackseries.sh

Script collect threaddumps from the Java process

Usage: "Usage: jstackSeries <process identfier> [ <count> [ <delay> [ <sample count> [ <file prefix> [ <folder> ] ] ] ] ]

Where:

  • process identfier is prosess id or if it is not a number then script is trying to find pid by ps -ef|grep java| grep <process identifier>
  • count how many times we take samples, use -1 if no limit.
  • delay wait between samples
  • sample count how many threadump samples we take on row
  • file prefix what is the file prefix, this can be example server name
  • folder where to write thread dump files
 #!/bin/bash
 if [ $# -eq 0 ]; then
     echo >&2 "Usage: jstackseries.sh <process identfier> [ <count> [ <delay> [ <sample count> [ <file prefix> [ <folder> ] ] ] ] ]"
     echo >&2 "    Defaults: count = 10 (-1 eternal), delay = 0.5 (seconds), series count = 1, file prefix=jstack, folder="
     exit 1
 fi
 
 pid=$1          # can be a pid, if is not then grep java|grep <process identifier> is used to find correct pid
 count=${2:-10}  # defaults to 10 times
 delay=${3:-0.5} # defaults to 0.5 seconds
 samplecount=${4:-1}
 fileprefix=${5:-"jstack"}
 folder=${6:-"log"}

 if [ ! -d "$folder" ]; then
    mkdir $folder
 fi
 

 counter=1
 eternal=0
 
 if [ $count -lt 0 ]; then
     let eternal=1
 fi
 
 while [[ $count -gt 0 || $eternal -eq 1 ]]; do
     scount=$samplecount
     
     while [ $scount -gt 0 ]; do
       
       datefolder=$(date +%F)T.$(date +%H)
     
       if [ ! -d "$folder/$datefolder" ]; then
         mkdir $folder/$datefolder
       fi
 
       printf -v counterstr "%06d" $counter
       
       pid2=$pid
 
       if ! [[ $pid =~ '^[0-9]+$' ]] ; then 
           pid2=$(ps -ef | grep $pid | grep java | awk '{print $2}')
       fi
 
       jstack -l $pid2 > $folder/$datefolder/$fileprefix.$pid2.$counterstr.$(date +%H%M%S).log
#      All the threaddumps to same file below      
#      jstack -l $pid2 >> $folder/$datefolder/$fileprefix.$pid2.log       
       let scount--
       let counter++
       echo -n "."
     done 
     if [ $eternal -eq 0 ]; then
       let count--
     fi
     if [ $count -gt 0 ] || [ $eternal -eq 1 ]; then
       sleep $delay
     fi
 done
echo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment