From 5e28a3e2d2e7f02d6f0c81ddfe4ae3b0387112b6 Mon Sep 17 00:00:00 2001 From: Kui Shi Date: Fri, 2 Aug 2013 17:26:28 +0800 Subject: [PATCH] Add call trace in error message Call trace can help user to locate problem quickly. stack.sh uses bash as interpreter, which defines a series of "Shell Variables": BASH_SOURCE: An array variable whose members are the source filenames BASH_LINENO: An array variable whose members are the line numbers in source files where each corresponding member of FUNCNAME was invoked. FUNCNAME: An array variable containing the names of all shell functions currently in the execution call stack. run "man bash" and search the variable name to get detailed info. In function backtrace, it gets the call deepth from ${#BASH_SOURCE[@]}, then print the call stack from top to down. In function die, backtrace is called with parameter "2" to ignore the call trace of function "die" and "backtrace". I add a broken function in lib/database, and call it in stack.sh, the output looks like this: [Call Trace] ./stack.sh:104:broken /home/kui/osd/devstack/lib/database:24:die [ERROR] ./stack.sh:24 It is broken Fixes bug # 1207660 Change-Id: I04d0b3ccf783c769e41582c20f48694c19917334 --- functions | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/functions b/functions index 262f70f29f..d28efefe55 100644 --- a/functions +++ b/functions @@ -76,6 +76,19 @@ function cp_it { } +# Prints backtrace info +# filename:lineno:function +function backtrace { + local level=$1 + local deep=$((${#BASH_SOURCE[@]} - 1)) + echo "[Call Trace]" + while [ $level -le $deep ]; do + echo "${BASH_SOURCE[$deep]}:${BASH_LINENO[$deep-1]}:${FUNCNAME[$deep-1]}" + deep=$((deep - 1)) + done +} + + # Prints line number and "message" then exits # die $LINENO "message" function die() { @@ -85,6 +98,7 @@ function die() { if [ $exitcode == 0 ]; then exitcode=1 fi + backtrace 2 err $line "$*" exit $exitcode }