show-busy-java-threads.sh 17 KB

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