Bash script for taking java thread dump triggered by CPU load

 

#!/bin/bash

## Title: Bash script for taking java thread dump triggered by CPU load an get notified by email using sendmail.

##Alternative solution to take  java dumps it`s  with jstack -l

## Older dumps will be erase in function of how many days you set it on the “RETENTION_DAYS” variable.

# #!!!Execute this as the user that’s running the java process!!!

##!!! If CPU load will stay over “TRIGGER” a while  the script will run again only after one hour(you can set whatever resting time you want)!!!.

## Author: BoierMoflea

# #Email: [email protected]

##CONFIGURATION##
LOG_DIRECTORY=”/var/log/javadumps”
RETENTION_DAYS=”3″
DUMP_MODE=’644′
PROCESS=”java”
TRIGGER=4.00
COUNTER=0

##COMMANDS##
JCMD=”/your jdk install dir path/jcmd”
LS=”/bin/ls”
AWK=”/bin/awk”
GREP=”/bin/grep”
CHMOD=”/bin/chmod”
MKDIR=”/bin/mkdir”
ECHO=”/bin/echo”
DATE=”/bin/date”
PS=”/bin/ps”
FIND=’/bin/find’
CAT=’/bin/cat’
MAIL=’/usr/sbin/sendmail’

##TAKING NECCESARY INFORMATION ##

LOAD=`cat /proc/loadavg | awk ‘{print $1}’`
RESPONSE=`echo | awk -v T=$TRIGGER -v L=$LOAD ‘BEGIN{if ( L > T){ print “greater”}}’`
LASTDUMP=$(find $LOG_DIRECTORY -type f -mmin -60 |wc -l |awk ‘{print}’)
NODUMP=`echo | awk -v C=$COUNTER -v L=$LASTDUMP ‘BEGIN{if ( L == C){ print “proceed”}}’`

PID=`$PS auxww | $GREP “$PROCESS” | $GREP -v $GREP |$AWK ‘{print $2}’`

##VARIABLES##
CURRENT_DATE=`$DATE +’%m-%d-%y_%T’`
MONTH_DAY_YEAR=`$ECHO $CURRENT_DATE | $AWK -F ‘_’ ‘{print $1}’`

#check if LOG_DIRECTORY exists
if [ ! -d “$LOG_DIRECTORY” ]; then
$ECHO “Create ${LOG_DIRECTORY} and set the permissions so the user executing the dump can write to this directory”
$ECHO “Failed to take a dump :)”
exit 1
fi

#create sub directory for this day’s dumps
if [ ! -d “${LOG_DIRECTORY}/${MONTH_DAY_YEAR}” ]; then
$MKDIR ${LOG_DIRECTORY}/${MONTH_DAY_YEAR}
$CHMOD 755 ${LOG_DIRECTORY}/${MONTH_DAY_YEAR}
fi

if [ -z “$PID” ]; then
$ECHO “Failed to find any java process with ‘${PROCESS}’ in its name”
$ECHO “Failed to take a dump :)”
exit 1
fi

if [[ $RESPONSE = “greater” && $NODUMP = “proceed” ]]; then

$JCMD $PID Thread.print > ${LOG_DIRECTORY}/${MONTH_DAY_YEAR}/thread_dump_${CURRENT_DATE}
$CHMOD $DUMP_MODE ${LOG_DIRECTORY}/${MONTH_DAY_YEAR}/thread_dump_${CURRENT_DATE}
( $ECHO “Subject: Thread dump was created for java PID=$PID (CPU-LOAD)=$LOAD, TIME=$CURRENT_DATE”; $CAT ${LOG_DIRECTORY}/${MONTH_DAY_YEAR}/thread_dump_${CURRENT_DATE} ) | $MAIL [email protected]
exit 1
fi
#Clean up older dumps
$FIND $LOG_DIRECTORY -type d -ctime +${RETENTION_DAYS} -exec rm -rf {} \;

 

Click to rate this post!
[Total: 2 Average: 5]