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