improve cleanup() in run.sh
[doctor.git] / tests / functions-common
1 #!/bin/bash
2
3 # Test if the named environment variable is set and not zero length
4 # is_set env-var
5 function is_set {
6     local var=\$"$1"
7     eval "[ -n \"$var\" ]"
8 }
9
10 # Prints backtrace info
11 # filename:lineno:function
12 # backtrace level
13 function backtrace {
14     local level=$1
15     local deep
16     deep=$((${#BASH_SOURCE[@]} - 1))
17     echo "[Call Trace]"
18     while [ $level -le $deep ]; do
19         echo "${BASH_SOURCE[$deep]}:${BASH_LINENO[$deep-1]}:${FUNCNAME[$deep-1]}"
20         deep=$((deep - 1))
21     done
22 }
23
24 # Prints line number and "message" in error format
25 # err $LINENO "message"
26 function err {
27     local exitcode=$?
28     local xtrace
29     xtrace=$(set +o | grep xtrace)
30     set +o xtrace
31     local msg="[ERROR] ${BASH_SOURCE[2]}:$1 $2"
32     echo $msg 1>&2;
33     if [[ -n ${LOGDIR} ]]; then
34         echo $msg >> "${LOGDIR}/error.log"
35     fi
36     $xtrace
37     return $exitcode
38 }
39
40 # Prints line number and "message" then exits
41 # die $LINENO "message"
42 function die {
43     local exitcode=$?
44     set +o xtrace
45     local line=$1; shift
46     if [ $exitcode == 0 ]; then
47         exitcode=1
48     fi
49     backtrace 2
50     err $line "$*"
51     # Give buffers a second to flush
52     sleep 1
53     exit $exitcode
54 }
55
56 # Checks an environment variable is not set or has length 0 OR if the
57 # exit code is non-zero and prints "message" and exits
58 # NOTE: env-var is the variable name without a '$'
59 # die_if_not_set $LINENO env-var "message"
60 function die_if_not_set {
61     local exitcode=$?
62     local xtrace
63     xtrace=$(set +o | grep xtrace)
64     set +o xtrace
65     local line=$1; shift
66     local evar=$1; shift
67     if ! is_set $evar || [ $exitcode != 0 ]; then
68         die $line "$*"
69     fi
70     $xtrace
71 }
72
73 # Wait until the condition is met.
74 # wait_until condition timeout interval
75 function wait_until {
76     local condition="$1"
77     local timeout=$2
78     local interval=$3
79
80     while eval ${condition}
81     do
82         sleep ${interval}
83         timeout=$((${timeout} - ${interval}))
84         if [[ ${timeout} < 0 ]]; then
85             err $LINENO "timed out ($condition)..."
86             return 1
87         fi
88     done
89 }