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