Skip to content

Instantly share code, notes, and snippets.

@cinsk
Created January 25, 2018 00:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cinsk/80ba34881188a114a8c329ef86bf077c to your computer and use it in GitHub Desktop.
Save cinsk/80ba34881188a114a8c329ef86bf077c to your computer and use it in GitHub Desktop.
Generate flame graphs of JVM, JAVA
#!/bin/bash
# SJK tool need to run as the same user of the target process.
USER=
PID=
INTERVAL=10ms
PROGRAM_NAME=$(basename $0)
error() {
local exitcode="$1"
shift
echo "$PROGRAM_NAME: $*" 1>&2
[ "$exitcode" -ne 0 ] && exit "$exitcode"
}
while getopts "u:p:i:h" opt; do
case "$opt" in
u)
USER=$OPTARG
;;
p)
PID=$OPTARG
;;
i)
INTERVAL=$OPTARG
;;
h)
cat <<EOF
Usage: $PROGRAM_NAME [OPTION...]
-u USER user id of the target Java process
-p PID pid of the target Java process
EOF
esac
done
shift $((OPTIND - 1))
[ -z "$PID" ] && error 1 "missing PID, use -p PID"
[ -z "$USER" ] && error 1 "missing USER, use -u USER"
SJK_JAR=sjk-0.10-SNAPSHOT.jar
SJK="/tmp/$SJK_JAR"
SJK_SOURCE="https://github.com/cinsk/jvm-tools/blob/master/release/${SJK_JAR}?raw=true"
echo "Retrieving $SJK_SOURCE"
curl -s -o "$SJK" -L -k "$SJK_SOURCE"
# if [ -z "$PID" ]; then
# if [ "$(pgrep -u cassandra java | wc -l)" -ne 1 ]; then
# echo "more than one Java process owned by the user cassandra" 1>&2
# exit 1
# fi
# PID="$(pgrep -u cassandra java)"
# fi
SJK_DUMP=/tmp/flamegraph-sjk-dump.$$.std
FLAME_OUTPUT=/tmp/flame-${PID}-$(hostname).svg
[ -f "$SJK_DUMP" ] && rm -f "$SJK_DUMP"
trap "rm -f $SJK_DUMP" EXIT
sudo -u "$USER" java -jar "$SJK" stcap -p $PID -i "$INTERVAL" -o "$SJK_DUMP" "$@"
java -jar "$SJK" ssa --flame -f "$SJK_DUMP" > "$FLAME_OUTPUT"
echo "flamegraph: $FLAME_OUTPUT"
rm -f "$SJK_DUMP"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment