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