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