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