#! /bin/sh BASEDIR=`dirname $0` BASENAME=`basename ${0%\.*}` LOGDIR="${BASEDIR}/../log" BINDIR="${BASEDIR}/../bin" PID=-1 EXECUTION_SLEEP=0.1 HOSTFILE="/etc/hosts" MSG_NOTFOUND="not found (did you build this test?)" MSG_FAILED="\t[FAILED] (see log file)" MSG_ABORTED="\t[ABORTED]" MSG_SUCCESS="\t[OK]" MSG_PID="target never started" MSG_ERRCODE="error code :" # Cleanup on signal trap "kill `jobs -p` > /dev/null 2>&1" EXIT SIGINT SIGTERM # Create log directory and temporary file mkdir -p "${LOGDIR}" TMPFILE=`mktemp -t 'regress'` # Cleanup previous logs rm -f "${LOGDIR}/${BASENAME}-err.log" ## # Private macros ## checkpid() { local context=$1 if [ "${PID}" -eq -1 ] ; then echo "$0:$LINENO in ${context} : ${MSG_PID}" >&2 exit 1 fi } jobdone() { jobs "${PID}" > "${TMPFILE}" local status=`awk '{ print $2 }' "${TMPFILE}"` if [ $? -ne 0 ] || [ ${status%%(*} = "Done" ] ; then return 1 fi return 0 } ## # Flow control macros ## _cleanup_() { rm -f "${TMPFILE}" PID=-1 } _cktarget_() { if ! [ -x "${BINDIR}/${BASENAME}" ] ; then echo "${BINDIR}/${BASENAME} ${MSG_NOTFOUND}" >&2 exit 1 fi } _startest_() { local args="" stdbuf -o L ${BINDIR}/${BASENAME} "${args}" > "${LOGDIR}/${BASENAME}-err.log" 2>&1 & PID=$! } _sync_() { checkpid "_sync_" wait "${PID}" return $? } _isrunning_() { local timeout=${1:-5} # Timeout at 5s by default local t=1 checkpid "_isrunning_" sleep ${EXECUTION_SLEEP} while [ $t -lt $timeout ] ; do jobdone if [ $? -eq 1 ] ; then return 0 ; fi sleep $t timeout=$(( $timeout - $t )) t=$(( $t * 2 )) done if [ $timeout -gt 0 ] ; then sleep $timeout fi jobdone if [ $? -eq 1 ] ; then return 0 ; fi return 1 # Still running } _log_() { local message="${1:-Unknown error}" echo -e "${message}" >> "${LOGDIR}/${BASENAME}-err.log" } _cleanlog_() { rm -f "${LOGDIR}/${BASENAME}-err.log" } _endtest_() { checkpid "_endtest_" _sync_ local errcode=${1:-$?} if [ "${errcode}" -eq 0 ] ; then echo -e "${BASENAME} ${MSG_SUCCESS}" _cleanlog_ else echo -e "${BASENAME} ${MSG_FAILED}" >&2 _log_ "${MSG_ERRCODE} ${errcode}" fi _cleanup_ } _forcetermin_() { checkpid "_forcetermin_" kill "${PID}" > /dev/null 2>&1 # Must be cleanup explicitly or via or via `_endtest_' } _abortest_() { checkpid "_abortest" _forcetermin_ _sync_ echo -e "${BASENAME} ${MSG_ABORTED} ${1:+($1)}" >&2 _cleanup_ } ## # Inet specific macros ## _getaddrstatus_() { local addr="$1" netstat -la -p tcp | awk 'BEGIN { OFS="|" ; ORS=" " } { if ($4 ~ /'${addr}'/) print $1, $6}' } _addnsrecord_() { local record="$1" local error DNSTAG="#TEMPORARY_RECORD" echo -e "${record} ${DNSTAG}" 2> "${TMPFILE}" >> "${HOSTFILE}" if [ $? -ne 0 ] ; then error=`cat ${TMPFILE}` echo "$0:$LINENO in _addnsrecord_ :${error#*:}" >&2 exit 1 fi } _cleanupdnsrecords_() { sed -i -e "/${DNSTAG}$/d" "${HOSTFILE}" }