Created
September 5, 2016 06:19
-
-
Save andy722/97854bb96f9d90a3576b49cb34937518 to your computer and use it in GitHub Desktop.
Dumps JVM application stack in case CPU load exceeds allowed threshold
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Dumps JVM application stack in case CPU load exceeds allowed threshold. | |
# | |
# This script is supposed to be called regularly, e.g. cron entry: | |
# | |
# */5 * * * * /opt/apps/stack-dumps/auto-dump.sh | |
# | |
# Where to put stack dumps. | |
export TARGET_DIR="/opt/apps/stack-dumps" | |
export JSTACK_BIN="/usr/java/jdk1.7.0_79/bin/jstack" | |
# Target JVM PID-file. | |
export PID_FILE="/opt/apps/site/site.pid" | |
# Stack will be dumped only if the following maximal allowed CPU load is exceeded. | |
export CPU_THRESHOLD="90" | |
function die() { | |
echo "ERROR: $@" 1>&2 | |
exit 1 | |
} | |
function getCpuLoad() { | |
local load=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%*id.*/\1/" | awk '{print 100 - $1}') | |
local __rc=$1 | |
if [[ "$__rc" ]]; then | |
eval ${__rc}="'$load'" | |
else | |
echo "$load" | |
fi | |
} | |
function dumpStack() { | |
local PID=$(cat ${PID_FILE}) | |
local TIME=$(date +%Y%m%d-%H%M%S-%N) | |
local FILE_NAME="${TARGET_DIR}/stack-${PID}-${TIME}.dump" | |
echo "Dumping PID=${PID} -> ${FILE_NAME}" | |
${JSTACK_BIN} ${PID} >${FILE_NAME} 2>&1 | |
} | |
function main() { | |
local LOAD="$(getCpuLoad)" | |
echo "CPU load: ${LOAD}" | |
if [ ${LOAD} -ge ${CPU_THRESHOLD} ]; then | |
dumpStack | |
fi | |
} | |
[ -f ${PID_FILE} ] || die "${PID_FILE} missing" | |
[ -d ${TARGET_DIR} ] || die "${TARGET_DIR} missing" | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment