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