1. #!/bin/bash
    2. # @Function
    3. # Find out the highest cpu consumed threads of java processes, and print the stack of these threads.
    4. #
    5. # @Usage
    6. # $ ./show-busy-java-threads
    7. #
    8. # @online-doc https://github.com/oldratlee/useful-scripts/blob/master/docs/java.md#-show-busy-java-threads
    9. # @author Jerry Lee (oldratlee at gmail dot com)
    10. # @author superhj1987 (superhj1987 at 126 dot com)
    11. readonly PROG="`basename $0`"
    12. readonly -a COMMAND_LINE=("$0" "$@")
    13. # Get current user name via whoami command
    14. # See https://www.lifewire.com/current-linux-user-whoami-command-3867579
    15. # Because if run command by `sudo -u`, env var $USER is not rewritten/correct, just inherited from outside!
    16. readonly USER="`whoami`"
    17. ################################################################################
    18. # util functions
    19. ################################################################################
    20. # NOTE: $'foo' is the escape sequence syntax of bash
    21. readonly ec=$'\033' # escape char
    22. readonly eend=$'\033[0m' # escape end
    23. colorEcho() {
    24. local color=$1
    25. shift
    26. # if stdout is console, turn on color output.
    27. [ -t 1 ] && echo "$ec[1;${color}m$@$eend" || echo "$@"
    28. }
    29. colorPrint() {
    30. local color=$1
    31. shift
    32. colorEcho "$color" "$@"
    33. [ -n "$append_file" -a -w "$append_file" ] && echo "$@" >> "$append_file"
    34. [ -n "$store_dir" -a -w "$store_dir" ] && echo "$@" >> "${store_file_prefix}$PROG"
    35. }
    36. normalPrint() {
    37. echo "$@"
    38. [ -n "$append_file" -a -w "$append_file" ] && echo "$@" >> "$append_file"
    39. [ -n "$store_dir" -a -w "$store_dir" ] && echo "$@" >> "${store_file_prefix}$PROG"
    40. }
    41. redPrint() {
    42. colorPrint 31 "$@"
    43. }
    44. greenPrint() {
    45. colorPrint 32 "$@"
    46. }
    47. yellowPrint() {
    48. colorPrint 33 "$@"
    49. }
    50. bluePrint() {
    51. colorPrint 36 "$@"
    52. }
    53. die() {
    54. redPrint "Error: $@" 1>&2
    55. exit 1
    56. }
    57. logAndRun() {
    58. echo "$@"
    59. echo
    60. "$@"
    61. }
    62. logAndCat() {
    63. echo "$@"
    64. echo
    65. cat
    66. }
    67. usage() {
    68. local -r exit_code="$1"
    69. shift
    70. [ -n "$exit_code" -a "$exit_code" != 0 ] && local -r out=/dev/stderr || local -r out=/dev/stdout
    71. (( $# > 0 )) && { echo "$@"; echo; } > $out
    72. > $out cat <<EOF
    73. Usage: ${PROG} [OPTION]... [delay [count]]
    74. Find out the highest cpu consumed threads of java processes,
    75. and print the stack of these threads.
    76. Example:
    77. ${PROG} # show busy java threads info
    78. ${PROG} 1 # update every 1 second, (stop by eg: CTRL+C)
    79. ${PROG} 3 10 # update every 3 seconds, update 10 times
    80. Output control:
    81. -p, --pid <java pid> find out the highest cpu consumed threads from
    82. the specified java process.
    83. default from all java process.
    84. -c, --count <num> set the thread count to show, default is 5.
    85. -a, --append-file <file> specifies the file to append output as log.
    86. -S, --store-dir <dir> specifies the directory for storing
    87. the intermediate files, and keep files.
    88. default store intermediate files at tmp dir,
    89. and auto remove after run. use this option to keep
    90. files so as to review jstack/top/ps output later.
    91. delay the delay between updates in seconds.
    92. count the number of updates.
    93. delay/count arguments imitates the style of
    94. vmstat command.
    95. jstack control:
    96. -s, --jstack-path <path> specifies the path of jstack command.
    97. -F, --force set jstack to force a thread dump. use when jstack
    98. does not respond (process is hung).
    99. -m, --mix-native-frames set jstack to print both java and native frames
    100. (mixed mode).
    101. -l, --lock-info set jstack with long listing.
    102. prints additional information about locks.
    103. CPU usage calculation control:
    104. -d, --top-delay specifies the delay between top samples.
    105. default is 0.5 (second). get thread cpu percentage
    106. during this delay interval.
    107. more info see top -d option. eg: -d 1 (1 second).
    108. -P, --use-ps use ps command to find busy thread(cpu usage)
    109. instead of top command.
    110. default use top command, because cpu usage of
    111. ps command is expressed as the percentage of
    112. time spent running during the *entire lifetime*
    113. of a process, this is not ideal in general.
    114. Miscellaneous:
    115. -h, --help display this help and exit.
    116. EOF
    117. exit $exit_code
    118. }
    119. ################################################################################
    120. # Check os support
    121. ################################################################################
    122. uname | grep '^Linux' -q || die "$PROG only support Linux, not support `uname` yet!"
    123. ################################################################################
    124. # parse options
    125. ################################################################################
    126. # NOTE: ARGS can not be declared as readonly!!
    127. # readonly declaration make exit code of assignment to be always 0, aka. the exit code of `getopt` in subshell is discarded.
    128. # tested on bash 4.2.46
    129. ARGS=`getopt -n "$PROG" -a -o p:c:a:s:S:Pd:Fmlh -l count:,pid:,append-file:,jstack-path:,store-dir:,use-ps,top-delay:,force,mix-native-frames,lock-info,help -- "$@"`
    130. [ $? -ne 0 ] && { echo; usage 1; }
    131. eval set -- "${ARGS}"
    132. while true; do
    133. case "$1" in
    134. -c|--count)
    135. count="$2"
    136. shift 2
    137. ;;
    138. -p|--pid)
    139. pid="$2"
    140. shift 2
    141. ;;
    142. -a|--append-file)
    143. append_file="$2"
    144. shift 2
    145. ;;
    146. -s|--jstack-path)
    147. jstack_path="$2"
    148. shift 2
    149. ;;
    150. -S|--store-dir)
    151. store_dir="$2"
    152. shift 2
    153. ;;
    154. -P|--use-ps)
    155. use_ps=true
    156. shift
    157. ;;
    158. -d|--top-delay)
    159. top_delay="$2"
    160. shift 2
    161. ;;
    162. -F|--force)
    163. force=-F
    164. shift
    165. ;;
    166. -m|--mix-native-frames)
    167. mix_native_frames=-m
    168. shift
    169. ;;
    170. -l|--lock-info)
    171. more_lock_info=-l
    172. shift
    173. ;;
    174. -h|--help)
    175. usage
    176. ;;
    177. --)
    178. shift
    179. break
    180. ;;
    181. esac
    182. done
    183. count=${count:-5}
    184. update_delay=${1:-0}
    185. [ -z "$1" ] && update_count=1 || update_count=${2:-0}
    186. (( update_count < 0 )) && update_count=0
    187. top_delay=${top_delay:-0.5}
    188. use_ps=${use_ps:-false}
    189. # check the directory of append-file(-a) mode, create if not exsit.
    190. if [ -n "$append_file" ]; then
    191. if [ -e "$append_file" ]; then
    192. [ -f "$append_file" ] || die "$append_file(specified by option -a, for storing run output files) exists but is not a file!"
    193. [ -w "$append_file" ] || die "file $append_file(specified by option -a, for storing run output files) exists but is not writable!"
    194. else
    195. append_file_dir="$(dirname "$append_file")"
    196. if [ -e "$append_file_dir" ]; then
    197. [ -d "$append_file_dir" ] || die "directory $append_file_dir(specified by option -a, for storing run output files) exists but is not a directory!"
    198. [ -w "$append_file_dir" ] || die "directory $append_file_dir(specified by option -a, for storing run output files) exists but is not writable!"
    199. else
    200. mkdir -p "$append_file_dir" || die "fail to create directory $append_file_dir(specified by option -a, for storing run output files)!"
    201. fi
    202. fi
    203. fi
    204. # check store directory(-S) mode, create directory if not exsit.
    205. if [ -n "$store_dir" ]; then
    206. if [ -e "$store_dir" ]; then
    207. [ -d "$store_dir" ] || die "$store_dir(specified by option -S, for storing output files) exists but is not a directory!"
    208. [ -w "$store_dir" ] || die "directory $store_dir(specified by option -S, for storing output files) exists but is not writable!"
    209. else
    210. mkdir -p "$store_dir" || die "fail to create directory $store_dir(specified by option -S, for storing output files)!"
    211. fi
    212. fi
    213. ################################################################################
    214. # check the existence of jstack command
    215. ################################################################################
    216. if [ -n "$jstack_path" ]; then
    217. [ -f "$jstack_path" ] || die "$jstack_path is NOT found!"
    218. [ -x "$jstack_path" ] || die "$jstack_path is NOT executalbe!"
    219. elif which jstack &> /dev/null; then
    220. jstack_path="`which jstack`"
    221. else
    222. [ -n "$JAVA_HOME" ] || die "jstack not found on PATH and No JAVA_HOME setting! Use -s option set jstack path manually."
    223. [ -f "$JAVA_HOME/bin/jstack" ] || die "jstack not found on PATH and \$JAVA_HOME/bin/jstack($JAVA_HOME/bin/jstack) file does NOT exists! Use -s option set jstack path manually."
    224. [ -x "$JAVA_HOME/bin/jstack" ] || die "jstack not found on PATH and \$JAVA_HOME/bin/jstack($JAVA_HOME/bin/jstack) is NOT executalbe! Use -s option set jstack path manually."
    225. jstack_path="$JAVA_HOME/bin/jstack"
    226. fi
    227. ################################################################################
    228. # biz logic
    229. ################################################################################
    230. readonly run_timestamp="`date "+%Y-%m-%d_%H:%M:%S.%N"`"
    231. readonly uuid="${PROG}_${run_timestamp}_${RANDOM}_$$"
    232. readonly tmp_store_dir="/tmp/${uuid}"
    233. if [ -n "$store_dir" ]; then
    234. readonly store_file_prefix="$store_dir/${run_timestamp}_"
    235. else
    236. readonly store_file_prefix="$tmp_store_dir/${run_timestamp}_"
    237. fi
    238. mkdir -p "$tmp_store_dir"
    239. cleanupWhenExit() {
    240. rm -rf "$tmp_store_dir" &> /dev/null
    241. }
    242. trap "cleanupWhenExit" EXIT
    243. headInfo() {
    244. colorEcho "0;34;42" ================================================================================
    245. echo "$(date "+%Y-%m-%d %H:%M:%S.%N") [$(( i + 1 ))/$update_count]: ${COMMAND_LINE[@]}"
    246. colorEcho "0;34;42" ================================================================================
    247. echo
    248. }
    249. if [ -n "${pid}" ]; then
    250. readonly ps_process_select_options="-p $pid"
    251. else
    252. readonly ps_process_select_options="-C java -C jsvc"
    253. fi
    254. # output field: pid, thread id(lwp), pcpu, user
    255. # order by pcpu(percentage of cpu usage)
    256. findBusyJavaThreadsByPs() {
    257. # 1. sort by %cpu by ps option `--sort -pcpu`
    258. # 2. use wide output(unlimited width) by ps option `-ww`
    259. # avoid trunk user column to username_fo+ or $uid alike
    260. local -a ps_cmd_line=(ps $ps_process_select_options -wwLo pid,lwp,pcpu,user --sort -pcpu --no-headers)
    261. local -r ps_out="$("${ps_cmd_line[@]}")"
    262. if [ -n "$store_dir" ]; then
    263. echo "$ps_out" | logAndCat "${ps_cmd_line[@]}" > "${store_file_prefix}$(( i + 1 ))_ps"
    264. fi
    265. echo "$ps_out" | head -n "${count}"
    266. }
    267. # top with output field: thread id, %cpu
    268. __top_threadId_cpu() {
    269. # 1. sort by %cpu by top option `-o %CPU`
    270. # unfortunately, top version 3.2 does not support -o option(supports from top version 3.3+),
    271. # use
    272. # HOME="$tmp_store_dir" top -H -b -n 1
    273. # combined
    274. # sort
    275. # instead of
    276. # HOME="$tmp_store_dir" top -H -b -n 1 -o '%CPU'
    277. # 2. change HOME env var when run top,
    278. # so as to prevent top command output format being change by .toprc user config file unexpectedly
    279. # 3. use option `-d 0.5`(update interval 0.5 second) and `-n 2`(update 2 times),
    280. # and use second time update data to get cpu percentage of thread in 0.5 second interval
    281. # 4. top v3.3, there is 1 black line between 2 update;
    282. # but top v3.2, there is 2 blank lines between 2 update!
    283. local -a top_cmd_line=(top -H -b -d $top_delay -n 2)
    284. local -r top_out=$(HOME="$tmp_store_dir" "${top_cmd_line[@]}")
    285. if [ -n "$store_dir" ]; then
    286. echo "$top_out" | logAndCat "${top_cmd_line[@]}" > "${store_file_prefix}$(( i + 1 ))_top"
    287. fi
    288. echo "$top_out" |
    289. awk 'BEGIN { blockIndex = 0; currentLineHasText = 0; prevLineHasText = 0; } {
    290. currentLineHasText = ($0 != "")
    291. if (prevLineHasText && !currentLineHasText)
    292. blockIndex++ # from text line to empty line, increase block index
    293. if (blockIndex == 3 && ($NF == "java" || $NF == "jsvc")) # $NF(last field) is command field
    294. # only print 4th text block(blockIndex == 3), aka. process info of second top update
    295. print $1 " " $9 # $1 is thread id field, $9 is %cpu field
    296. prevLineHasText = currentLineHasText # update prevLineHasText
    297. }' | sort -k2,2nr
    298. }
    299. __complete_pid_user_by_ps() {
    300. # ps output field: pid, thread id(lwp), user
    301. local -a ps_cmd_line=(ps $ps_process_select_options -wwLo pid,lwp,user --no-headers)
    302. local -r ps_out="$("${ps_cmd_line[@]}")"
    303. if [ -n "$store_dir" ]; then
    304. echo "$ps_out" | logAndCat "${ps_cmd_line[@]}" > "${store_file_prefix}$(( i + 1 ))_ps"
    305. fi
    306. local idx=0
    307. local -a line
    308. while IFS=" " read -a line ; do
    309. (( idx < count )) || break
    310. local threadId="${line[0]}"
    311. local pcpu="${line[1]}"
    312. # output field: pid, threadId, pcpu, user
    313. local output_fields="$( echo "$ps_out" |
    314. awk -v "threadId=$threadId" -v "pcpu=$pcpu" '$2==threadId {
    315. printf "%s %s %s %s\n", $1, threadId, pcpu, $3; exit
    316. }' )"
    317. if [ -n "$output_fields" ]; then
    318. (( idx++ ))
    319. echo "$output_fields"
    320. fi
    321. done
    322. }
    323. # output format is same as function findBusyJavaThreadsByPs
    324. findBusyJavaThreadsByTop() {
    325. __top_threadId_cpu | __complete_pid_user_by_ps
    326. }
    327. printStackOfThreads() {
    328. local -a line
    329. local idx=0
    330. while IFS=" " read -a line ; do
    331. local pid="${line[0]}"
    332. local threadId="${line[1]}"
    333. local threadId0x="0x`printf %x ${threadId}`"
    334. local pcpu="${line[2]}"
    335. local user="${line[3]}"
    336. (( idx++ ))
    337. local jstackFile="${store_file_prefix}$(( i + 1 ))_jstack_${pid}"
    338. [ -f "${jstackFile}" ] || {
    339. local -a jstack_cmd_line=( "$jstack_path" ${force} $mix_native_frames $more_lock_info ${pid} )
    340. if [ "${user}" == "${USER}" ]; then
    341. # run without sudo, when java process user is current user
    342. logAndRun "${jstack_cmd_line[@]}" > ${jstackFile}
    343. elif [ $UID == 0 ]; then
    344. # if java process user is not current user, must run jstack with sudo
    345. logAndRun sudo -u "${user}" "${jstack_cmd_line[@]}" > ${jstackFile}
    346. else
    347. # current user is not root user, so can not run with sudo; print error message and rerun suggestion
    348. redPrint "[$idx] Fail to jstack busy(${pcpu}%) thread(${threadId}/${threadId0x}) stack of java process(${pid}) under user(${user})."
    349. redPrint "User of java process($user) is not current user($USER), need sudo to rerun:"
    350. yellowPrint " sudo ${COMMAND_LINE[@]}"
    351. normalPrint
    352. continue
    353. fi || {
    354. redPrint "[$idx] Fail to jstack busy(${pcpu}%) thread(${threadId}/${threadId0x}) stack of java process(${pid}) under user(${user})."
    355. normalPrint
    356. rm "${jstackFile}" &> /dev/null
    357. continue
    358. }
    359. }
    360. bluePrint "[$idx] Busy(${pcpu}%) thread(${threadId}/${threadId0x}) stack of java process(${pid}) under user(${user}):"
    361. if [ -n "$mix_native_frames" ]; then
    362. local sed_script="/--------------- $threadId ---------------/,/^---------------/ {
    363. /--------------- $threadId ---------------/b # skip first separator line
    364. /^---------------/d # delete second separator line
    365. p
    366. }"
    367. elif [ -n "$force" ]; then
    368. local sed_script="/^Thread ${threadId}:/,/^$/ {
    369. /^$/d; p # delete end separator line
    370. }"
    371. else
    372. local sed_script="/ nid=${threadId0x} /,/^$/ {
    373. /^$/d; p # delete end separator line
    374. }"
    375. fi
    376. {
    377. sed "$sed_script" -n ${jstackFile}
    378. echo
    379. } | tee ${append_file:+-a "$append_file"} ${store_dir:+-a "${store_file_prefix}$PROG"}
    380. done
    381. }
    382. ################################################################################
    383. # Main
    384. ################################################################################
    385. main() {
    386. local i
    387. # if update_count <= 0, infinite loop till user interrupted (eg: CTRL+C)
    388. for (( i = 0; update_count <= 0 || i < update_count; ++i )); do
    389. (( i > 0 )) && sleep "$update_delay"
    390. [ -n "$append_file" -o -n "$store_dir" ] && headInfo | tee ${append_file:+-a "$append_file"} ${store_dir:+-a "${store_file_prefix}$PROG"} > /dev/null
    391. (( update_count != 1 )) && headInfo
    392. if $use_ps; then
    393. findBusyJavaThreadsByPs
    394. else
    395. findBusyJavaThreadsByTop
    396. fi | printStackOfThreads
    397. done
    398. }
    399. main