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