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