Whamcloud - gitweb
b=22668 test_65b fix
[fs/lustre-release.git] / lustre / tests / test-framework.sh
1 #!/bin/bash
2 # vim:expandtab:shiftwidth=4:softtabstop=4:tabstop=4:
3
4 trap 'print_summary && echo "test-framework exiting on error"' ERR
5 set -e
6 #set -x
7
8
9 export REFORMAT=${REFORMAT:-""}
10 export WRITECONF=${WRITECONF:-""}
11 export VERBOSE=false
12 export GMNALNID=${GMNALNID:-/usr/sbin/gmlndnid}
13 export CATASTROPHE=${CATASTROPHE:-/proc/sys/lnet/catastrophe}
14 #export PDSH="pdsh -S -Rssh -w"
15
16 # function used by scripts run on remote nodes
17 LUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}
18 . $LUSTRE/tests/functions.sh
19
20 LUSTRE_TESTS_CFG_DIR=${LUSTRE_TESTS_CFG_DIR:-${LUSTRE}/tests/cfg}
21
22 EXCEPT_LIST_FILE=${EXCEPT_LIST_FILE:-${LUSTRE_TESTS_CFG_DIR}/tests-to-skip.sh}
23
24 if [ -f "$EXCEPT_LIST_FILE" ]; then
25     echo "Reading test skip list from $EXCEPT_LIST_FILE"
26     cat $EXCEPT_LIST_FILE
27     . $EXCEPT_LIST_FILE
28 fi
29
30 assert_DIR () {
31     local failed=""
32     [[ $DIR/ = $MOUNT/* ]] || \
33         { failed=1 && echo "DIR=$DIR not in $MOUNT. Aborting."; }
34     [[ $DIR1/ = $MOUNT1/* ]] || \
35         { failed=1 && echo "DIR1=$DIR1 not in $MOUNT1. Aborting."; }
36     [[ $DIR2/ = $MOUNT2/* ]] || \
37         { failed=1 && echo "DIR2=$DIR2 not in $MOUNT2. Aborting"; }
38
39     [ -n "$failed" ] && exit 99 || true
40 }
41
42 usage() {
43     echo "usage: $0 [-r] [-f cfgfile]"
44     echo "       -r: reformat"
45
46     exit
47 }
48
49 print_summary () {
50     trap 0
51     [ "$TESTSUITE" == "lfscktest" ] && return 0
52     [ -n "$ONLY" ] && echo "WARNING: ONLY is set to ${ONLY}."
53     local form="%-13s %-17s %s\n"
54     printf "$form" "status" "script" "skipped tests E(xcluded) S(low)"
55     echo "------------------------------------------------------------------------------------"
56     for O in $TESTSUITE_LIST; do
57         local skipped=""
58         local slow=""
59         local o=$(echo $O | tr "[:upper:]" "[:lower:]")
60         o=${o//_/-}
61         o=${o//tyn/tyN}
62         local log=${TMP}/${o}.log
63         [ -f $log ] && skipped=$(grep excluded $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
64         [ -f $log ] && slow=$(grep SLOW $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
65         [ "${!O}" = "done" ] && \
66             printf "$form" "Done" "$O" "E=$skipped" && \
67             [ -n "$slow" ] && printf "$form" "-" "-" "S=$slow"
68
69     done
70
71     for O in $TESTSUITE_LIST; do
72         if [ "${!O}" = "no" ]; then
73             # FIXME.
74             # only for those tests suits which are run directly from acc-sm script:
75             # bonnie, iozone, etc.
76             if [ -f "$TESTSUITELOG" ] && grep FAIL $TESTSUITELOG | grep -q ' '$O  ; then
77                printf "$form" "UNFINISHED" "$O" ""  
78             else
79                printf "$form" "Skipped" "$O" ""
80             fi
81         fi
82     done
83
84     for O in $TESTSUITE_LIST; do
85         [ "${!O}" = "done" -o "${!O}" = "no" ] || \
86             printf "$form" "UNFINISHED" "$O" ""
87     done
88 }
89
90 init_test_env() {
91     export LUSTRE=`absolute_path $LUSTRE`
92     export TESTSUITE=`basename $0 .sh`
93     export TEST_FAILED=false
94     export FAIL_ON_SKIP_ENV=${FAIL_ON_SKIP_ENV:-false}
95
96     export MKE2FS=${MKE2FS:-mke2fs}
97     export DEBUGFS=${DEBUGFS:-debugfs}
98     export TUNE2FS=${TUNE2FS:-tune2fs}
99     export E2LABEL=${E2LABEL:-e2label}
100     export DUMPE2FS=${DUMPE2FS:-dumpe2fs}
101     export E2FSCK=${E2FSCK:-e2fsck}
102
103     #[ -d /r ] && export ROOT=${ROOT:-/r}
104     export TMP=${TMP:-$ROOT/tmp}
105     export TESTSUITELOG=${TMP}/${TESTSUITE}.log
106     export HOSTNAME=${HOSTNAME:-`hostname`}
107     if ! echo $PATH | grep -q $LUSTRE/utils; then
108         export PATH=$PATH:$LUSTRE/utils
109     fi
110     if ! echo $PATH | grep -q $LUSTRE/test; then
111         export PATH=$PATH:$LUSTRE/tests
112     fi
113     export LST=${LST:-"$LUSTRE/../lnet/utils/lst"}
114     [ ! -f "$LST" ] && export LST=$(which lst)
115     export MDSRATE=${MDSRATE:-"$LUSTRE/tests/mpi/mdsrate"}
116     [ ! -f "$MDSRATE" ] && export MDSRATE=$(which mdsrate 2> /dev/null)
117     if ! echo $PATH | grep -q $LUSTRE/tests/racer; then
118         export PATH=$PATH:$LUSTRE/tests/racer
119     fi
120     if ! echo $PATH | grep -q $LUSTRE/tests/mpi; then
121         export PATH=$PATH:$LUSTRE/tests/mpi
122     fi
123     export RSYNC_RSH=${RSYNC_RSH:-rsh}
124     export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
125     export LFS=${LFS:-"$LUSTRE/utils/lfs"}
126     [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
127     export LFS=${LFS:-"$LUSTRE/utils/lfs"}
128     [ ! -f "$LFS" ] && export LFS=$(which lfs)
129     export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
130     [ ! -f "$MKFS" ] && export MKFS=$(which mkfs.lustre)
131     export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
132     [ ! -f "$TUNEFS" ] && export TUNEFS=$(which tunefs.lustre)
133     export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
134     export LUSTRE_RMMOD=${LUSTRE_RMMOD:-$LUSTRE/scripts/lustre_rmmod}
135     [ ! -f "$LUSTRE_RMMOD" ] && export LUSTRE_RMMOD=$(which lustre_rmmod 2> /dev/null)
136     export FSTYPE=${FSTYPE:-"ldiskfs"}
137     export NAME=${NAME:-local}
138     export DIR2
139     export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
140
141     if [ "$ACCEPTOR_PORT" ]; then
142         export PORT_OPT="--port $ACCEPTOR_PORT"
143     fi
144
145     export LOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}
146
147     # Paths on remote nodes, if different
148     export RLUSTRE=${RLUSTRE:-$LUSTRE}
149     export RPWD=${RPWD:-$PWD}
150     export I_MOUNTED=${I_MOUNTED:-"no"}
151     if [ ! -f /lib/modules/$(uname -r)/kernel/fs/lustre/mds.ko -a \
152         ! -f `dirname $0`/../mds/mds.ko ]; then
153         export CLIENTMODSONLY=yes
154     fi
155
156     # command line
157
158     while getopts "rvwf:" opt $*; do
159         case $opt in
160             f) CONFIG=$OPTARG;;
161             r) REFORMAT=--reformat;;
162             v) VERBOSE=true;;
163             w) WRITECONF=writeconf;;
164             \?) usage;;
165         esac
166     done
167
168     shift $((OPTIND - 1))
169     ONLY=${ONLY:-$*}
170
171     [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
172     rm -f $TMP/*active
173 }
174
175 case `uname -r` in
176     *) EXT=".ko"; USE_QUOTA=yes;;
177 esac
178
179 pool_list () {
180    do_facet mgs lctl pool_list $1
181 }
182
183 create_pool() {
184     local fsname=${1%%.*}
185     local poolname=${1##$fsname.}
186
187     do_facet mgs lctl pool_new $1
188     local RC=$?
189     # get param should return err unless pool is created
190     [[ $RC -ne 0 ]] && return $RC
191
192     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
193         2>/dev/null || echo foo" "" || RC=1
194     if [[ $RC -eq 0 ]]; then
195         add_pool_to_list $1
196     else
197         error "pool_new failed $1"
198     fi
199     return $RC
200 }
201
202 add_pool_to_list () {
203     local fsname=${1%%.*}
204     local poolname=${1##$fsname.}
205
206     local listvar=${fsname}_CREATED_POOLS
207     eval export ${listvar}=$(expand_list ${!listvar} $poolname)
208 }
209
210 remove_pool_from_list () {
211     local fsname=${1%%.*}
212     local poolname=${1##$fsname.}
213
214     local listvar=${fsname}_CREATED_POOLS
215     eval export ${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
216 }
217
218 module_loaded () {
219    /sbin/lsmod | grep -q $1
220 }
221
222 load_module() {
223     module=$1
224     shift
225     BASE=`basename $module $EXT`
226
227     module_loaded ${BASE} && return
228
229     if [ "$BASE" == "lnet_selftest" ] && \
230             [ -f ${LUSTRE}/../lnet/selftest/${module}${EXT} ]; then
231         insmod ${LUSTRE}/../lnet/selftest/${module}${EXT}
232
233     elif [ -f ${LUSTRE}/${module}${EXT} ]; then
234         insmod ${LUSTRE}/${module}${EXT} $@
235     else
236         # must be testing a "make install" or "rpm" installation
237         modprobe $BASE $@
238     fi
239 }
240
241 load_modules_local() {
242     if [ -n "$MODPROBE" ]; then
243         # use modprobe
244     return 0
245     fi
246     if [ "$HAVE_MODULES" = true ]; then
247     # we already loaded
248         return 0
249     fi
250     HAVE_MODULES=true
251
252     echo Loading modules from $LUSTRE
253     load_module ../lnet/libcfs/libcfs
254     [ "$PTLDEBUG" ] && lctl set_param debug="$PTLDEBUG"
255     [ "$SUBSYSTEM" ] && lctl set_param subsystem_debug="${SUBSYSTEM# }"
256     local MODPROBECONF=
257     [ -f /etc/modprobe.conf ] && MODPROBECONF=/etc/modprobe.conf
258     [ ! "$MODPROBECONF" -a -d /etc/modprobe.d ] && MODPROBECONF=/etc/modprobe.d/Lustre
259     [ -z "$LNETOPTS" -a "$MODPROBECONF" ] && \
260         LNETOPTS=$(awk '/^options lnet/ { print $0}' $MODPROBECONF | sed 's/^options lnet //g')
261     echo $LNETOPTS | grep -q "accept=all"  || LNETOPTS="$LNETOPTS accept=all";
262     # bug 19380
263     # disable it for now since it only hides the stack overflow upon test w/
264     # local servers
265 #    if [ "$NETTYPE" = "tcp" -o "$NETTYPE" = "o2ib" -o "$NETTYPE" = "ptl" ]; then
266 #        echo $LNETOPTS | grep -q "local_nid_dist_zero=0" ||
267 #        LNETOPTS="$LNETOPTS local_nid_dist_zero=0"
268 #    fi
269     echo "lnet options: '$LNETOPTS'"
270     # note that insmod will ignore anything in modprobe.conf
271     load_module ../lnet/lnet/lnet $LNETOPTS
272     LNETLND=${LNETLND:-"socklnd/ksocklnd"}
273     load_module ../lnet/klnds/$LNETLND
274     load_module lvfs/lvfs
275     load_module obdclass/obdclass
276     load_module ptlrpc/ptlrpc
277     [ "$USE_QUOTA" = "yes" ] && load_module quota/lquota
278     load_module mdc/mdc
279     load_module osc/osc
280     load_module lov/lov
281     load_module mgc/mgc
282     if ! client_only; then
283         load_module mgs/mgs
284         load_module mds/mds
285         grep -q crc16 /proc/kallsyms || { modprobe crc16 2>/dev/null || true; }
286         grep -q jbd /proc/kallsyms || { modprobe jbd 2>/dev/null || true; }
287         [ "$FSTYPE" = "ldiskfs" ] && load_module ../ldiskfs/ldiskfs/ldiskfs
288         load_module lvfs/fsfilt_$FSTYPE
289         load_module ost/ost
290         load_module obdfilter/obdfilter
291     fi
292
293     load_module llite/lustre
294     load_module llite/llite_lloop
295     rm -f $TMP/ogdb-$HOSTNAME
296     OGDB=$TMP
297     [ -d /r ] && OGDB="/r/tmp"
298     $LCTL modules > $OGDB/ogdb-$HOSTNAME
299     # 'mount' doesn't look in $PATH, just sbin
300     [ -f $LUSTRE/utils/mount.lustre ] && cp $LUSTRE/utils/mount.lustre /sbin/. || true
301 }
302
303 load_modules () {
304     load_modules_local
305     # bug 19124
306     # load modules on remote nodes optionally
307     # lustre-tests have to be installed on these nodes
308     if $LOAD_MODULES_REMOTE ; then
309         local list=$(comma_list $(remote_nodes_list))
310         echo loading modules on $list
311         do_rpc_nodes $list load_modules 
312     fi
313 }
314
315 check_mem_leak () {
316     LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
317     LEAK_PORTALS=$(dmesg | tail -n 20 | grep "Portals memory leaked" || true)
318     if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
319         echo "$LEAK_LUSTRE" 1>&2
320         echo "$LEAK_PORTALS" 1>&2
321         mv $TMP/debug $TMP/debug-leak.`date +%s` || true
322         echo "Memory leaks detected"
323         [ -n "$IGNORE_LEAK" ] && { echo "ignoring leaks" && return 0; } || true
324         return 1
325     fi
326 }
327
328 unload_modules() {
329     wait_exit_ST client # bug 12845
330
331     if $LOAD_MODULES_REMOTE ; then
332         local list=$(comma_list $(remote_nodes_list))
333         if [ ! -z $list ]; then
334             echo unloading modules on $list
335             do_rpc_nodes $list $LUSTRE_RMMOD $FSTYPE
336             do_rpc_nodes $list check_mem_leak
337         fi
338     fi
339
340     $LUSTRE_RMMOD $FSTYPE || return 2
341
342     HAVE_MODULES=false
343
344     check_mem_leak || return 254
345
346     echo "modules unloaded."
347     return 0
348 }
349
350 # Facet functions
351 mount_facet() {
352     local facet=$1
353     shift
354     local dev=$(facet_active $facet)_dev
355     local opt=${facet}_opt
356     local mntpt=$(facet_mntpt $facet)
357
358     echo "Starting ${facet}: ${!opt} $@ ${!dev} $mntpt"
359     do_facet ${facet} mount -t lustre ${!opt} $@ ${!dev} $mntpt
360     RC=${PIPESTATUS[0]}
361     if [ $RC -ne 0 ]; then
362         echo "mount -t lustre $@ ${!dev} $mntpt"
363         echo "Start of ${!dev} on ${facet} failed ${RC}"
364     else
365         do_facet ${facet} "lctl set_param debug=\\\"$PTLDEBUG\\\"; \
366             lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\"; \
367             lctl set_param debug_mb=${DEBUG_SIZE}; \
368             sync"
369
370         label=$(do_facet ${facet} "$E2LABEL ${!dev}")
371         [ -z "$label" ] && echo no label for ${!dev} && exit 1
372         eval export ${facet}_svc=${label}
373         echo Started ${label}
374     fi
375     return $RC
376 }
377
378 # start facet device options
379 start() {
380     local facet=$1
381     shift
382     local device=$1
383     shift
384     eval export ${facet}_dev=${device}
385     eval export ${facet}_opt=\"$@\"
386
387     local varname=${facet}failover_dev
388     if [ -n "${!varname}" ] ; then
389         eval export ${facet}failover_dev=${!varname}
390     else
391         eval export ${facet}failover_dev=$device
392     fi
393
394     local mntpt=$(facet_mntpt $facet)
395     do_facet ${facet} mkdir -p $mntpt
396     eval export ${facet}_MOUNT=$mntpt
397     mount_facet ${facet}
398     RC=$?
399     return $RC
400 }
401
402 stop() {
403     local running
404     local facet=$1
405     shift
406     local HOST=`facet_active_host $facet`
407     [ -z $HOST ] && echo stop: no host for $facet && return 0
408
409     local mntpt=$(facet_mntpt $facet)
410     running=$(do_facet ${facet} "grep -c $mntpt' ' /proc/mounts") || true
411     if [ ${running} -ne 0 ]; then
412         echo "Stopping $mntpt (opts:$@)"
413         do_facet ${facet} umount -d $@ $mntpt
414     fi
415
416     # umount should block, but we should wait for unrelated obd's
417     # like the MGS or MGC to also stop.
418
419     wait_exit_ST ${facet}
420 }
421
422 # set quota version (both administrative and operational quotas)
423 quota_set_version() {
424         do_facet mds "lctl set_param lquota.${FSNAME}-MDT*.quota_type=$1"
425         local varsvc
426         local osts=$(get_facets OST)
427         for ost in ${osts//,/ }; do
428                 varsvc=${ost}_svc
429                 do_facet $ost "lctl set_param lquota.${!varsvc}.quota_type=$1"
430         done
431 }
432
433 # save quota version (both administrative and operational quotas)
434 # the function will also switch to the new version and the new type
435 quota_save_version() {
436     local spec=$1
437     local ver=$(tr -c -d "123" <<< $spec)
438     local type=$(tr -c -d "ug" <<< $spec)
439
440     local lustre_version=$(get_lustre_version mds)
441     if [[ $lustre_version = 1.8* ]] ; then
442         $LFS quotaoff -ug $MOUNT # just in case
443         [ -n "$ver" ] && quota_set_version $ver
444     else
445         echo mds running $lustre_version 
446         [ -n "$ver" -a "$ver" != "3" ] && error "wrong quota version specifier"
447     fi
448
449     [ -n "$type" ] && { $LFS quotacheck -$type $MOUNT || error "quotacheck has failed"; }
450
451     do_facet mgs "lctl conf_param ${FSNAME}-MDT*.$(get_md_name).quota_type=$spec"
452     local varsvc
453     local osts=$(get_facets OST)
454     for ost in ${osts//,/ }; do
455         varsvc=${ost}_svc
456         do_facet mgs "lctl conf_param ${!varsvc}.ost.quota_type=$spec"
457     done
458 }
459
460 # client could mount several lustre
461 quota_type () {
462     local fsname=${1:-$FSNAME}
463     local rc=0
464     do_facet mgs lctl get_param md*.${fsname}-MDT*.quota_type || rc=$?
465     do_nodes $(comma_list $(osts_nodes)) \
466         lctl get_param obdfilter.${fsname}-OST*.quota_type || rc=$?
467     return $rc
468 }
469
470 restore_quota_type () {
471    local mntpt=${1:-$MOUNT}
472    local quota_type=$(quota_type $FSNAME | grep MDT | cut -d "=" -f2)
473    if [ ! "$old_QUOTA_TYPE" ] || [ "$quota_type" = "$old_QUOTA_TYPE" ]; then
474         return
475    fi
476    quota_save_version $old_QUOTA_TYPE
477 }
478
479 setup_quota(){
480     local mntpt=$1
481
482     # We need:
483     # 1. run quotacheck only if quota is off
484     # 2. save the original quota_type params, restore them after testing
485
486     # Suppose that quota type the same on mds and ost
487     local quota_type=$(quota_type | grep MDT | cut -d "=" -f2)
488     [ ${PIPESTATUS[0]} -eq 0 ] || error "quota_type failed!"
489     echo "[HOST:$HOSTNAME] [old_quota_type:$quota_type] [new_quota_type:$QUOTA_TYPE]"
490     if [ "$quota_type" != "$QUOTA_TYPE" ]; then
491         export old_QUOTA_TYPE=$quota_type
492         quota_save_version $QUOTA_TYPE
493     fi
494
495     local quota_usrs=$QUOTA_USERS
496
497     # get_filesystem_size
498     local disksz=$(lfs df $mntpt | grep "filesystem summary:"  | awk '{print $3}')
499     local blk_soft=$((disksz + 1024))
500     local blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over
501
502     local Inodes=$(lfs df -i $mntpt | grep "filesystem summary:"  | awk '{print $3}')
503     local i_soft=$Inodes
504     local i_hard=$((i_soft + i_soft / 20))
505
506     echo "Total disk size: $disksz  block-softlimit: $blk_soft block-hardlimit:
507         $blk_hard inode-softlimit: $i_soft inode-hardlimit: $i_hard"
508
509     local cmd
510     for usr in $quota_usrs; do
511         echo "Setting up quota on $client:$mntpt for $usr..."
512         for type in u g; do
513             cmd="$LFS setquota -$type $usr -b $blk_soft -B $blk_hard -i $i_soft -I $i_hard $mntpt"
514             echo "+ $cmd"
515             eval $cmd || error "$cmd FAILED!"
516         done
517         # display the quota status
518         echo "Quota settings for $usr : "
519         $LFS quota -v -u $usr $mntpt || true
520     done
521 }
522
523 zconf_mount() {
524     local OPTIONS
525     local client=$1
526     local mnt=$2
527     # Only supply -o to mount if we have options
528     if [ -n "$MOUNTOPT" ]; then
529         OPTIONS="-o $MOUNTOPT"
530     fi
531     local device=$MGSNID:/$FSNAME
532     if [ -z "$mnt" -o -z "$FSNAME" ]; then
533         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
534         exit 1
535     fi
536
537     echo "Starting client: $client: $OPTIONS $device $mnt"
538     do_node $client mkdir -p $mnt
539     do_node $client mount -t lustre $OPTIONS $device $mnt || return 1
540     do_node $client "lctl set_param debug=\\\"$PTLDEBUG\\\";
541         lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
542         lctl set_param debug_mb=${DEBUG_SIZE}"
543
544     return 0
545 }
546
547 zconf_umount() {
548     local client=$1
549     local mnt=$2
550     local force
551     local busy
552     local need_kill
553
554     [ "$3" ] && force=-f
555     local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
556     if [ $running -ne 0 ]; then
557         echo "Stopping client $client $mnt (opts:$force)"
558         do_node $client lsof -t $mnt || need_kill=no
559         if [ "x$force" != "x" -a "x$need_kill" != "xno" ]; then
560             pids=$(do_node $client lsof -t $mnt | sort -u);
561             if [ -n $pids ]; then
562                 do_node $client kill -9 $pids || true
563             fi
564         fi
565
566         busy=$(do_node $client "umount $force $mnt 2>&1" | grep -c "busy") || true
567         if [ $busy -ne 0 ] ; then
568             echo "$mnt is still busy, wait one second" && sleep 1
569             do_node $client umount $force $mnt
570         fi
571     fi
572 }
573
574 # nodes is comma list
575 sanity_mount_check_nodes () {
576     local nodes=$1
577     shift
578     local mnts="$@"
579     local mnt
580
581     # FIXME: assume that all cluster nodes run the same os
582     [ "$(uname)" = Linux ] || return 0
583
584     local rc=0
585     for mnt in $mnts ; do
586         do_nodes $nodes "running=\\\$(grep -c $mnt' ' /proc/mounts);
587 mpts=\\\$(mount | grep -w -c $mnt);
588 if [ \\\$running -ne \\\$mpts ]; then
589     echo \\\$(hostname) env are INSANE!;
590     exit 1;
591 fi"
592     [ $? -eq 0 ] || rc=1
593     done
594     return $rc
595 }
596
597 sanity_mount_check_servers () {
598     [ "$CLIENTONLY" ] && 
599         { echo "CLIENTONLY mode, skip mount_check_servers"; return 0; } || true
600     echo Checking servers environments
601
602     # FIXME: modify get_facets to display all facets wo params
603     local facets="$(get_facets OST),$(get_facets MDS),mgs"
604     local node
605     local mntpt
606     local facet
607     for facet in ${facets//,/ }; do
608         node=$(facet_host ${facet})
609         mntpt=$(facet_mntpt $facet)
610         sanity_mount_check_nodes $node $mntpt ||
611             { error "server $node environments are insane!"; return 1; }
612     done
613 }
614
615 sanity_mount_check_clients () {
616     local clients=${1:-$CLIENTS}
617     local mntpt=${2:-$MOUNT}
618     local mntpt2=${3:-$MOUNT2}
619
620     [ -z $clients ] && clients=$(hostname)
621     echo Checking clients $clients environments
622
623     sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
624        error "clients environments are insane!"
625 }
626
627 sanity_mount_check () {
628     sanity_mount_check_servers || return 1
629     sanity_mount_check_clients || return 2
630 }
631
632 # mount clients if not mouted
633 zconf_mount_clients() {
634     local clients=$1
635     local mnt=$2
636     local OPTIONS=${3:-$MOUNTOPT}
637
638     # Only supply -o to mount if we have options
639     if [ "$OPTIONS" ]; then
640         OPTIONS="-o $OPTIONS"
641     fi
642     local device=$MGSNID:/$FSNAME
643     if [ -z "$mnt" -o -z "$FSNAME" ]; then
644         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
645         exit 1
646     fi
647
648     echo "Starting client $clients: $OPTIONS $device $mnt"
649
650     do_nodes $clients "
651 running=\\\$(mount | grep -c $mnt' ');
652 rc=0;
653 if [ \\\$running -eq 0 ] ; then
654     mkdir -p $mnt;
655     mount -t lustre $OPTIONS $device $mnt;
656     rc=$?;
657 fi;
658 exit $rc"
659
660     echo "Started clients $clients: "
661     do_nodes $clients "mount | grep -w $mnt"
662
663     do_nodes $clients "sysctl -w lnet.debug=\\\"$PTLDEBUG\\\";
664         sysctl -w lnet.subsystem_debug=\\\"${SUBSYSTEM# }\\\";
665         sysctl -w lnet.debug_mb=${DEBUG_SIZE};"
666
667     return 0
668 }
669
670 zconf_umount_clients() {
671     local clients=$1
672     local mnt=$2
673     local force
674
675     [ "$3" ] && force=-f
676
677     echo "Stopping clients: $clients $mnt (opts:$force)"
678     do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
679 if [ \\\$running -ne 0 ] ; then
680 echo Stopping client \\\$(hostname) $mnt opts:$force;
681 lsof -t $mnt || need_kill=no;
682 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
683     pids=\\\$(lsof -t $mnt | sort -u);
684     if [ -n \\\"\\\$pids\\\" ]; then
685              kill -9 \\\$pids;
686     fi
687 fi;
688 busy=\\\$(umount $force $mnt 2>&1 | grep -c "busy");
689 if [ \\\$busy -ne 0 ] ; then
690     echo "$mnt is still busy, wait one second" && sleep 1;
691     umount $force $mnt;
692 fi
693 fi"
694 }
695
696 shudown_node_hard () {
697     local host=$1
698     local attempts=3
699
700     for i in $(seq $attempts) ; do
701         $POWER_DOWN $host
702         sleep 1
703         ping -w 3 -c 1 $host > /dev/null 2>&1 || return 0
704         echo "waiting for $host to fail attempts=$attempts"
705         [ $i -lt $attempts ] || \
706             { echo "$host still pingable after power down! attempts=$attempts" && return 1; }
707     done
708 }
709
710 shutdown_client() {
711     local client=$1
712     local mnt=${2:-$MOUNT}
713     local attempts=3
714
715     if [ "$FAILURE_MODE" = HARD ]; then
716         shudown_node_hard $client
717     else
718        zconf_umount_clients $client $mnt -f
719     fi
720 }
721
722 shutdown_facet() {
723     local facet=$1
724     if [ "$FAILURE_MODE" = HARD ]; then
725         shudown_node_hard $(facet_active_host $facet)
726     elif [ "$FAILURE_MODE" = SOFT ]; then
727         stop $facet
728     fi
729 }
730
731 reboot_facet() {
732     facet=$1
733     if [ "$FAILURE_MODE" = HARD ]; then
734         $POWER_UP `facet_active_host $facet`
735     else
736         sleep 10
737     fi
738 }
739
740 boot_node() {
741     local node=$1
742     if [ "$FAILURE_MODE" = HARD ]; then
743        $POWER_UP $node
744        wait_for_host $node
745     fi
746 }
747
748 # recovery-scale functions
749 check_progs_installed () {
750     local clients=$1
751     shift
752     local progs=$@
753
754     do_nodes $clients "PATH=:$PATH; status=true;
755 for prog in $progs; do
756     if ! [ \\\"\\\$(which \\\$prog)\\\"  -o  \\\"\\\${!prog}\\\" ]; then
757        echo \\\$prog missing on \\\$(hostname);
758        status=false;
759     fi
760 done;
761 eval \\\$status"
762 }
763
764 client_var_name() {
765     echo __$(echo $1 | tr '-' 'X')
766 }
767
768 start_client_load() {
769     local client=$1
770     local load=$2
771     local var=$(client_var_name $client)_load
772     eval export ${var}=$load
773
774     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
775                               BREAK_ON_ERROR=$BREAK_ON_ERROR \
776                               END_RUN_FILE=$END_RUN_FILE \
777                               LOAD_PID_FILE=$LOAD_PID_FILE \
778                               TESTSUITELOG=$TESTSUITELOG \
779                               run_${load}.sh" &
780     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $!"
781     log "Started client load: ${load} on $client"
782
783     return 0
784 }
785
786 start_client_loads () {
787     local -a clients=(${1//,/ })
788     local numloads=${#CLIENT_LOADS[@]}
789     local testnum
790
791     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
792         testnum=$((nodenum % numloads))
793         start_client_load ${clients[nodenum]} ${CLIENT_LOADS[testnum]}
794     done
795     # bug 22169: wait the background threads to start
796     sleep 2
797 }
798
799 # only for remote client
800 check_client_load () {
801     local client=$1
802     local var=$(client_var_name $client)_load
803     local TESTLOAD=run_${!var}.sh
804
805     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
806
807     # bug 18914: try to connect several times not only when
808     # check ps, but  while check_catastrophe also
809     local tries=3
810     local RC=254
811     while [ $RC = 254 -a $tries -gt 0 ]; do
812         let tries=$tries-1
813         # assume success
814         RC=0
815         if ! check_catastrophe $client; then
816             RC=${PIPESTATUS[0]}
817             if [ $RC -eq 254 ]; then
818                 # FIXME: not sure how long we shuold sleep here
819                 sleep 10
820                 continue
821             fi
822             echo "check catastrophe failed: RC=$RC "
823             return $RC
824         fi
825     done
826
827     # We can continue try to connect if RC=254
828     # Just print the warning about this
829     if [ $RC = 254 ]; then
830         echo "got a return status of $RC from do_node while checking catastrophe on $client"
831     fi
832
833     # see if the load is still on the client
834     tries=3
835     RC=254
836     while [ $RC = 254 -a $tries -gt 0 ]; do
837         let tries=$tries-1
838         # assume success
839         RC=0
840         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
841             RC=${PIPESTATUS[0]}
842             sleep 30
843         fi
844     done
845     if [ $RC = 254 ]; then
846         echo "got a return status of $RC from do_node while checking (catastrophe and 'ps') the client load on $client"
847         # see if we can diagnose a bit why this is
848     fi
849
850     return $RC
851 }
852 check_client_loads () {
853    local clients=${1//,/ }
854    local client=
855    local rc=0
856
857    for client in $clients; do
858       check_client_load $client
859       rc=${PIPESTATUS[0]}
860       if [ "$rc" != 0 ]; then
861         log "Client load failed on node $client, rc=$rc"
862         return $rc
863       fi
864    done
865 }
866
867 restart_client_loads () {
868     local clients=${1//,/ }
869     local expectedfail=${2:-""}
870     local client=
871     local rc=0
872
873     for client in $clients; do
874         check_client_load $client
875         rc=${PIPESTATUS[0]}
876         if [ "$rc" != 0 -a "$expectedfail" ]; then
877             local var=$(client_var_name $client)_load
878             start_client_load $client ${!var}
879             echo "Restarted client load ${!var}: on $client. Checking ..."
880             check_client_load $client
881             rc=${PIPESTATUS[0]}
882             if [ "$rc" != 0 ]; then
883                 log "Client load failed to restart on node $client, rc=$rc"
884                 # failure one client load means test fail
885                 # we do not need to check other
886                 return $rc
887             fi
888         else
889             return $rc
890         fi
891     done
892 }
893 # End recovery-scale functions
894
895 # verify that lustre actually cleaned up properly
896 cleanup_check() {
897     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
898         error "LBUG/LASSERT detected"
899     BUSY=`dmesg | grep -i destruct || true`
900     if [ "$BUSY" ]; then
901         echo "$BUSY" 1>&2
902         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
903         exit 205
904     fi
905
906     check_mem_leak || exit 204
907
908     [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl && \
909         echo "$0: lustre didn't clean up..." 1>&2 && return 202 || true
910
911     if module_loaded lnet || module_loaded libcfs; then
912         echo "$0: modules still loaded..." 1>&2
913         /sbin/lsmod 1>&2
914         return 203
915     fi
916     return 0
917 }
918
919 wait_update () {
920     local node=$1
921     local TEST=$2
922     local FINAL=$3
923     local MAX=${4:-90}
924
925         local RESULT
926         local WAIT=0
927         local sleep=5
928         while [ true ]; do
929             RESULT=$(do_node $node "$TEST")
930             if [ "$RESULT" == "$FINAL" ]; then
931                 echo "Updated after $WAIT sec: wanted '$FINAL' got '$RESULT'"
932                 return 0
933             fi
934             [ $WAIT -ge $MAX ] && break
935             echo "Waiting $((MAX - WAIT)) secs for update"
936             WAIT=$((WAIT + sleep))
937             sleep $sleep
938         done
939         echo "Update not seen after $MAX sec: wanted '$FINAL' got '$RESULT'"
940         return 3
941 }
942
943 wait_update_facet () {
944     local facet=$1
945     shift
946     wait_update  $(facet_active_host $facet) "$@"
947 }
948
949 wait_delete_completed () {
950     local TOTALPREV=`lctl get_param -n osc.*.kbytesavail | \
951                      awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
952
953     local WAIT=0
954     local MAX_WAIT=20
955     while [ "$WAIT" -ne "$MAX_WAIT" ]; do
956         sleep 1
957         TOTAL=`lctl get_param -n osc.*.kbytesavail | \
958                awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
959         [ "$TOTAL" -eq "$TOTALPREV" ] && break
960         echo "Waiting delete completed ... prev: $TOTALPREV current: $TOTAL "
961         TOTALPREV=$TOTAL
962         WAIT=$(( WAIT + 1))
963     done
964     echo "Delete completed."
965 }
966
967 wait_for_host() {
968     local host=$1
969     check_network "$host" 900
970     while ! do_node $host hostname  > /dev/null; do sleep 5; done
971 }
972
973 wait_for() {
974     local facet=$1
975     local host=`facet_active_host $facet`
976     wait_for_host $host
977 }
978
979 wait_recovery_complete () {
980     local facet=$1
981
982     # Use default policy if $2 is not passed by caller.
983     local MAX=${2:-$(max_recovery_time)}
984
985     local var_svc=${facet}_svc
986     local procfile="*.${!var_svc}.recovery_status"
987     local WAIT=0
988     local STATUS=
989
990     while [ $WAIT -lt $MAX ]; do
991         STATUS=$(do_facet $facet lctl get_param -n $procfile | grep status)
992         [[ $STATUS = "status: COMPLETE" ]] && return 0
993         sleep 5
994         WAIT=$((WAIT + 5))
995         echo "Waiting $((MAX - WAIT)) secs for $facet recovery done. $STATUS"
996     done
997     echo "$facet recovery not done in $MAX sec. $STATUS"
998     return 1
999 }
1000
1001 wait_exit_ST () {
1002     local facet=$1
1003
1004     local WAIT=0
1005     local INTERVAL=1
1006     local running
1007     # conf-sanity 31 takes a long time cleanup
1008     while [ $WAIT -lt 300 ]; do
1009         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
1010         [ -z "${running}" ] && return 0
1011         echo "waited $WAIT for${running}"
1012         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
1013         sleep $INTERVAL
1014         WAIT=$((WAIT + INTERVAL))
1015     done
1016     echo "service didn't stop after $WAIT seconds.  Still running:"
1017     echo ${running}
1018     return 1
1019 }
1020
1021 wait_remote_prog () {
1022    local prog=$1
1023    local WAIT=0
1024    local INTERVAL=5
1025    local rc=0
1026
1027    [ "$PDSH" = "no_dsh" ] && return 0
1028
1029    while [ $WAIT -lt $2 ]; do
1030         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
1031         [ -z "${running}" ] && return 0 || true
1032         echo "waited $WAIT for: "
1033         echo "$running"
1034         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
1035         sleep $INTERVAL
1036         WAIT=$((WAIT + INTERVAL))
1037     done
1038     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
1039     [ -z "$pids" ] && return 0
1040     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
1041     # FIXME: not portable
1042     for pid in $pids; do
1043         cat /proc/${pid}/status || true
1044         cat /proc/${pid}/wchan || true
1045         echo "Killing $pid"
1046         kill -9 $pid || true
1047         sleep 1
1048         ps -P $pid && rc=1
1049     done
1050
1051     return $rc
1052 }
1053
1054 clients_up() {
1055     # not every config has many clients
1056     sleep 1
1057     if [ -n "$CLIENTS" ]; then
1058         $PDSH $CLIENTS "stat -f $MOUNT" > /dev/null
1059     else
1060         stat -f $MOUNT > /dev/null
1061     fi
1062 }
1063
1064 client_up() {
1065     local client=$1
1066     # usually checked on particular client or locally
1067     sleep 1
1068     if [ ! -z "$client" ]; then
1069         $PDSH $client "stat -f $MOUNT" > /dev/null
1070     else
1071         stat -f $MOUNT > /dev/null
1072     fi
1073 }
1074
1075 client_evicted() {
1076     ! client_up $1
1077 }
1078
1079 client_reconnect() {
1080     uname -n >> $MOUNT/recon
1081     if [ -z "$CLIENTS" ]; then
1082         df $MOUNT; uname -n >> $MOUNT/recon
1083     else
1084         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
1085     fi
1086     echo Connected clients:
1087     cat $MOUNT/recon
1088     ls -l $MOUNT/recon > /dev/null
1089     rm $MOUNT/recon
1090 }
1091
1092 facet_failover() {
1093     local facet=$1
1094     local sleep_time=$2
1095     echo "Failing $facet on node `facet_active_host $facet`"
1096     shutdown_facet $facet
1097     [ -n "$sleep_time" ] && sleep $sleep_time
1098     reboot_facet $facet
1099     clients_up &
1100     DFPID=$!
1101     RECOVERY_START_TIME=`date +%s`
1102     echo "df pid is $DFPID"
1103     change_active $facet
1104     local TO=`facet_active_host $facet`
1105     echo "Failover $facet to $TO"
1106     wait_for $facet
1107     mount_facet $facet || error "Restart of $facet failed"
1108 }
1109
1110 obd_name() {
1111     local facet=$1
1112 }
1113
1114 replay_barrier() {
1115     local facet=$1
1116     do_facet $facet sync
1117     df $MOUNT
1118     local svc=${facet}_svc
1119     do_facet $facet $LCTL --device %${!svc} notransno
1120     do_facet $facet $LCTL --device %${!svc} readonly
1121     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1122     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1123 }
1124
1125 replay_barrier_nodf() {
1126     local facet=$1    echo running=${running}
1127     do_facet $facet sync
1128     local svc=${facet}_svc
1129     echo Replay barrier on ${!svc}
1130     do_facet $facet $LCTL --device %${!svc} notransno
1131     do_facet $facet $LCTL --device %${!svc} readonly
1132     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1133     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1134 }
1135
1136 mds_evict_client() {
1137     UUID=`lctl get_param -n mdc.${mds_svc}-mdc-*.uuid`
1138     local mdtdevice=$(get_mds_mdt_device_proc_path)
1139     do_facet mds "lctl set_param -n ${mdtdevice}.${mds_svc}.evict_client $UUID"
1140 }
1141
1142 ost_evict_client() {
1143     UUID=`lctl get_param -n osc.${ost1_svc}-osc-*.uuid`
1144     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
1145 }
1146
1147 fail() {
1148     facet_failover $* || error "failover: $?"
1149     clients_up || error "post-failover df: $?"
1150 }
1151
1152 fail_nodf() {
1153     local facet=$1
1154     facet_failover $facet
1155 }
1156
1157 fail_abort() {
1158     local facet=$1
1159     stop $facet
1160     change_active $facet
1161     mount_facet $facet -o abort_recovery
1162     clients_up || echo "first df failed: $?"
1163     clients_up || error "post-failover df: $?"
1164 }
1165
1166 do_lmc() {
1167     echo There is no lmc.  This is mountconf, baby.
1168     exit 1
1169 }
1170
1171 h2gm () {
1172     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1173         ID=`$PDSH $1 $GMNALNID -l | cut -d\  -f2`
1174         echo $ID"@gm"
1175     fi
1176 }
1177
1178 h2name_or_ip() {
1179     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1180         echo $1"@$2"
1181     fi
1182 }
1183
1184 h2ptl() {
1185    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1186        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
1187        if [ -z "$ID" ]; then
1188            echo "Could not get a ptl id for $1..."
1189            exit 1
1190        fi
1191        echo $ID"@ptl"
1192    fi
1193 }
1194 declare -fx h2ptl
1195
1196 h2tcp() {
1197     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1198         echo $1"@tcp"
1199     fi
1200 }
1201 declare -fx h2tcp
1202
1203 h2elan() {
1204     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1205         if type __h2elan >/dev/null 2>&1; then
1206             ID=$(__h2elan $1)
1207         else
1208             ID=`echo $1 | sed 's/[^0-9]*//g'`
1209         fi
1210         echo $ID"@elan"
1211     fi
1212 }
1213 declare -fx h2elan
1214
1215 h2openib() {
1216     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1217         ID=`echo $1 | sed 's/[^0-9]*//g'`
1218         echo $ID"@openib"
1219     fi
1220 }
1221 declare -fx h2openib
1222
1223 h2o2ib() {
1224     h2name_or_ip "$1" "o2ib"
1225 }
1226 declare -fx h2o2ib
1227
1228 facet_host() {
1229     local facet=$1
1230
1231     [ "$facet" == client ] && echo -n $HOSTNAME && return
1232     varname=${facet}_HOST
1233     if [ -z "${!varname}" ]; then
1234         if [ "${facet:0:3}" == "ost" ]; then
1235             eval ${facet}_HOST=${ost_HOST}
1236         fi
1237     fi
1238     echo -n ${!varname}
1239 }
1240
1241 facet_active() {
1242     local facet=$1
1243     local activevar=${facet}active
1244
1245     if [ -f $TMP/${facet}active ] ; then
1246         source $TMP/${facet}active
1247     fi
1248
1249     active=${!activevar}
1250     if [ -z "$active" ] ; then
1251         echo -n ${facet}
1252     else
1253         echo -n ${active}
1254     fi
1255 }
1256
1257 facet_active_host() {
1258     local facet=$1
1259     local active=`facet_active $facet`
1260     if [ "$facet" == client ]; then
1261         echo $HOSTNAME
1262     else
1263         echo `facet_host $active`
1264     fi
1265 }
1266
1267 change_active() {
1268     local facet=$1
1269     local failover=${facet}failover
1270     host=`facet_host $failover`
1271     [ -z "$host" ] && return
1272     local curactive=`facet_active $facet`
1273     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
1274         eval export ${facet}active=$facet
1275     else
1276         eval export ${facet}active=$failover
1277     fi
1278     # save the active host for this facet
1279     local activevar=${facet}active
1280     echo "$activevar=${!activevar}" > $TMP/$activevar
1281 }
1282
1283 do_node() {
1284     local verbose=false
1285     # do not stripe off hostname if verbose, bug 19215
1286     if [ x$1 = x--verbose ]; then
1287         shift
1288         verbose=true
1289     fi
1290
1291     local HOST=$1
1292     shift
1293     local myPDSH=$PDSH
1294     if [ "$HOST" = "$HOSTNAME" ]; then
1295         myPDSH="no_dsh"
1296     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
1297         echo "cannot run remote command on $HOST with $myPDSH"
1298         return 128
1299     fi
1300     if $VERBOSE; then
1301         echo "CMD: $HOST $@" >&2
1302         $myPDSH $HOST $LCTL mark "$@" > /dev/null 2>&1 || :
1303     fi
1304
1305     if [ "$myPDSH" = "rsh" ]; then
1306 # we need this because rsh does not return exit code of an executed command
1307         local command_status="$TMP/cs"
1308         rsh $HOST ":> $command_status"
1309         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
1310                     cd $RPWD; sh -c \"$@\") ||
1311                     echo command failed >$command_status"
1312         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
1313         return 0
1314     fi
1315
1316     if $verbose ; then
1317         # print HOSTNAME for myPDSH="no_dsh"
1318         if [[ $myPDSH = no_dsh ]]; then
1319             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
1320         else
1321             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")"
1322         fi
1323     else
1324         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed "s/^${HOST}: //"
1325     fi
1326     return ${PIPESTATUS[0]}
1327 }
1328
1329 do_nodev() {
1330     do_node --verbose "$@"
1331 }
1332
1333 single_local_node () {
1334    [ "$1" = "$HOSTNAME" ]
1335 }
1336
1337 do_nodes() {
1338     local verbose=false
1339     # do not stripe off hostname if verbose, bug 19215
1340     if [ x$1 = x--verbose ]; then
1341         shift
1342         verbose=true
1343     fi
1344
1345     local rnodes=$1
1346     shift
1347
1348     if $(single_local_node $rnodes); then
1349         if $verbose; then
1350            do_nodev $rnodes "$@"
1351         else
1352            do_node $rnodes "$@"
1353         fi
1354         return $?
1355     fi
1356
1357     # This is part from do_node
1358     local myPDSH=$PDSH
1359
1360     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
1361         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
1362
1363     if $VERBOSE; then
1364         echo "CMD: $rnodes $@" >&2
1365         $myPDSH $rnodes $LCTL mark "$@" > /dev/null 2>&1 || :
1366     fi
1367
1368     if $verbose ; then
1369         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")"
1370     else
1371         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed -re "s/\w+:\s//g"
1372     fi
1373     return ${PIPESTATUS[0]}
1374 }
1375
1376 do_facet() {
1377     local facet=$1
1378     shift
1379     local HOST=`facet_active_host $facet`
1380     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
1381     do_node $HOST "$@"
1382 }
1383
1384 do_nodesv() {
1385     do_nodes --verbose "$@"
1386 }
1387
1388 add() {
1389     local facet=$1
1390     shift
1391     # make sure its not already running
1392     stop ${facet} -f
1393     rm -f $TMP/${facet}active
1394     do_facet ${facet} $MKFS $*
1395 }
1396
1397 ostdevname() {
1398     num=$1
1399     DEVNAME=OSTDEV$num
1400     #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
1401     eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}}
1402     echo -n $DEVPTR
1403 }
1404
1405 facet_mntpt() {
1406     local facet=$1
1407     if combined_mgs_mds && [[ $facet = "mgs" ]]  ; then
1408         facet="mds"
1409     fi
1410     local var=${facet}_MOUNT
1411     eval mntpt=${!var:-${MOUNT%/*}/$facet}
1412
1413     echo -n $mntpt
1414 }
1415
1416 ########
1417 ## MountConf setup
1418
1419 stopall() {
1420     # make sure we are using the primary server, so test-framework will
1421     # be able to clean up properly.
1422     activemds=`facet_active mds`
1423     if [ $activemds != "mds" ]; then
1424         fail mds
1425     fi
1426
1427     local clients=$CLIENTS
1428     [ -z $clients ] && clients=$(hostname)
1429
1430     zconf_umount_clients $clients $MOUNT "$*" || true
1431     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
1432
1433     [ "$CLIENTONLY" ] && return
1434     # The add fn does rm ${facet}active file, this would be enough
1435     # if we use do_facet <facet> only after the facet added, but
1436     # currently we use do_facet mds in local.sh
1437     stop mds -f
1438     rm -f ${TMP}/mdsactive
1439     for num in `seq $OSTCOUNT`; do
1440         stop ost$num -f
1441         rm -f $TMP/ost${num}active
1442     done
1443     if ! combined_mgs_mds ; then
1444         stop mgs 
1445     fi
1446
1447     return 0
1448 }
1449
1450 cleanupall() {
1451     nfs_client_mode && return
1452
1453     stopall $*
1454     unload_modules
1455 }
1456
1457 combined_mgs_mds () {
1458     [[ $MDSDEV = $MGSDEV ]] && [[ $mds_HOST = $mgs_HOST ]]
1459 }
1460
1461 formatall() {
1462     [ "$FSTYPE" ] && FSTYPE_OPT="--backfstype $FSTYPE"
1463
1464     stopall
1465     # We need ldiskfs here, may as well load them all
1466     load_modules
1467     [ "$CLIENTONLY" ] && return
1468     echo Formatting mgs, mds, osts
1469     if ! combined_mgs_mds ; then
1470         add mgs $mgs_MKFS_OPTS $FSTYPE_OPT --reformat $MGSDEV || exit 10
1471     fi
1472
1473     if $VERBOSE; then
1474         add mds $MDS_MKFS_OPTS $FSTYPE_OPT --reformat $MDSDEV || exit 10
1475     else
1476         add mds $MDS_MKFS_OPTS $FSTYPE_OPT --reformat $MDSDEV > /dev/null || exit 10
1477     fi
1478
1479     for num in `seq $OSTCOUNT`; do
1480         if $VERBOSE; then
1481             add ost$num $OST_MKFS_OPTS $FSTYPE_OPT --reformat `ostdevname $num` || exit 10
1482         else
1483             add ost$num $OST_MKFS_OPTS $FSTYPE_OPT --reformat `ostdevname $num` > /dev/null || exit 10
1484         fi
1485     done
1486 }
1487
1488 mount_client() {
1489     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
1490 }
1491
1492 remount_client()
1493 {
1494         zconf_umount `hostname` $1 || error "umount failed"
1495         zconf_mount `hostname` $1 || error "mount failed"
1496 }
1497
1498 writeconf_facet () {
1499     local facet=$1
1500     local dev=$2
1501
1502     do_facet $facet "$TUNEFS --writeconf $dev"
1503 }
1504
1505 writeconf_all () {
1506     writeconf_facet mds $MDSDEV
1507
1508     for num in `seq $OSTCOUNT`; do
1509         DEVNAME=`ostdevname $num`
1510         writeconf_facet ost$num $DEVNAME
1511     done
1512 }
1513
1514 setupall() {
1515     nfs_client_mode && return
1516
1517     sanity_mount_check ||
1518         error "environments are insane!"
1519
1520     load_modules
1521     if [ -z "$CLIENTONLY" ]; then
1522         echo Setup mgs, mdt, osts
1523
1524         echo $WRITECONF | grep -q "writeconf" && \
1525             writeconf_all
1526
1527         if ! combined_mgs_mds ; then
1528             start mgs $MGSDEV $mgs_MOUNT_OPTS
1529         fi
1530
1531         start mds $MDSDEV $MDS_MOUNT_OPTS
1532         # We started mds, now we should set failover variable properly.
1533         # Set mdsfailover_HOST if it is not set (the default failnode).
1534         if [ -z "$mdsfailover_HOST" ]; then
1535            mdsfailover_HOST=$(facet_host mds)
1536         fi
1537
1538         for num in `seq $OSTCOUNT`; do
1539             DEVNAME=`ostdevname $num`
1540             start ost$num $DEVNAME $OST_MOUNT_OPTS
1541
1542             # We started ost$num, now we should set ost${num}failover variable properly.
1543             # Set ost${num}failover_HOST if it is not set (the default failnode).
1544             varname=ost${num}failover_HOST
1545             if [ -z "${!varname}" ]; then
1546                 eval ost${num}failover_HOST=$(facet_host ost${num})
1547             fi
1548
1549         done
1550     fi
1551     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
1552     mount_client $MOUNT
1553     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
1554
1555     if [ "$MOUNT_2" ]; then
1556         mount_client $MOUNT2
1557         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
1558     fi
1559     sleep 5
1560     init_param_vars
1561 }
1562
1563 mounted_lustre_filesystems() {
1564         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
1565 }
1566
1567 init_facet_vars () {
1568     [ "$CLIENTONLY" ] && return 0
1569     local facet=$1
1570     shift
1571     local device=$1
1572
1573     shift
1574
1575     eval export ${facet}_dev=${device}
1576     eval export ${facet}_opt=\"$@\"
1577
1578     local dev=${facet}_dev
1579     local label=$(do_facet ${facet} "$E2LABEL ${!dev}")
1580     [ -z "$label" ] && echo no label for ${!dev} && exit 1
1581
1582     eval export ${facet}_svc=${label}
1583
1584     local varname=${facet}failover_HOST
1585     if [ -z "${!varname}" ]; then
1586        eval $varname=$(facet_host $facet)
1587     fi
1588
1589     # ${facet}failover_dev is set in cfg file
1590     varname=${facet}failover_dev
1591     if [ -n "${!varname}" ] ; then
1592         eval export ${facet}failover_dev=${!varname}
1593     else
1594         eval export ${facet}failover_dev=$device
1595     fi
1596
1597     # get mount point of already mounted device
1598     # is facet_dev is already mounted then use the real
1599     #  mount point of this facet; otherwise use $(facet_mntpt $facet)
1600     # i.e. ${facet}_MOUNT if specified by user or default 
1601     local mntpt=$(do_facet ${facet} cat /proc/mounts | \
1602             awk '"'${!dev}'" == $1 && $3 == "lustre" { print $2 }')
1603     if [ -z $mntpt ]; then
1604         mntpt=$(facet_mntpt $facet)
1605     fi
1606     eval export ${facet}_MOUNT=$mntpt
1607 }
1608
1609 init_facets_vars () {
1610     remote_mds_nodsh ||
1611         init_facet_vars mds $MDSDEV $MDS_MOUNT_OPTS
1612
1613     remote_ost_nodsh && return
1614
1615     for num in `seq $OSTCOUNT`; do
1616         DEVNAME=`ostdevname $num`
1617         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
1618     done
1619 }
1620
1621 init_param_vars () {
1622     if ! remote_ost_nodsh && ! remote_mds_nodsh; then
1623         export MDSVER=$(do_facet mds "lctl get_param version" | cut -d. -f1,2)
1624         export OSTVER=$(do_facet ost1 "lctl get_param version" | cut -d. -f1,2)
1625         export CLIVER=$(lctl get_param version | cut -d. -f 1,2)
1626     fi
1627
1628     remote_mds_nodsh ||
1629         TIMEOUT=$(do_facet mds "lctl get_param -n timeout")
1630
1631     log "Using TIMEOUT=$TIMEOUT"
1632
1633     if [ "$ENABLE_QUOTA" ]; then
1634         setup_quota $MOUNT  || return 2
1635     fi
1636 }
1637
1638 nfs_client_mode () {
1639     if [ "$NFSCLIENT" ]; then
1640         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
1641         local clients=$CLIENTS
1642         [ -z $clients ] && clients=$(hostname)
1643
1644         # FIXME: remove hostname when 19215 fixed
1645         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
1646         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
1647         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
1648         return
1649     fi
1650     return 1
1651 }
1652
1653 check_config_client () {
1654     local mntpt=$1
1655
1656     local mounted=$(mount | grep " $mntpt ")
1657     if [ "$CLIENTONLY" ]; then
1658         # bug 18021
1659         # CLIENTONLY should not depend on *_HOST settings
1660         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
1661         # in theory someone could create a new,
1662         # client-only config file that assumed lustre was already
1663         # configured and didn't set the MGSNID. If MGSNID is not set,
1664         # then we should use the mgs nid currently being used 
1665         # as the default value. bug 18021
1666         [[ x$MGSNID = x ]] &&
1667             MGSNID=${mgc//MGC/}
1668
1669         if [[ x$mgc != xMGC$MGSNID ]]; then
1670             if [ "$mgs_HOST" ]; then
1671                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
1672                 [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
1673                     error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
1674             fi
1675         fi
1676         return 0
1677     fi
1678
1679     local myMGS_host=$mgs_HOST
1680     if [ "$NETTYPE" = "ptl" ]; then
1681         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//)
1682     fi
1683
1684     echo Checking config lustre mounted on $mntpt
1685     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
1686     mgshost=$(echo $mgshost | awk -F: '{print $1}')
1687
1688 #    if [ "$mgshost" != "$myMGS_host" ]; then
1689 #            error_exit "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
1690 #                   Please use correct config or set mds_HOST correctly!"
1691 #    fi
1692
1693 }
1694
1695 check_config_clients () {
1696     local clients=${CLIENTS:-$HOSTNAME}
1697     local mntpt=$1
1698
1699     nfs_client_mode && return
1700
1701     do_rpc_nodes $clients check_config_client $mntpt
1702
1703     sanity_mount_check ||
1704         error "environments are insane!"
1705 }
1706
1707 check_timeout () {
1708     local mdstimeout=$(do_facet mds "lctl get_param -n timeout")
1709     local cltimeout=$(lctl get_param -n timeout)
1710     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
1711         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
1712         return 1
1713     fi
1714 }
1715
1716 is_mounted () {
1717     local mntpt=$1
1718     local mounted=$(mounted_lustre_filesystems)
1719
1720     echo $mounted' ' | grep -w -q $mntpt' '
1721 }
1722
1723 check_and_setup_lustre() {
1724     nfs_client_mode && return
1725
1726     local MOUNTED=$(mounted_lustre_filesystems)
1727
1728     local do_check=true
1729     # 1.
1730     # both MOUNT and MOUNT2 are not mounted
1731     if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
1732         [ "$REFORMAT" ] && formatall
1733         # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
1734         setupall
1735         is_mounted $MOUNT || error "NAME=$NAME not mounted"
1736         export I_MOUNTED=yes
1737         do_check=false
1738     # 2.
1739     # MOUNT2 is mounted
1740     elif is_mounted $MOUNT2; then
1741             # 3.
1742             # MOUNT2 is mounted, while MOUNT_2 is not set
1743             if ! [ "$MOUNT_2" ]; then
1744                 cleanup_mount $MOUNT2
1745                 export I_UMOUNTED2=yes
1746
1747             # 4.
1748             # MOUNT2 is mounted, MOUNT_2 is set
1749             else
1750                 # FIXME: what to do if check_config failed?
1751                 # i.e. if:
1752                 # 1) remote client has mounted other Lustre fs ?
1753                 # 2) it has insane env ?
1754                 # let's try umount MOUNT2 on all clients and mount it again:
1755                 if ! check_config_clients $MOUNT2; then
1756                     cleanup_mount $MOUNT2
1757                     restore_mount $MOUNT2
1758                     export I_MOUNTED2=yes
1759                 fi
1760             fi 
1761
1762     # 5.
1763     # MOUNT is mounted MOUNT2 is not mounted
1764     elif [ "$MOUNT_2" ]; then
1765         restore_mount $MOUNT2
1766         export I_MOUNTED2=yes
1767     fi
1768
1769     if $do_check; then
1770         # FIXME: what to do if check_config failed?
1771         # i.e. if:
1772         # 1) remote client has mounted other Lustre fs?
1773         # 2) lustre is mounted on remote_clients atall ?
1774         check_config_clients $MOUNT
1775         init_facets_vars
1776         init_param_vars
1777
1778         do_nodes $(comma_list $(nodes_list)) "lctl set_param debug=\\\"$PTLDEBUG\\\";
1779             lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
1780             lctl set_param debug_mb=${DEBUG_SIZE};
1781             sync"
1782     fi
1783     if [ "$ONLY" == "setup" ]; then
1784         exit 0
1785     fi
1786 }
1787
1788 restore_mount () {
1789    local clients=${CLIENTS:-$HOSTNAME}
1790    local mntpt=$1
1791
1792    zconf_mount_clients $clients $mntpt
1793 }
1794
1795 cleanup_mount () {
1796     local clients=${CLIENTS:-$HOSTNAME}
1797     local mntpt=$1
1798
1799     zconf_umount_clients $clients $mntpt    
1800 }
1801
1802 cleanup_and_setup_lustre() {
1803     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
1804         lctl set_param debug=0 || true
1805         cleanupall
1806         if [ "$ONLY" == "cleanup" ]; then
1807             exit 0
1808         fi
1809     fi
1810     check_and_setup_lustre
1811 }
1812
1813 check_and_cleanup_lustre() {
1814     if is_mounted $MOUNT; then
1815         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
1816         [ "$ENABLE_QUOTA" ] && restore_quota_type || true
1817     fi
1818
1819     if [ "$I_UMOUNTED2" = "yes" ]; then
1820         restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
1821     fi
1822
1823     if [ "$I_MOUNTED2" = "yes" ]; then
1824         cleanup_mount $MOUNT2
1825     fi
1826
1827     if [ "$I_MOUNTED" = "yes" ]; then
1828         cleanupall -f || error "cleanup failed"
1829         unset I_MOUNTED
1830     fi
1831 }
1832
1833 #######
1834 # General functions
1835
1836 check_network() {
1837     local NETWORK=0
1838     local WAIT=0
1839     local MAX=$2
1840     while [ $NETWORK -eq 0 ]; do
1841         if ping -c 1 -w 3 $1 > /dev/null; then
1842             NETWORK=1
1843         else
1844             WAIT=$((WAIT + 5))
1845             echo "waiting for $1, $((MAX - WAIT)) secs left"
1846             sleep 5
1847         fi
1848         if [ $WAIT -gt $MAX ]; then
1849             echo "Network not available"
1850             exit 1
1851         fi
1852     done
1853 }
1854 check_port() {
1855     while( !($DSH2 $1 "netstat -tna | grep -q $2") ) ; do
1856         sleep 9
1857     done
1858 }
1859
1860 no_dsh() {
1861     shift
1862     eval $@
1863 }
1864
1865 comma_list() {
1866     # the sed converts spaces to commas, but leaves the last space
1867     # alone, so the line doesn't end with a comma.
1868     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
1869 }
1870
1871 # list, excluded are the comma separated lists
1872 exclude_items_from_list () {
1873     local list=$1
1874     local excluded=$2
1875     local item
1876
1877     list=${list//,/ }
1878     for item in ${excluded//,/ }; do
1879         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
1880     done
1881     echo $(comma_list $list)
1882 }
1883
1884 # list, expand  are the comma separated lists
1885 expand_list () {
1886     local list=${1//,/ }
1887     local expand=${2//,/ }
1888     local expanded=
1889
1890     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
1891     echo $(comma_list $expanded)
1892 }
1893
1894 testslist_filter () {
1895     local script=$LUSTRE/tests/${TESTSUITE}.sh
1896
1897     [ -f $script ] || return 0
1898
1899     local start_at=$START_AT
1900     local stop_at=$STOP_AT
1901
1902     local var=${TESTSUITE//-/_}_START_AT
1903     [ x"${!var}" != x ] && start_at=${!var}
1904     var=${TESTSUITE//-/_}_STOP_AT
1905     [ x"${!var}" != x ] && stop_at=${!var}
1906
1907     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
1908         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
1909             /^'${start_at}'$/ {flag = 0}
1910             {if (flag == 1) print $0}
1911             /^'${stop_at}'$/ { flag = 1 }'
1912 }
1913
1914 absolute_path() {
1915     (cd `dirname $1`; echo $PWD/`basename $1`)
1916 }
1917
1918 get_facets () {
1919     local name=$(echo $1 | tr "[:upper:]" "[:lower:]")
1920     local type=$(echo $1 | tr "[:lower:]" "[:upper:]")
1921
1922     local list=""
1923
1924     case $type in
1925         MDS )    list=mds;;
1926         OST )    for ((i=1; i<=$OSTCOUNT; i++)) do
1927                     list="$list ${name}$i"
1928                  done;;
1929           * )    error "Invalid facet type"
1930                  exit 1;;
1931     esac
1932     echo $(comma_list $list)
1933 }
1934
1935 ##################################
1936 # Adaptive Timeouts funcs
1937
1938 at_is_enabled() {
1939     # only check mds, we assume at_max is the same on all nodes
1940     local at_max=$(do_facet mds "lctl get_param -n at_max")
1941     if [ $at_max -eq 0 ]; then
1942         return 1
1943     else
1944         return 0
1945     fi
1946 }
1947
1948 at_max_get() {
1949     local facet=$1
1950
1951     # suppose that all ost-s has the same at_max set
1952     if [ $facet == "ost" ]; then
1953         do_facet ost1 "lctl get_param -n at_max"
1954     else
1955         do_facet $facet "lctl get_param -n at_max"
1956     fi
1957 }
1958
1959 at_max_set() {
1960     local at_max=$1
1961     shift
1962
1963     local facet
1964     for facet in $@; do
1965         if [ $facet == "ost" ]; then
1966             for i in `seq $OSTCOUNT`; do
1967                 do_facet ost$i "lctl set_param at_max=$at_max"
1968             done
1969         else
1970             do_facet $facet "lctl set_param at_max=$at_max"
1971         fi
1972     done
1973 }
1974
1975 ##################################
1976 # OBD_FAIL funcs
1977
1978 drop_request() {
1979 # OBD_FAIL_MDS_ALL_REQUEST_NET
1980     RC=0
1981     do_facet mds lctl set_param fail_loc=0x123
1982     do_facet client "$1" || RC=$?
1983     do_facet mds lctl set_param fail_loc=0
1984     return $RC
1985 }
1986
1987 drop_reply() {
1988 # OBD_FAIL_MDS_ALL_REPLY_NET
1989     RC=0
1990     do_facet mds lctl set_param fail_loc=0x122
1991     do_facet client "$@" || RC=$?
1992     do_facet mds lctl set_param fail_loc=0
1993     return $RC
1994 }
1995
1996 drop_reint_reply() {
1997 # OBD_FAIL_MDS_REINT_NET_REP
1998     RC=0
1999     do_facet mds lctl set_param fail_loc=0x119
2000     do_facet client "$@" || RC=$?
2001     do_facet mds lctl set_param fail_loc=0
2002     return $RC
2003 }
2004
2005 pause_bulk() {
2006 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
2007     RC=0
2008     do_facet ost1 lctl set_param fail_loc=0x214
2009     do_facet client "$1" || RC=$?
2010     do_facet client "sync"
2011     do_facet ost1 lctl set_param fail_loc=0
2012     return $RC
2013 }
2014
2015 drop_ldlm_cancel() {
2016 #define OBD_FAIL_LDLM_CANCEL             0x304
2017     RC=0
2018     do_facet client lctl set_param fail_loc=0x304
2019     do_facet client "$@" || RC=$?
2020     do_facet client lctl set_param fail_loc=0
2021     return $RC
2022 }
2023
2024 drop_bl_callback() {
2025 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
2026     RC=0
2027     do_facet client lctl set_param fail_loc=0x305
2028     do_facet client "$@" || RC=$?
2029     do_facet client lctl set_param fail_loc=0
2030     return $RC
2031 }
2032
2033 drop_ldlm_reply() {
2034 #define OBD_FAIL_LDLM_REPLY              0x30c
2035     RC=0
2036     do_facet mds lctl set_param fail_loc=0x30c
2037     do_facet client "$@" || RC=$?
2038     do_facet mds lctl set_param fail_loc=0
2039     return $RC
2040 }
2041
2042 clear_failloc() {
2043     facet=$1
2044     pause=$2
2045     sleep $pause
2046     echo "clearing fail_loc on $facet"
2047     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
2048 }
2049
2050 set_nodes_failloc () {
2051     do_nodes $(comma_list $1)  lctl set_param fail_loc=$2
2052 }
2053
2054 cancel_lru_locks() {
2055     $LCTL mark "cancel_lru_locks $1 start"
2056     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
2057         $LCTL set_param -n $d=clear
2058     done
2059     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
2060     $LCTL mark "cancel_lru_locks $1 stop"
2061 }
2062
2063 default_lru_size()
2064 {
2065         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
2066         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
2067         echo "$DEFAULT_LRU_SIZE"
2068 }
2069
2070 lru_resize_enable()
2071 {
2072     lctl set_param ldlm.namespaces.*$1*.lru_size=0
2073 }
2074
2075 lru_resize_disable()
2076 {
2077     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
2078 }
2079
2080 pgcache_empty() {
2081     local FILE
2082     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
2083         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
2084             echo there is still data in page cache $FILE ?
2085             lctl get_param -n $FILE
2086             return 1
2087         fi
2088     done
2089     return 0
2090 }
2091
2092 create_fake_exports () {
2093     local facet=$1
2094     local num=$2
2095 #obd_fail_val = num;
2096 #define OBD_FAIL_TGT_FAKE_EXP 0x708
2097     do_facet $facet "lctl set_param fail_val=$num"
2098     do_facet $facet "lctl set_param fail_loc=0x80000708"
2099     fail $facet
2100 }
2101
2102 debugsave() {
2103     DEBUGSAVE="$(lctl get_param -n debug)"
2104 }
2105
2106 debugrestore() {
2107     [ -n "$DEBUGSAVE" ] && lctl set_param debug="${DEBUGSAVE}"
2108     DEBUGSAVE=""
2109 }
2110
2111 ##################################
2112 # Test interface
2113 ##################################
2114
2115 error_noexit() {
2116     local TYPE=${TYPE:-"FAIL"}
2117     local ERRLOG
2118
2119     local dump=true
2120     # do not dump logs if $1=false
2121     if [ "x$1" = "xfalse" ]; then
2122         shift
2123         dump=false
2124     fi
2125
2126     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
2127
2128     if $dump; then
2129         ERRLOG=$TMP/lustre_${TESTSUITE}_${TESTNAME}.$(date +%s)
2130         echo "Dumping lctl log to $ERRLOG"
2131         # We need to dump the logs on all nodes
2132         do_nodes $(comma_list $(nodes_list)) $NODE $LCTL dk $ERRLOG
2133     fi
2134     debugrestore
2135     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
2136     TEST_FAILED=true
2137 }
2138
2139 error() {
2140     error_noexit "$@"
2141     if $FAIL_ON_ERROR;  then
2142         reset_fail_loc
2143         exit 1
2144     fi
2145 }
2146
2147 error_exit() {
2148     error_noexit "$@"
2149     exit 1
2150 }
2151
2152 # use only if we are ignoring failures for this test, bugno required.
2153 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
2154 # e.g. error_ignore 5494 "your message"
2155 error_ignore() {
2156     local TYPE="IGNORE (bz$1)"
2157     shift
2158     error_noexit "$@"
2159 }
2160
2161 skip_env () {
2162     $FAIL_ON_SKIP_ENV && error false $@ || skip $@
2163 }
2164
2165 skip () {
2166         log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
2167         [ "$TESTSUITELOG" ] && \
2168                 echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
2169 }
2170
2171 build_test_filter() {
2172     EXCEPT="$EXCEPT $(testslist_filter)"
2173
2174     [ "$ONLY" ] && log "only running test `echo $ONLY`"
2175     for O in $ONLY; do
2176         eval ONLY_${O}=true
2177     done
2178     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
2179         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
2180     [ "$EXCEPT_SLOW" ] && \
2181         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
2182     for E in $EXCEPT $ALWAYS_EXCEPT; do
2183         eval EXCEPT_${E}=true
2184     done
2185     for E in $EXCEPT_SLOW; do
2186         eval EXCEPT_SLOW_${E}=true
2187     done
2188     for G in $GRANT_CHECK_LIST; do
2189         eval GCHECK_ONLY_${G}=true
2190         done
2191 }
2192
2193 basetest() {
2194     if [[ $1 = [a-z]* ]]; then
2195         echo $1
2196     else
2197         echo ${1%%[a-z]*}
2198     fi
2199 }
2200
2201 # print a newline if the last test was skipped
2202 export LAST_SKIPPED=
2203 run_test() {
2204     assert_DIR
2205
2206     export base=`basetest $1`
2207     if [ ! -z "$ONLY" ]; then
2208         testname=ONLY_$1
2209         if [ ${!testname}x != x ]; then
2210             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2211             run_one $1 "$2"
2212             return $?
2213         fi
2214         testname=ONLY_$base
2215         if [ ${!testname}x != x ]; then
2216             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2217             run_one $1 "$2"
2218             return $?
2219         fi
2220         LAST_SKIPPED="y"
2221         echo -n "."
2222         return 0
2223     fi
2224     testname=EXCEPT_$1
2225     if [ ${!testname}x != x ]; then
2226         LAST_SKIPPED="y"
2227         TESTNAME=test_$1 skip "skipping excluded test $1"
2228         return 0
2229     fi
2230     testname=EXCEPT_$base
2231     if [ ${!testname}x != x ]; then
2232         LAST_SKIPPED="y"
2233         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
2234         return 0
2235     fi
2236     testname=EXCEPT_SLOW_$1
2237     if [ ${!testname}x != x ]; then
2238         LAST_SKIPPED="y"
2239         TESTNAME=test_$1 skip "skipping SLOW test $1"
2240         return 0
2241     fi
2242     testname=EXCEPT_SLOW_$base
2243     if [ ${!testname}x != x ]; then
2244         LAST_SKIPPED="y"
2245         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
2246         return 0
2247     fi
2248
2249     LAST_SKIPPED=
2250     run_one $1 "$2"
2251
2252     return $?
2253 }
2254
2255 EQUALS="======================================================================"
2256 equals_msg() {
2257     msg="$@"
2258
2259     local suffixlen=$((${#EQUALS} - ${#msg}))
2260     [ $suffixlen -lt 5 ] && suffixlen=5
2261     log `echo $(printf '===== %s %.*s\n' "$msg" $suffixlen $EQUALS)`
2262 }
2263
2264 log() {
2265     echo "$*"
2266     module_loaded lnet || load_modules
2267
2268     local MSG="$*"
2269     # Get rid of '
2270     MSG=${MSG//\'/\\\'}
2271     MSG=${MSG//\(/\\\(}
2272     MSG=${MSG//\)/\\\)}
2273     MSG=${MSG//\;/\\\;}
2274     MSG=${MSG//\|/\\\|}
2275     MSG=${MSG//\>/\\\>}
2276     MSG=${MSG//\</\\\<}
2277     MSG=${MSG//\//\\\/}
2278     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
2279 }
2280
2281 trace() {
2282         log "STARTING: $*"
2283         strace -o $TMP/$1.strace -ttt $*
2284         RC=$?
2285         log "FINISHED: $*: rc $RC"
2286         return 1
2287 }
2288
2289 pass() {
2290     $TEST_FAILED && echo -n "FAIL " || echo -n "PASS "
2291     echo $@
2292 }
2293
2294 check_mds() {
2295     FFREE=`lctl get_param -n mds.*.filesfree`
2296     FTOTAL=`lctl get_param -n mds.*.filestotal`
2297     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
2298 }
2299
2300 reset_fail_loc () {
2301     echo -n "Resetting fail_loc on all nodes..."
2302     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
2303     echo done.
2304 }
2305
2306 run_one() {
2307     testnum=$1
2308     message=$2
2309     tfile=f${testnum}
2310     export tdir=d0.${TESTSUITE}/d${base}
2311
2312     local SAVE_UMASK=`umask`
2313     umask 0022
2314
2315     local BEFORE=`date +%s`
2316     echo
2317     log "== test $testnum: $message == `date +%H:%M:%S` ($BEFORE)"
2318     #check_mds
2319     export TESTNAME=test_$testnum
2320     TEST_FAILED=false
2321     test_${testnum} || error "test_$testnum failed with $?"
2322     #check_mds
2323     cd $SAVE_PWD
2324     reset_fail_loc
2325     check_grant ${testnum} || error "check_grant $testnum failed with $?"
2326     check_catastrophe || error "LBUG/LASSERT detected"
2327     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
2328     pass "($((`date +%s` - $BEFORE))s)"
2329     TEST_FAILED=false
2330     unset TESTNAME
2331     unset tdir
2332     umask $SAVE_UMASK
2333 }
2334
2335 canonical_path() {
2336     (cd `dirname $1`; echo $PWD/`basename $1`)
2337 }
2338
2339 sync_clients() {
2340     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
2341     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
2342         cd $SAVE_PWD
2343 }
2344
2345 check_grant() {
2346     export base=`basetest $1`
2347     [ "$CHECK_GRANT" == "no" ] && return 0
2348
2349         testname=GCHECK_ONLY_${base}
2350     [ ${!testname}x == x ] && return 0
2351
2352     echo -n "checking grant......"
2353         cd $SAVE_PWD
2354         # write some data to sync client lost_grant
2355         rm -f $DIR1/${tfile}_check_grant_* 2>&1
2356         for i in `seq $OSTCOUNT`; do
2357                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
2358                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
2359                                               count=1 > /dev/null 2>&1
2360         done
2361     # sync all the data and make sure no pending data on server
2362     sync_clients
2363
2364     #get client grant and server grant
2365     client_grant=0
2366     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
2367         client_grant=$((client_grant + $d))
2368     done
2369     server_grant=0
2370     for d in `lctl get_param -n obdfilter.*.tot_granted`; do
2371         server_grant=$((server_grant + $d))
2372     done
2373
2374         # cleanup the check_grant file
2375         for i in `seq $OSTCOUNT`; do
2376                 rm $DIR1/${tfile}_check_grant_$i
2377         done
2378
2379         #check whether client grant == server grant
2380         if [ $client_grant != $server_grant ]; then
2381                 echo "failed: client:${client_grant} server: ${server_grant}"
2382                 return 1
2383         else
2384                 echo "pass"
2385         fi
2386 }
2387
2388 ########################
2389 # helper functions
2390
2391 osc_to_ost()
2392 {
2393     osc=$1
2394     ost=`echo $1 | awk -F_ '{print $3}'`
2395     if [ -z $ost ]; then
2396         ost=`echo $1 | sed 's/-osc.*//'`
2397     fi
2398     echo $ost
2399 }
2400
2401 remote_node () {
2402     local node=$1
2403     [ "$node" != "$(hostname)" ]
2404 }
2405
2406 remote_mds ()
2407 {
2408     remote_node $mds_HOST
2409 }
2410
2411 remote_mds_nodsh()
2412 {
2413     [ "$CLIENTONLY" ] && return 0 || true
2414     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
2415 }
2416
2417 remote_ost ()
2418 {
2419     local node
2420     for node in $(osts_nodes) ; do
2421         remote_node $node && return 0
2422     done
2423     return 1
2424 }
2425
2426 remote_ost_nodsh()
2427 {
2428     [ "$CLIENTONLY" ] && return 0 || true 
2429     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2430 }
2431
2432 remote_mgs_nodsh()
2433 {
2434     local MGS
2435     MGS=$(facet_host mgs)
2436     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2437 }
2438
2439 remote_servers () {
2440     remote_ost && remote_mds
2441 }
2442
2443 local_mode ()
2444 {
2445     remote_mds_nodsh || remote_ost_nodsh || \
2446         $(single_local_node $(comma_list $(nodes_list)))
2447 }
2448
2449 osts_nodes () {
2450     local OSTNODES=$(facet_host ost1)
2451     local NODES_sort
2452
2453     for num in `seq $OSTCOUNT`; do
2454         local myOST=$(facet_host ost$num)
2455         OSTNODES="$OSTNODES $myOST"
2456     done
2457     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
2458
2459     echo $NODES_sort
2460 }
2461
2462 nodes_list () {
2463     # FIXME. We need a list of clients
2464     local myNODES=$HOSTNAME
2465     local myNODES_sort
2466
2467     # CLIENTS (if specified) contains the local client
2468     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
2469
2470     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
2471         myNODES="$myNODES $(osts_nodes) $mds_HOST"
2472     fi
2473
2474     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
2475
2476     echo $myNODES_sort
2477 }
2478
2479 remote_nodes_list () {
2480     local rnodes=$(nodes_list)
2481     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2482     echo $rnodes
2483 }
2484
2485 init_clients_lists () {
2486     # Sanity check: exclude the local client from RCLIENTS
2487     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2488
2489     # Sanity check: exclude the dup entries
2490     rclients=$(for i in $rclients; do echo $i; done | sort -u)
2491
2492     local clients="$SINGLECLIENT $HOSTNAME $rclients"
2493
2494     # Sanity check: exclude the dup entries from CLIENTS
2495     # for those configs which has SINGLCLIENT set to local client
2496     clients=$(for i in $clients; do echo $i; done | sort -u)
2497
2498     CLIENTS=`comma_list $clients`
2499     local -a remoteclients=($rclients)
2500     for ((i=0; $i<${#remoteclients[@]}; i++)); do
2501             varname=CLIENT$((i + 2))
2502             eval $varname=${remoteclients[i]}
2503     done
2504
2505     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
2506 }
2507
2508 get_random_entry () {
2509     local rnodes=$1
2510
2511     rnodes=${rnodes//,/ }
2512
2513     local -a nodes=($rnodes)
2514     local num=${#nodes[@]}
2515     local i=$((RANDOM * num * 2 / 65536))
2516
2517     echo ${nodes[i]}
2518 }
2519
2520 client_only () {
2521     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
2522 }
2523
2524 is_patchless ()
2525 {
2526     lctl get_param version | grep -q patchless
2527 }
2528
2529 check_versions () {
2530     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
2531 }
2532
2533 get_node_count() {
2534     local nodes="$@"
2535     echo $nodes | wc -w || true
2536 }
2537
2538 mixed_ost_devs () {
2539     local nodes=$(osts_nodes)
2540     local osscount=$(get_node_count "$nodes")
2541     [ ! "$OSTCOUNT" = "$osscount" ]
2542 }
2543
2544 generate_machine_file() {
2545     local nodes=${1//,/ }
2546     local machinefile=$2
2547     rm -f $machinefile
2548     for node in $nodes; do
2549         echo $node >>$machinefile || \
2550             { echo "can not generate machinefile $machinefile" && return 1; }
2551     done
2552 }
2553
2554 get_stripe () {
2555     local file=$1/stripe
2556     touch $file
2557     $LFS getstripe -v $file || error
2558     rm -f $file
2559 }
2560
2561 setstripe_nfsserver () {
2562     local dir=$1
2563
2564     local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
2565                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -1)
2566
2567     [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
2568
2569     do_nodev $nfsserver lfs setstripe "$@"
2570 }
2571
2572 check_runas_id_ret() {
2573     local myRC=0
2574     local myRUNAS_UID=$1
2575     local myRUNAS_GID=$2
2576     shift 2
2577     local myRUNAS=$@
2578     if [ -z "$myRUNAS" ]; then
2579         error_exit "myRUNAS command must be specified for check_runas_id"
2580     fi
2581     mkdir $DIR/d0_runas_test
2582     chmod 0755 $DIR
2583     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
2584     if ! $myRUNAS touch $DIR/d0_runas_test/f$$ ; then
2585         do_nodesv $(comma_list $(nodes_list)) grep -w $myRUNAS_UID /etc/passwd
2586         myRC=1
2587     fi
2588     rm -rf $DIR/d0_runas_test
2589     return $myRC
2590 }
2591
2592 check_runas_id() {
2593     local myRUNAS_UID=$1
2594     local myRUNAS_GID=$2
2595     shift 2
2596     local myRUNAS=$@
2597     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
2598         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
2599         Please set RUNAS_ID to some UID which exists on MDS and client or
2600         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
2601 }
2602
2603 # Run multiop in the background, but wait for it to print
2604 # "PAUSING" to its stdout before returning from this function.
2605 multiop_bg_pause() {
2606     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
2607     FILE=$1
2608     ARGS=$2
2609
2610     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
2611     mkfifo $TMPPIPE
2612
2613     echo "$MULTIOP_PROG $FILE v$ARGS"
2614     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
2615
2616     echo "TMPPIPE=${TMPPIPE}"
2617     local multiop_output
2618
2619     read -t 60 multiop_output < $TMPPIPE
2620     if [ $? -ne 0 ]; then
2621         rm -f $TMPPIPE
2622         return 1
2623     fi
2624     rm -f $TMPPIPE
2625     if [ "$multiop_output" != "PAUSING" ]; then
2626         echo "Incorrect multiop output: $multiop_output"
2627         kill -9 $PID
2628         return 1
2629     fi
2630
2631     return 0
2632 }
2633
2634 do_and_time () {
2635     local cmd=$1
2636     local rc
2637
2638     SECONDS=0
2639     eval '$cmd'
2640     
2641     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
2642
2643     echo $SECONDS
2644     return $rc
2645 }
2646
2647 inodes_available () {
2648     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
2649     echo $IFree
2650 }
2651
2652 # reset llite stat counters
2653 clear_llite_stats(){
2654         lctl set_param -n llite.*.stats 0
2655 }
2656
2657 # sum llite stat items
2658 calc_llite_stats() {
2659         local res=$(lctl get_param -n llite.*.stats |
2660                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
2661         echo $res
2662 }
2663
2664 calc_sum () {
2665         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
2666 }
2667
2668 calc_osc_kbytes () {
2669         df $MOUNT > /dev/null
2670         $LCTL get_param -n osc.*[oO][sS][cC][-_]*.$1 | calc_sum
2671 }
2672
2673 # save_lustre_params(node, parameter_mask)
2674 # generate a stream of formatted strings (<node> <param name>=<param value>)
2675 save_lustre_params() {
2676         local s
2677         do_nodesv $1 "lctl get_param $2 | while read s; do echo \\\$s; done"
2678 }
2679
2680 # restore lustre parameters from input stream, produces by save_lustre_params
2681 restore_lustre_params() {
2682         local node
2683         local name
2684         local val
2685         while IFS=" =" read node name val; do
2686                 do_node ${node//:/} "lctl set_param -n $name $val"
2687         done
2688 }
2689
2690 check_catastrophe() {
2691     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
2692     local C=$CATASTROPHE
2693     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
2694
2695     if [ $rnodes ]; then
2696         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
2697 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
2698 exit \\\$rc;"
2699     fi
2700 }
2701
2702 # $1 node
2703 # $2 file
2704 # $3 $RUNAS
2705 get_stripe_info() {
2706         local tmp_file
2707
2708         stripe_size=0
2709         stripe_count=0
2710         stripe_index=0
2711         tmp_file=$(mktemp)
2712
2713         do_facet $1 $3 lfs getstripe -v $2 > $tmp_file
2714
2715         stripe_size=`awk '$1 ~ /size/ {print $2}' $tmp_file`
2716         stripe_count=`awk '$1 ~ /count/ {print $2}' $tmp_file`
2717         stripe_index=`awk '$1 ~ /stripe_offset/ {print $2}' $tmp_file`
2718         rm -f $tmp_file
2719 }
2720
2721 mdsrate_cleanup () {
2722     mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
2723 }
2724
2725 delayed_recovery_enabled () {
2726     do_facet mds "lctl get_param -n mds.${mds_svc}.stale_export_age" > /dev/null 2>&1
2727 }
2728
2729 ################################################################################
2730 # The following functions are used to enable interop testing between
2731 # 1.8 and 2.0. The lprocfs layout changed from 1.8 to 2.0 as the followings:
2732 # mds -> mdt
2733 # {blocksize filesfree filestotal fstype kbytesavail kbytesfree kbytestotal mntdev} moved from mds to osd
2734 # mdt lov: fsname-mdtlov -> fsname-MDTXXXX-mdtlov
2735 # mdt osc: fsname-OSTXXXX-osc -> fsname-OSTXXXX-osc-MDTXXXX
2736 ################################################################################
2737
2738 get_lustre_version () {
2739     local node=${1:-"mds"}
2740     do_facet $node $LCTL get_param -n version |  awk '/^lustre:/ {print $2}'
2741 }
2742
2743 get_mds_version_major () {
2744     local version=$(get_lustre_version mds)
2745     echo $version | awk -F. '{print $1}'
2746 }
2747
2748 get_mds_version_minor () {
2749     local version=$(get_lustre_version mds)
2750     echo $version | awk -F. '{print $2}'
2751 }
2752
2753 get_mds_version_patch () {
2754     local version=$(get_lustre_version mds)
2755     echo $version | awk -F. '{print $3}'
2756 }
2757
2758 get_mds_version_fix () {
2759     local version=$(get_lustre_version mds)
2760     echo $version | awk -F. '{print $4}'
2761 }
2762
2763 get_mds_fsstat_proc_path() {
2764     local major=$(get_mds_version_major)
2765     local minor=$(get_mds_version_minor)
2766     if [ $major -le 1 -a $minor -le 8 ] ; then
2767         echo "mds"
2768     else
2769         echo "osd"
2770     fi
2771 }
2772
2773 get_mds_mntdev_proc_path() {
2774     local fsstat_dev=$(get_mds_fsstat_proc_path)
2775     echo "$fsstat_dev.*.mntdev"
2776 }
2777
2778 get_mdtlov_proc_path() {
2779     local fsname=$1
2780     local major=$(get_mds_version_major)
2781     local minor=$(get_mds_version_minor)
2782     if [ $major -le 1 -a $minor -le 8 ] ; then
2783         echo "${fsname}-mdtlov"
2784     else
2785         echo "${fsname}-MDT0000-mdtlov"
2786     fi
2787 }
2788
2789 get_mdtosc_proc_path() {
2790     local ost=$1
2791     local major=$(get_mds_version_major)
2792     local minor=$(get_mds_version_minor)
2793     if [ $major -le 1 -a $minor -le 8 ] ; then
2794         echo "${ost}-osc"
2795     else
2796         echo "${ost}-osc-MDT0000"
2797     fi
2798 }
2799
2800 get_mds_mdt_device_proc_path() {
2801     local major=$(get_mds_version_major)
2802     local minor=$(get_mds_version_minor)
2803     if [ $major -le 1 -a $minor -le 8 ] ; then
2804         echo "mds"
2805     else
2806         echo "mdt"
2807     fi
2808 }
2809
2810 get_md_name () {
2811     local major=$(get_mds_version_major)
2812     local minor=$(get_mds_version_minor)
2813     if [ $major -le 1 -a $minor -le 8 ] ; then
2814         echo "mdt"
2815     else
2816         echo "mdd"
2817     fi
2818 }
2819
2820 ########################
2821
2822 convert_facet2label() { 
2823     local facet=$1
2824
2825     if [ x$facet = xost ]; then
2826        facet=ost1
2827     fi
2828
2829     local varsvc=${facet}_svc
2830
2831     if [ -n ${!varsvc} ]; then
2832         echo ${!varsvc}
2833     else  
2834         error "No lablel for $facet!"
2835     fi
2836 }
2837
2838 get_clientosc_proc_path() {
2839     local ost=$1
2840
2841     echo "{$1}-osc-*"
2842 }
2843
2844 get_osc_import_name() {
2845     local facet=$1
2846     local ost=$2
2847     local label=$(convert_facet2label $ost)
2848
2849     if [ "$facet" == "mds" ]; then
2850         get_mdtosc_proc_path $label
2851         return 0
2852     fi
2853
2854     get_clientosc_proc_path $label
2855     return 0
2856 }
2857
2858 wait_import_state () {
2859     local expected=$1
2860     local CONN_PROC=$2
2861     local CONN_STATE
2862     local i=0
2863
2864     CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
2865     while [ "${CONN_STATE}" != "${expected}" ]; do
2866         if [ "${expected}" == "DISCONN" ]; then
2867             # for disconn we can check after proc entry is removed
2868             [ "x${CONN_STATE}" == "x" ] && return 0
2869             #  with AT we can have connect request timeout ~ reconnect timeout
2870             # and test can't see real disconnect
2871             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
2872         fi
2873         # disconnect rpc should be wait not more obd_timeout
2874         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
2875             error "can't put import for $CONN_PROC into ${expected} state" && return 1
2876         sleep 1
2877         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
2878         i=$(($i + 1))
2879     done
2880
2881     log "$CONN_PROC now in ${CONN_STATE} state"
2882     return 0
2883 }
2884
2885 wait_osc_import_state() {
2886     local facet=$1
2887     local ost_facet=$2
2888     local expected=$3
2889     local ost=$(get_osc_import_name $facet $ost_facet)
2890     local CONN_PROC
2891     local CONN_STATE
2892     local i=0
2893
2894     CONN_PROC="osc.${ost}.ost_server_uuid"
2895     CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
2896     while [ "${CONN_STATE}" != "${expected}" ]; do
2897         if [ "${expected}" == "DISCONN" ]; then 
2898             # for disconn we can check after proc entry is removed
2899             [ "x${CONN_STATE}" == "x" ] && return 0
2900             #  with AT enabled, we can have connect request timeout near of 
2901             # reconnect timeout and test can't see real disconnect
2902             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
2903         fi
2904         # disconnect rpc should be wait not more obd_timeout
2905         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
2906             error "can't put import for ${ost}(${ost_facet}) into ${expected} state" && return 1
2907         sleep 1
2908         CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC | cut -f2)
2909         i=$(($i + 1))
2910     done
2911
2912     log "${ost_facet} now in ${CONN_STATE} state"
2913     return 0
2914 }
2915
2916 get_clientmdc_proc_path() {
2917     echo "${1}-mdc-*"
2918 }
2919
2920 do_rpc_nodes () {
2921     local list=$1
2922     shift
2923
2924     do_nodesv $list "PATH=$LUSTRE/tests/:$PATH sh rpc.sh $@ " 
2925 }
2926
2927 wait_clients_import_state () {
2928     local list=$1
2929     local facet=$2
2930     local expected=$3
2931     shift
2932
2933     local label=$(convert_facet2label $facet)
2934     local proc_path
2935     case $facet in
2936         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
2937         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
2938         *) error "unknown facet!" ;;
2939     esac
2940
2941     if ! do_rpc_nodes $list wait_import_state $expected $proc_path; then
2942         error "import is not in ${expected} state"
2943         return 1
2944     fi
2945 }
2946
2947 destroy_pool_int() {
2948     local ost
2949     local OSTS=$(do_facet mds lctl pool_list $1 | awk '$1 !~ /^Pool:/ {print $1}')
2950     for ost in $OSTS; do
2951         do_facet mgs lctl pool_remove $1 $ost
2952     done
2953     do_facet mgs lctl pool_destroy $1
2954 }
2955
2956 # <fsname>.<poolname> or <poolname>
2957 destroy_pool() {
2958     local fsname=${1%%.*}
2959     local poolname=${1##$fsname.}
2960
2961     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
2962
2963     local RC
2964
2965     pool_list $fsname.$poolname || return $?
2966
2967     destroy_pool_int $fsname.$poolname
2968     RC=$?
2969     [[ $RC -ne 0 ]] && return $RC
2970
2971     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
2972       2>/dev/null || echo foo" "foo" || RC=1
2973
2974     if [[ $RC -eq 0 ]]; then
2975         remove_pool_from_list $fsname.$poolname
2976     else
2977         error "destroy pool failed $1"
2978     fi
2979     return $RC
2980 }
2981
2982 destroy_pools () {
2983     local fsname=${1:-$FSNAME}
2984     local poolname
2985     local listvar=${fsname}_CREATED_POOLS
2986
2987     pool_list $fsname
2988
2989     [ x${!listvar} = x ] && return 0
2990
2991     echo destroy the created pools: ${!listvar}
2992     for poolname in ${!listvar//,/ }; do
2993         destroy_pool $fsname.$poolname
2994     done
2995 }
2996
2997 cleanup_pools () {
2998     local fsname=${1:-$FSNAME}
2999     trap 0
3000     destroy_pools $fsname
3001 }
3002
3003 gather_logs () {
3004     local list=$1
3005
3006     local ts=$(date +%s)
3007
3008     # bug 20237, comment 11
3009     # It would also be useful to provide the option
3010     # of writing the file to an NFS directory so it doesn't need to be copied.
3011     local tmp=$TMP
3012     local docp=true
3013     [ -d "$SHARED_DIR_LOGS" ] && tmp=$SHARED_DIR_LOGS && docp=false
3014
3015     # dump lustre logs, dmesg
3016     do_nodes $list "log=$tmp/\\\$(hostname)-debug-$ts.log ;
3017 lctl dk \\\$log >/dev/null;
3018 log=$tmp/\\\$(hostname)-dmesg-$ts.log;
3019 dmesg > \\\$log; "
3020
3021     # FIXME: does it make sense to collect the logs for $ts only, but all
3022     # TESTSUITE logs?
3023     # rsync $TMP/*${TESTSUITE}* to gather the logs dumped by error fn
3024     local logs=$TMP/'*'${TESTSUITE}'*'
3025     if $docp; then
3026         logs=$logs' '$tmp/'*'$ts'*'
3027     fi
3028     for node in ${list//,/ }; do
3029         rsync -az $node:"$logs" $TMP
3030     done
3031
3032     local archive=$TMP/${TESTSUITE}-$ts.tar.bz2
3033     tar -jcf $archive $tmp/*$ts* $TMP/*${TESTSUITE}*
3034
3035     echo $archive
3036 }
3037
3038 cleanup_logs () {
3039     local list=${1:-$(comma_list $(nodes_list))}
3040
3041     [ -n ${TESTSUITE} ] && do_nodes $list "rm -f $TMP/*${TESTSUITE}*" || true
3042 }
3043
3044 do_ls () {
3045     local mntpt_root=$1
3046     local num_mntpts=$2
3047     local dir=$3
3048     local i
3049     local cmd
3050     local pids
3051     local rc=0
3052
3053     for i in $(seq 0 $num_mntpts); do
3054         cmd="ls -laf ${mntpt_root}$i/$dir"
3055         echo + $cmd;
3056         $cmd > /dev/null &
3057         pids="$pids $!"
3058     done
3059     echo pids=$pids
3060     for pid in $pids; do
3061         wait $pid || rc=$?
3062     done
3063
3064     return $rc
3065 }
3066
3067 # target_start_and_reset_recovery_timer()
3068 #        service_time = at_est2timeout(service_time);
3069 #        service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC +
3070 #                             INITIAL_CONNECT_TIMEOUT);
3071 # CONNECTION_SWITCH_MAX : min(25U, max(CONNECTION_SWITCH_MIN,obd_timeout))
3072 #define CONNECTION_SWITCH_INC 1
3073 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
3074 #define CONNECTION_SWITCH_MIN 5U
3075
3076 max_recovery_time () {
3077     local init_connect_timeout=$(( TIMEOUT / 20 ))
3078     [[ $init_connect_timeout > 5 ]] || init_connect_timeout=5 
3079
3080     local service_time=$(( $(at_max_get client) + $(( 2 * $(( 25 + 1  + init_connect_timeout)) )) ))
3081
3082     echo $service_time 
3083 }