Browse code

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

Kui Shi authored on 2013/08/02 18:26:28
Showing 1 changed files
... ...
@@ -76,6 +76,19 @@ function cp_it {
76 76
 }
77 77
 
78 78
 
79
+# Prints backtrace info
80
+# filename:lineno:function
81
+function backtrace {
82
+    local level=$1
83
+    local deep=$((${#BASH_SOURCE[@]} - 1))
84
+    echo "[Call Trace]"
85
+    while [ $level -le $deep ]; do
86
+        echo "${BASH_SOURCE[$deep]}:${BASH_LINENO[$deep-1]}:${FUNCNAME[$deep-1]}"
87
+        deep=$((deep - 1))
88
+    done
89
+}
90
+
91
+
79 92
 # Prints line number and "message" then exits
80 93
 # die $LINENO "message"
81 94
 function die() {
... ...
@@ -85,6 +98,7 @@ function die() {
85 85
     if [ $exitcode == 0 ]; then
86 86
         exitcode=1
87 87
     fi
88
+    backtrace 2
88 89
     err $line "$*"
89 90
     exit $exitcode
90 91
 }