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