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