Whamcloud - gitweb
10f6f1f3a4882de3a115b9a587e80cbe157735ac
[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;
838 for prog in $progs; do
839     if ! [ \\\"\\\$(which \\\$prog)\\\"  -o  \\\"\\\${!prog}\\\" ]; then
840        echo \\\$prog missing on \\\$(hostname);
841        status=false;
842     fi
843 done;
844 eval \\\$status"
845 }
846
847 client_var_name() {
848     echo __$(echo $1 | tr '-' 'X')
849 }
850
851 start_client_load() {
852     local client=$1
853     local load=$2
854     local var=$(client_var_name $client)_load
855     eval export ${var}=$load
856
857     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
858                               BREAK_ON_ERROR=$BREAK_ON_ERROR \
859                               END_RUN_FILE=$END_RUN_FILE \
860                               LOAD_PID_FILE=$LOAD_PID_FILE \
861                               TESTSUITELOG=$TESTSUITELOG \
862                               run_${load}.sh" &
863     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $!"
864     log "Started client load: ${load} on $client"
865
866     return 0
867 }
868
869 start_client_loads () {
870     local -a clients=(${1//,/ })
871     local numloads=${#CLIENT_LOADS[@]}
872     local testnum
873
874     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
875         testnum=$((nodenum % numloads))
876         start_client_load ${clients[nodenum]} ${CLIENT_LOADS[testnum]}
877     done
878 }
879
880 # only for remote client 
881 check_client_load () {
882     local client=$1
883     local var=$(client_var_name $client)_load
884     local TESTLOAD=run_${!var}.sh
885
886     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
887     
888     # bug 18914: try to connect several times not only when
889     # check ps, but  while check_catastrophe also
890     local tries=3
891     local RC=254
892     while [ $RC = 254 -a $tries -gt 0 ]; do
893         let tries=$tries-1
894         # assume success
895         RC=0
896         if ! check_catastrophe $client; then
897             RC=${PIPESTATUS[0]}
898             if [ $RC -eq 254 ]; then
899                 # FIXME: not sure how long we shuold sleep here
900                 sleep 10
901                 continue
902             fi
903             echo "check catastrophe failed: RC=$RC "
904             return $RC
905         fi
906     done
907     # We can continue try to connect if RC=254
908     # Just print the warning about this
909     if [ $RC = 254 ]; then
910         echo "got a return status of $RC from do_node while checking catastrophe on $client"
911     fi
912
913     # see if the load is still on the client
914     tries=3
915     RC=254
916     while [ $RC = 254 -a $tries -gt 0 ]; do
917         let tries=$tries-1
918         # assume success
919         RC=0
920         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
921             RC=${PIPESTATUS[0]}
922             sleep 30
923         fi
924     done
925     if [ $RC = 254 ]; then
926         echo "got a return status of $RC from do_node while checking (catastrophe and 'ps') the client load on $client"
927         # see if we can diagnose a bit why this is
928     fi
929
930     return $RC
931 }
932 check_client_loads () {
933    local clients=${1//,/ }
934    local client=
935    local rc=0
936
937    for client in $clients; do
938       check_client_load $client
939       rc=${PIPESTATUS[0]}
940       if [ "$rc" != 0 ]; then
941         log "Client load failed on node $client, rc=$rc"
942         return $rc
943       fi
944    done
945 }
946
947 restart_client_loads () {
948     local clients=${1//,/ }
949     local expectedfail=${2:-""}
950     local client=
951     local rc=0
952
953     for client in $clients; do
954         check_client_load $client
955         rc=${PIPESTATUS[0]}
956         if [ "$rc" != 0 -a "$expectedfail" ]; then
957             start_client_load $client
958             echo "Restarted client load: on $client. Checking ..."
959             check_client_load $client 
960             rc=${PIPESTATUS[0]}
961             if [ "$rc" != 0 ]; then
962                 log "Client load failed to restart on node $client, rc=$rc"
963                 # failure one client load means test fail
964                 # we do not need to check other 
965                 return $rc
966             fi
967         else
968             return $rc
969         fi
970     done
971 }
972 # End recovery-scale functions
973
974 # verify that lustre actually cleaned up properly
975 cleanup_check() {
976     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
977         error "LBUG/LASSERT detected"
978     BUSY=`dmesg | grep -i destruct || true`
979     if [ "$BUSY" ]; then
980         echo "$BUSY" 1>&2
981         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
982         exit 205
983     fi
984
985     check_mem_leak || exit 204
986
987     [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl && \
988         echo "$0: lustre didn't clean up..." 1>&2 && return 202 || true
989
990     if [ "`/sbin/lsmod 2>&1 | egrep 'lnet|libcfs'`" ]; then
991         echo "$0: modules still loaded..." 1>&2
992         /sbin/lsmod 1>&2
993         return 203
994     fi
995     return 0
996 }
997
998 wait_update () {
999     local node=$1
1000     local TEST=$2
1001     local FINAL=$3
1002     local MAX=${4:-90}
1003
1004         local RESULT
1005         local WAIT=0
1006         local sleep=5
1007         while [ true ]; do
1008             RESULT=$(do_node $node "$TEST")
1009             if [ "$RESULT" == "$FINAL" ]; then
1010                 echo "Updated after $WAIT sec: wanted '$FINAL' got '$RESULT'"
1011                 return 0
1012             fi
1013             [ $WAIT -ge $MAX ] && break
1014             echo "Waiting $((MAX - WAIT)) secs for update"
1015             WAIT=$((WAIT + sleep))
1016             sleep $sleep
1017         done
1018         echo "Update not seen after $MAX sec: wanted '$FINAL' got '$RESULT'"
1019         return 3
1020 }
1021
1022 wait_update_facet () {
1023     local facet=$1
1024     wait_update  $(facet_active_host $facet) "$@"
1025 }
1026
1027 wait_delete_completed () {
1028     local TOTALPREV=`lctl get_param -n osc.*.kbytesavail | \
1029                      awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1030
1031     local WAIT=0
1032     local MAX_WAIT=20
1033     while [ "$WAIT" -ne "$MAX_WAIT" ]; do
1034         sleep 1
1035         TOTAL=`lctl get_param -n osc.*.kbytesavail | \
1036                awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1037         [ "$TOTAL" -eq "$TOTALPREV" ] && break
1038         echo "Waiting delete completed ... prev: $TOTALPREV current: $TOTAL "
1039         TOTALPREV=$TOTAL
1040         WAIT=$(( WAIT + 1))
1041     done
1042     echo "Delete completed."
1043 }
1044
1045 wait_for_host() {
1046     local host=$1
1047     check_network "$host" 900
1048     while ! do_node $host "ls -d $LUSTRE " > /dev/null; do sleep 5; done
1049 }
1050
1051 wait_for() {
1052     local facet=$1
1053     local host=`facet_active_host $facet`
1054     wait_for_host $host
1055 }
1056
1057 wait_recovery_complete () {
1058     local facet=$1
1059
1060     # Use default policy if $2 is not passed by caller. 
1061     #define OBD_RECOVERY_TIMEOUT (obd_timeout * 5 / 2)
1062     # as we are in process of changing obd_timeout in different ways
1063     # let's set MAX longer than that
1064     local MAX=${2:-$(( TIMEOUT * 4 ))}
1065  
1066     local var_svc=${facet}_svc
1067     local procfile="*.${!var_svc}.recovery_status"
1068     local WAIT=0
1069     local STATUS=
1070
1071     while [ $WAIT -lt $MAX ]; do
1072         STATUS=$(do_facet $facet lctl get_param -n $procfile | grep status)
1073         [[ $STATUS = "status: COMPLETE" ]] && return 0
1074         sleep 5
1075         WAIT=$((WAIT + 5))
1076         echo "Waiting $((MAX - WAIT)) secs for $facet recovery done. $STATUS"
1077     done
1078     echo "$facet recovery not done in $MAX sec. $STATUS"
1079     return 1
1080 }
1081
1082 wait_exit_ST () {
1083     local facet=$1
1084
1085     local WAIT=0
1086     local INTERVAL=1
1087     local running
1088     # conf-sanity 31 takes a long time cleanup
1089     while [ $WAIT -lt 300 ]; do
1090         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
1091         [ -z "${running}" ] && return 0
1092         echo "waited $WAIT for${running}"
1093         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
1094         sleep $INTERVAL
1095         WAIT=$((WAIT + INTERVAL))
1096     done
1097     echo "service didn't stop after $WAIT seconds.  Still running:"
1098     echo ${running}
1099     return 1
1100 }
1101
1102 wait_remote_prog () {
1103    local prog=$1
1104    local WAIT=0
1105    local INTERVAL=5
1106    local rc=0
1107
1108    [ "$PDSH" = "no_dsh" ] && return 0
1109
1110    while [ $WAIT -lt $2 ]; do
1111         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
1112         [ -z "${running}" ] && return 0 || true
1113         echo "waited $WAIT for: "
1114         echo "$running"
1115         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
1116         sleep $INTERVAL
1117         WAIT=$((WAIT + INTERVAL))
1118     done
1119     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
1120     [ -z "$pids" ] && return 0
1121     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
1122     # FIXME: not portable
1123     for pid in $pids; do
1124         cat /proc/${pid}/status || true
1125         cat /proc/${pid}/wchan || true
1126         echo "Killing $pid"
1127         kill -9 $pid || true
1128         sleep 1
1129         ps -P $pid && rc=1
1130     done
1131
1132     return $rc
1133 }
1134
1135 client_df() {
1136     # not every config has many clients
1137     if [ ! -z "$CLIENTS" ]; then
1138         $PDSH $CLIENTS "df $MOUNT" > /dev/null
1139     else
1140         df $MOUNT > /dev/null
1141     fi
1142 }
1143
1144 client_reconnect() {
1145     uname -n >> $MOUNT/recon
1146     if [ -z "$CLIENTS" ]; then
1147         df $MOUNT; uname -n >> $MOUNT/recon
1148     else
1149         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
1150     fi
1151     echo Connected clients:
1152     cat $MOUNT/recon
1153     ls -l $MOUNT/recon > /dev/null
1154     rm $MOUNT/recon
1155 }
1156
1157 facet_failover() {
1158     local facet=$1
1159     local sleep_time=$2
1160     echo "Failing $facet on node `facet_active_host $facet`"
1161     shutdown_facet $facet
1162     [ -n "$sleep_time" ] && sleep $sleep_time
1163     reboot_facet $facet
1164     change_active $facet
1165     local TO=`facet_active_host $facet`
1166     echo "Failover $facet to $TO"
1167     wait_for $facet
1168     mount_facet $facet || error "Restart of $facet failed"
1169 }
1170
1171 obd_name() {
1172     local facet=$1
1173 }
1174
1175 replay_barrier() {
1176     local facet=$1
1177     do_facet $facet sync
1178     df $MOUNT
1179     local svc=${facet}_svc
1180     do_facet $facet $LCTL --device %${!svc} notransno
1181     do_facet $facet $LCTL --device %${!svc} readonly
1182     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1183     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1184 }
1185
1186 replay_barrier_nodf() {
1187     local facet=$1    echo running=${running}
1188     do_facet $facet sync
1189     local svc=${facet}_svc
1190     echo Replay barrier on ${!svc}
1191     do_facet $facet $LCTL --device %${!svc} notransno
1192     do_facet $facet $LCTL --device %${!svc} readonly
1193     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1194     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1195 }
1196
1197 replay_barrier_nosync() {
1198     local facet=$1    echo running=${running}
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 mds_evict_client() {
1208     UUID=`lctl get_param -n mdc.${mds1_svc}-mdc-*.uuid`
1209     do_facet mds1 "lctl set_param -n mdt.${mds1_svc}.evict_client $UUID"
1210 }
1211
1212 ost_evict_client() {
1213     UUID=`lctl get_param -n devices| grep ${ost1_svc}-osc- | egrep -v 'MDT' | awk '{print $5}'`
1214     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
1215 }
1216
1217 fail() {
1218     facet_failover $* || error "failover: $?"
1219     client_df || error "post-failover df: $?"
1220 }
1221
1222 fail_nodf() {
1223         local facet=$1
1224         facet_failover $facet
1225 }
1226
1227 fail_abort() {
1228     local facet=$1
1229     stop $facet
1230     change_active $facet
1231     mount_facet $facet -o abort_recovery
1232     client_df || echo "first df failed: $?"
1233     sleep 1
1234     client_df || error "post-failover df: $?"
1235 }
1236
1237 do_lmc() {
1238     echo There is no lmc.  This is mountconf, baby.
1239     exit 1
1240 }
1241
1242 h2gm () {
1243     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1244         ID=`$PDSH $1 $GMNALNID -l | cut -d\  -f2`
1245         echo $ID"@gm"
1246     fi
1247 }
1248
1249 h2name_or_ip() {
1250     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1251         echo $1"@$2"
1252     fi
1253 }
1254
1255 h2ptl() {
1256    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1257        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
1258        if [ -z "$ID" ]; then
1259            echo "Could not get a ptl id for $1..."
1260            exit 1
1261        fi
1262        echo $ID"@ptl"
1263    fi
1264 }
1265 declare -fx h2ptl
1266
1267 h2tcp() {
1268     h2name_or_ip "$1" "tcp"
1269 }
1270 declare -fx h2tcp
1271
1272 h2elan() {
1273     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1274         if type __h2elan >/dev/null 2>&1; then
1275             ID=$(__h2elan $1)
1276         else
1277             ID=`echo $1 | sed 's/[^0-9]*//g'`
1278         fi
1279         echo $ID"@elan"
1280     fi
1281 }
1282 declare -fx h2elan
1283
1284 h2openib() {
1285     h2name_or_ip "$1" "openib"
1286 }
1287 declare -fx h2openib
1288
1289 h2o2ib() {
1290     h2name_or_ip "$1" "o2ib"
1291 }
1292 declare -fx h2o2ib
1293
1294 facet_host() {
1295     local facet=$1
1296
1297     [ "$facet" == client ] && echo -n $HOSTNAME && return
1298     varname=${facet}_HOST
1299     if [ -z "${!varname}" ]; then
1300         if [ "${facet:0:3}" == "ost" ]; then
1301             eval ${facet}_HOST=${ost_HOST}
1302         fi
1303     fi
1304     echo -n ${!varname}
1305 }
1306
1307 facet_active() {
1308     local facet=$1
1309     local activevar=${facet}active
1310
1311     if [ -f $TMP/${facet}active ] ; then
1312         source $TMP/${facet}active
1313     fi
1314
1315     active=${!activevar}
1316     if [ -z "$active" ] ; then
1317         echo -n ${facet}
1318     else
1319         echo -n ${active}
1320     fi
1321 }
1322
1323 facet_active_host() {
1324     local facet=$1
1325     local active=`facet_active $facet`
1326     if [ "$facet" == client ]; then
1327         echo $HOSTNAME
1328     else
1329         echo `facet_host $active`
1330     fi
1331 }
1332
1333 change_active() {
1334     local facet=$1
1335     local failover=${facet}failover
1336     host=`facet_host $failover`
1337     [ -z "$host" ] && return
1338     local curactive=`facet_active $facet`
1339     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
1340         eval export ${facet}active=$facet
1341     else
1342         eval export ${facet}active=$failover
1343     fi
1344     # save the active host for this facet
1345     local activevar=${facet}active
1346     echo "$activevar=${!activevar}" > $TMP/$activevar
1347 }
1348
1349 do_node() {
1350     HOST=$1
1351     shift
1352     local myPDSH=$PDSH
1353     if [ "$HOST" = "$HOSTNAME" ]; then
1354         myPDSH="no_dsh"
1355     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
1356         echo "cannot run remote command on $HOST with $myPDSH"
1357         return 128
1358     fi
1359     if $VERBOSE; then
1360         echo "CMD: $HOST $@" >&2
1361         $myPDSH $HOST $LCTL mark "$@" > /dev/null 2>&1 || :
1362     fi
1363
1364     if [ "$myPDSH" = "rsh" ]; then
1365 # we need this because rsh does not return exit code of an executed command
1366         local command_status="$TMP/cs"
1367         rsh $HOST ":> $command_status"
1368         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
1369                     cd $RPWD; sh -c \"$@\") ||
1370                     echo command failed >$command_status"
1371         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
1372         return 0
1373     fi
1374     $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed "s/^${HOST}: //"
1375     return ${PIPESTATUS[0]}
1376 }
1377
1378 single_local_node () {
1379    [ "$1" = "$HOSTNAME" ]
1380 }
1381
1382 do_nodes() {
1383     local rnodes=$1
1384     shift
1385
1386     if $(single_local_node $rnodes); then
1387         do_node $rnodes $@
1388         return $?
1389     fi
1390
1391     # This is part from do_node
1392     local myPDSH=$PDSH
1393
1394     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
1395         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
1396
1397     if $VERBOSE; then
1398         echo "CMD: $rnodes $@" >&2
1399         $myPDSH $rnodes $LCTL mark "$@" > /dev/null 2>&1 || :
1400     fi
1401
1402     $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed -re "s/\w+:\s//g"
1403     return ${PIPESTATUS[0]}
1404 }
1405
1406 do_facet() {
1407     local facet=$1
1408     shift
1409     local HOST=`facet_active_host $facet`
1410     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
1411     do_node $HOST "$@"
1412 }
1413
1414 add() {
1415     local facet=$1
1416     shift
1417     # make sure its not already running
1418     stop ${facet} -f
1419     rm -f $TMP/${facet}active
1420     do_facet ${facet} $MKFS $*
1421 }
1422
1423 ostdevname() {
1424     num=$1
1425     DEVNAME=OSTDEV$num
1426     #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
1427     eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}}
1428     echo -n $DEVPTR
1429 }
1430
1431 mdsdevname() {
1432     num=$1
1433     DEVNAME=MDSDEV$num
1434     #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
1435     eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}}
1436     echo -n $DEVPTR
1437 }
1438
1439 ########
1440 ## MountConf setup
1441
1442 stopall() {
1443     # make sure we are using the primary server, so test-framework will
1444     # be able to clean up properly.
1445     activemds=`facet_active mds1`
1446     if [ $activemds != "mds1" ]; then
1447         fail mds1
1448     fi
1449
1450     local clients=$CLIENTS
1451     [ -z $clients ] && clients=$(hostname)
1452
1453     zconf_umount_clients $clients $MOUNT "$*" || true
1454     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
1455
1456     [ "$CLIENTONLY" ] && return
1457     # The add fn does rm ${facet}active file, this would be enough
1458     # if we use do_facet <facet> only after the facet added, but
1459     # currently we use do_facet mds in local.sh
1460     for num in `seq $MDSCOUNT`; do
1461         stop mds$num -f
1462         rm -f ${TMP}/mds${num}active
1463     done
1464
1465     for num in `seq $OSTCOUNT`; do
1466         stop ost$num -f
1467         rm -f $TMP/ost${num}active
1468     done
1469
1470     return 0
1471 }
1472
1473 cleanupall() {
1474     stopall $*
1475     unload_modules
1476     cleanup_gss
1477 }
1478
1479 mdsmkfsopts()
1480 {
1481     local nr=$1
1482     test $nr = 1 && echo -n $MDS_MKFS_OPTS || echo -n $MDSn_MKFS_OPTS
1483 }
1484
1485 formatall() {
1486     if [ "$IAMDIR" == "yes" ]; then
1487         MDS_MKFS_OPTS="$MDS_MKFS_OPTS --iam-dir"
1488         MDSn_MKFS_OPTS="$MDSn_MKFS_OPTS --iam-dir"
1489     fi
1490
1491     [ "$FSTYPE" ] && FSTYPE_OPT="--backfstype $FSTYPE"
1492
1493     if [ ! -z $SEC ]; then
1494         MDS_MKFS_OPTS="$MDS_MKFS_OPTS --param srpc.flavor.default=$SEC"
1495         MDSn_MKFS_OPTS="$MDSn_MKFS_OPTS --param srpc.flavor.default=$SEC"
1496         OST_MKFS_OPTS="$OST_MKFS_OPTS --param srpc.flavor.default=$SEC"
1497     fi
1498
1499     stopall
1500     # We need ldiskfs here, may as well load them all
1501     load_modules
1502     [ "$CLIENTONLY" ] && return
1503     echo "Formatting mdts, osts"
1504     for num in `seq $MDSCOUNT`; do
1505         echo "Format mds$num: $(mdsdevname $num)"
1506         if $VERBOSE; then
1507             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` || exit 9
1508         else
1509             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` > /dev/null || exit 9
1510         fi
1511     done
1512
1513     for num in `seq $OSTCOUNT`; do
1514         echo "Format ost$num: $(ostdevname $num)"
1515         if $VERBOSE; then
1516             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` || exit 10
1517         else
1518             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` > /dev/null || exit 10
1519         fi
1520     done
1521 }
1522
1523 mount_client() {
1524     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
1525 }
1526
1527 umount_client() {
1528     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
1529 }
1530
1531 # return value:
1532 # 0: success, the old identity set already.
1533 # 1: success, the old identity does not set.
1534 # 2: fail.
1535 switch_identity() {
1536     local num=$1
1537     local switch=$2
1538     local j=`expr $num - 1`
1539     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
1540
1541     if [ -z "$MDT" ]; then
1542         return 2
1543     fi
1544
1545     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
1546
1547     if $switch; then
1548         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
1549     else
1550         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
1551     fi
1552
1553     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush \"-1\""
1554
1555     if [ $old = "NONE" ]; then
1556         return 1
1557     else
1558         return 0
1559     fi
1560 }
1561
1562 remount_client()
1563 {
1564         zconf_umount `hostname` $1 || error "umount failed"
1565         zconf_mount `hostname` $1 || error "mount failed"
1566 }
1567
1568 writeconf_facet () {
1569     local facet=$1
1570     local dev=$2
1571
1572     do_facet $facet "$TUNEFS --writeconf $dev"
1573 }
1574
1575 writeconf_all () {
1576     for num in `seq $MDSCOUNT`; do
1577         DEVNAME=$(mdsdevname $num)
1578         writeconf_facet mds$num $DEVNAME
1579     done
1580
1581     for num in `seq $OSTCOUNT`; do
1582         DEVNAME=$(ostdevname $num)
1583         writeconf_facet ost$num $DEVNAME
1584     done
1585 }
1586
1587 setupall() {
1588     sanity_mount_check ||
1589         error "environments are insane!"
1590
1591     load_modules
1592     init_gss
1593     if [ -z "$CLIENTONLY" ]; then
1594         echo "Setup mdts, osts"
1595         echo $WRITECONF | grep -q "writeconf" && \
1596             writeconf_all
1597         for num in `seq $MDSCOUNT`; do
1598             DEVNAME=$(mdsdevname $num)
1599             start mds$num $DEVNAME $MDS_MOUNT_OPTS
1600
1601             # We started mds, now we should set failover variables properly.
1602             # Set mds${num}failover_HOST if it is not set (the default failnode).
1603             local varname=mds${num}failover_HOST
1604             if [ -z "${!varname}" ]; then
1605                 eval mds${num}failover_HOST=$(facet_host mds$num)
1606             fi
1607
1608             if [ $IDENTITY_UPCALL != "default" ]; then
1609                 switch_identity $num $IDENTITY_UPCALL
1610             fi
1611         done
1612         for num in `seq $OSTCOUNT`; do
1613             DEVNAME=$(ostdevname $num)
1614             start ost$num $DEVNAME $OST_MOUNT_OPTS
1615
1616             # We started ost$num, now we should set ost${num}failover variable properly.
1617             # Set ost${num}failover_HOST if it is not set (the default failnode).
1618             varname=ost${num}failover_HOST
1619             if [ -z "${!varname}" ]; then
1620                 eval ost${num}failover_HOST=$(facet_host ost${num})
1621             fi
1622
1623         done
1624     fi
1625     # wait a while to allow sptlrpc configuration be propogated to targets,
1626     # only needed when mounting new target devices.
1627     $GSS && sleep 10
1628
1629     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
1630     mount_client $MOUNT
1631     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
1632
1633     if [ "$MOUNT_2" ]; then
1634         mount_client $MOUNT2
1635         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
1636     fi
1637
1638     init_param_vars
1639
1640     # by remounting mdt before ost, initial connect from mdt to ost might
1641     # timeout because ost is not ready yet. wait some time to its fully
1642     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
1643     # by a context negotiation rpc with $TIMEOUT.
1644     # FIXME better by monitoring import status.
1645     if $GSS; then
1646         sleep $((TIMEOUT + 5))
1647     else
1648         sleep 5
1649     fi
1650 }
1651
1652 mounted_lustre_filesystems() {
1653         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
1654 }
1655
1656 init_facet_vars () {
1657     [ "$CLIENTONLY" ] && return 0
1658     local facet=$1
1659     shift
1660     local device=$1
1661
1662     shift
1663
1664     eval export ${facet}_dev=${device}
1665     eval export ${facet}_opt=\"$@\"
1666
1667     local dev=${facet}_dev
1668     local label=$(do_facet ${facet} "$E2LABEL ${!dev}")
1669     [ -z "$label" ] && echo no label for ${!dev} && exit 1
1670
1671     eval export ${facet}_svc=${label}
1672
1673     local varname=${facet}failover_HOST
1674     if [ -z "${!varname}" ]; then
1675        eval $varname=$(facet_host $facet) 
1676     fi
1677
1678     # ${facet}failover_dev is set in cfg file
1679     varname=${facet}failover_dev
1680     if [ -n "${!varname}" ] ; then
1681         eval export ${facet}failover_dev=${!varname}
1682     else
1683         eval export ${facet}failover_dev=$device
1684     fi
1685 }
1686
1687 init_facets_vars () {
1688     local DEVNAME
1689
1690     if ! remote_mds_nodsh; then 
1691         for num in `seq $MDSCOUNT`; do
1692             DEVNAME=`mdsdevname $num`
1693             init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
1694         done
1695     fi
1696
1697     remote_ost_nodsh && return
1698
1699     for num in `seq $OSTCOUNT`; do
1700         DEVNAME=`ostdevname $num`
1701         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
1702     done
1703 }
1704
1705 mds_sanity_check () {
1706     local timeout=$1
1707     local period=0
1708
1709     while [ $period -lt $timeout ]; do
1710         count=$(do_facet $SINGLEMDS "lctl dl | grep 'osc.*mdtlov_UUID' | grep ' IN ' 2>/dev/null | wc -l")
1711         if [ $count -eq 0 ]; then
1712             break
1713         fi
1714
1715         echo "There are $count OST are inactive, wait $period seconds, and try again"
1716         sleep 3
1717         period=$((period+3))
1718     done
1719
1720     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
1721 }
1722
1723 som_check() {
1724     SOM_ENABLED=$(do_facet $SINGLEMDS "$LCTL get_param mdt.*.som" | awk -F= ' {print $2}' | head -n 1)
1725     echo $SOM_ENABLED
1726 }
1727
1728 init_param_vars () {
1729     if ! remote_ost_nodsh && ! remote_mds_nodsh; then
1730         export MDSVER=$(do_facet $SINGLEMDS "lctl get_param version" | cut -d. -f1,2)
1731         export OSTVER=$(do_facet ost1 "lctl get_param version" | cut -d. -f1,2)
1732         export CLIVER=$(lctl get_param version | cut -d. -f 1,2)
1733     fi
1734
1735     remote_mds_nodsh ||
1736         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
1737
1738     log "Using TIMEOUT=$TIMEOUT"
1739
1740     mds_sanity_check $TIMEOUT
1741
1742     if [ x"$(som_check)" = x"enabled" ]; then
1743         ENABLE_QUOTA=""
1744     fi
1745     if [ "$ENABLE_QUOTA" ]; then
1746         setup_quota $MOUNT  || return 2
1747     fi
1748 }
1749
1750 check_config () {
1751     local mntpt=$1
1752
1753     local mounted=$(mount | grep " $mntpt ")
1754     if [ "$CLIENTONLY" ]; then
1755         # bug 18021
1756         # CLIENTONLY should not depend on *_HOST settings
1757         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
1758         # in theory someone could create a new,
1759         # client-only config file that assumed lustre was already
1760         # configured and didn't set the MGSNID. If MGSNID is not set,
1761         # then we should use the mgs nid currently being used 
1762         # as the default value. bug 18021
1763         [[ x$MGSNID = x ]] &&
1764             MGSNID=${mgc//MGC/}
1765
1766         if [[ x$mgc != xMGC$MGSNID ]]; then
1767             if [ "$mgs_HOST" ]; then
1768                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
1769                 [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
1770                     error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
1771             fi
1772         fi
1773         return 0
1774     fi
1775
1776     local myMGS_host=$mgs_HOST   
1777     if [ "$NETTYPE" = "ptl" ]; then
1778         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
1779     fi
1780
1781     echo Checking config lustre mounted on $mntpt
1782     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
1783     mgshost=$(echo $mgshost | awk -F: '{print $1}')
1784
1785     if [ "$mgshost" != "$myMGS_host" ]; then
1786             error_exit "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
1787                    Please use correct config or set mds_HOST correctly!"
1788     fi
1789
1790     sanity_mount_check ||
1791         error "environments are insane!"
1792 }
1793
1794 check_timeout () {
1795     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
1796     local cltimeout=$(lctl get_param -n timeout)
1797     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
1798         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
1799         return 1
1800     fi
1801 }
1802
1803 check_and_setup_lustre() {
1804     local MOUNTED=$(mounted_lustre_filesystems)
1805     if [ -z "$MOUNTED" ] || ! $(echo $MOUNTED | grep -w -q $MOUNT); then
1806         [ "$REFORMAT" ] && formatall
1807         setupall
1808         MOUNTED=$(mounted_lustre_filesystems | head -1)
1809         [ -z "$MOUNTED" ] && error "NAME=$NAME not mounted"
1810         export I_MOUNTED=yes
1811     else
1812         check_config $MOUNT
1813         init_facets_vars
1814         init_param_vars
1815     fi
1816     if [ "$ONLY" == "setup" ]; then
1817         exit 0
1818     fi
1819 }
1820
1821 cleanup_and_setup_lustre() {
1822     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
1823         lctl set_param debug=0 || true
1824         cleanupall
1825         if [ "$ONLY" == "cleanup" ]; then
1826             exit 0
1827         fi
1828     fi
1829     check_and_setup_lustre
1830 }
1831
1832 check_and_cleanup_lustre() {
1833     if [ "`mount | grep $MOUNT`" ]; then
1834         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
1835         [ "$ENABLE_QUOTA" ] && restore_quota_type || true
1836     fi
1837     if [ "$I_MOUNTED" = "yes" ]; then
1838         cleanupall -f || error "cleanup failed"
1839     fi
1840     unset I_MOUNTED
1841 }
1842
1843 #######
1844 # General functions
1845
1846 check_network() {
1847     local NETWORK=0
1848     local WAIT=0
1849     local MAX=$2
1850     while [ $NETWORK -eq 0 ]; do
1851         ping -c 1 -w 3 $1 > /dev/null
1852         if [ $? -eq 0 ]; then
1853             NETWORK=1
1854         else
1855             WAIT=$((WAIT + 5))
1856             echo "waiting for $1, $((MAX - WAIT)) secs left"
1857             sleep 5
1858         fi
1859         if [ $WAIT -gt $MAX ]; then
1860             echo "Network not available"
1861             exit 1
1862         fi
1863     done
1864 }
1865 check_port() {
1866     while( !($DSH2 $1 "netstat -tna | grep -q $2") ) ; do
1867         sleep 9
1868     done
1869 }
1870
1871 no_dsh() {
1872     shift
1873     eval $@
1874 }
1875
1876 comma_list() {
1877     # the sed converts spaces to commas, but leaves the last space
1878     # alone, so the line doesn't end with a comma.
1879     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
1880 }
1881
1882 # list, excluded are the comma separated lists
1883 exclude_items_from_list () {
1884     local list=$1
1885     local excluded=$2
1886     local item
1887
1888     list=${list//,/ }
1889     for item in ${excluded//,/ }; do
1890         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
1891     done
1892     echo $(comma_list $list) 
1893 }
1894
1895 # list, expand  are the comma separated lists
1896 expand_list () {
1897     local list=${1//,/ }
1898     local expand=${2//,/ }
1899     local expanded=
1900
1901     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
1902     echo $(comma_list $expanded)
1903 }
1904
1905 absolute_path() {
1906     (cd `dirname $1`; echo $PWD/`basename $1`)
1907 }
1908
1909 get_facets () {
1910     local name=$(echo $1 | tr "[:upper:]" "[:lower:]")
1911     local type=$(echo $1 | tr "[:lower:]" "[:upper:]")
1912
1913     local list=""
1914     local count=${type}COUNT
1915     for ((i=1; i<=${!count}; i++)) do
1916         list="$list ${name}$i"
1917     done
1918     echo $(comma_list $list)
1919 }
1920
1921 ##################################
1922 # Adaptive Timeouts funcs
1923
1924 at_is_enabled() {
1925     # only check mds, we assume at_max is the same on all nodes
1926     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
1927     if [ $at_max -eq 0 ]; then
1928         return 1
1929     else
1930         return 0
1931     fi
1932 }
1933
1934 at_max_get() {
1935     local facet=$1
1936
1937     # suppose that all ost-s has the same at_max set
1938     if [ $facet == "ost" ]; then
1939         do_facet ost1 "lctl get_param -n at_max"
1940     else
1941         do_facet $facet "lctl get_param -n at_max"
1942     fi
1943 }
1944
1945 at_max_set() {
1946     local at_max=$1
1947     shift
1948
1949     local facet
1950     for facet in $@; do
1951         if [ $facet == "ost" ]; then
1952             for i in `seq $OSTCOUNT`; do
1953                 do_facet ost$i "lctl set_param at_max=$at_max"
1954
1955             done
1956         elif [ $facet == "mds" ]; then
1957             for i in `seq $MDSCOUNT`; do
1958                 do_facet mds$i "lctl set_param at_max=$at_max"
1959             done
1960         else
1961             do_facet $facet "lctl set_param at_max=$at_max"
1962         fi
1963     done
1964 }
1965
1966 ##################################
1967 # OBD_FAIL funcs
1968
1969 drop_request() {
1970 # OBD_FAIL_MDS_ALL_REQUEST_NET
1971     RC=0
1972     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
1973     do_facet client "$1" || RC=$?
1974     do_facet $SINGLEMDS lctl set_param fail_loc=0
1975     return $RC
1976 }
1977
1978 drop_reply() {
1979 # OBD_FAIL_MDS_ALL_REPLY_NET
1980     RC=0
1981     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
1982     do_facet client "$@" || RC=$?
1983     do_facet $SINGLEMDS lctl set_param fail_loc=0
1984     return $RC
1985 }
1986
1987 drop_reint_reply() {
1988 # OBD_FAIL_MDS_REINT_NET_REP
1989     RC=0
1990     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
1991     do_facet client "$@" || RC=$?
1992     do_facet $SINGLEMDS lctl set_param fail_loc=0
1993     return $RC
1994 }
1995
1996 pause_bulk() {
1997 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
1998     RC=0
1999     do_facet ost1 lctl set_param fail_loc=0x214
2000     do_facet client "$1" || RC=$?
2001     do_facet client "sync"
2002     do_facet ost1 lctl set_param fail_loc=0
2003     return $RC
2004 }
2005
2006 drop_ldlm_cancel() {
2007 #define OBD_FAIL_LDLM_CANCEL             0x304
2008     RC=0
2009     do_facet client lctl set_param fail_loc=0x304
2010     do_facet client "$@" || RC=$?
2011     do_facet client lctl set_param fail_loc=0
2012     return $RC
2013 }
2014
2015 drop_bl_callback() {
2016 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
2017     RC=0
2018     do_facet client lctl set_param fail_loc=0x305
2019     do_facet client "$@" || RC=$?
2020     do_facet client lctl set_param fail_loc=0
2021     return $RC
2022 }
2023
2024 drop_ldlm_reply() {
2025 #define OBD_FAIL_LDLM_REPLY              0x30c
2026     RC=0
2027     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
2028     do_facet client "$@" || RC=$?
2029     do_facet $SINGLEMDS lctl set_param fail_loc=0
2030     return $RC
2031 }
2032
2033 clear_failloc() {
2034     facet=$1
2035     pause=$2
2036     sleep $pause
2037     echo "clearing fail_loc on $facet"
2038     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
2039 }
2040
2041 set_nodes_failloc () {
2042     do_nodes $(comma_list $1)  lctl set_param fail_loc=$2
2043 }
2044
2045 cancel_lru_locks() {
2046     $LCTL mark "cancel_lru_locks $1 start"
2047     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
2048         $LCTL set_param -n $d=clear
2049     done
2050     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
2051     $LCTL mark "cancel_lru_locks $1 stop"
2052 }
2053
2054 default_lru_size()
2055 {
2056         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
2057         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
2058         echo "$DEFAULT_LRU_SIZE"
2059 }
2060
2061 lru_resize_enable()
2062 {
2063     lctl set_param ldlm.namespaces.*$1*.lru_size=0
2064 }
2065
2066 lru_resize_disable()
2067 {
2068     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
2069 }
2070
2071 pgcache_empty() {
2072     local FILE
2073     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
2074         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
2075             echo there is still data in page cache $FILE ?
2076             lctl get_param -n $FILE
2077             return 1
2078         fi
2079     done
2080     return 0
2081 }
2082
2083 debugsave() {
2084     DEBUGSAVE="$(lctl get_param -n debug)"
2085 }
2086
2087 debugrestore() {
2088     [ -n "$DEBUGSAVE" ] && lctl set_param debug="${DEBUGSAVE}"
2089     DEBUGSAVE=""
2090 }
2091
2092 ##################################
2093 # Test interface
2094 ##################################
2095
2096 error_noexit() {
2097     local TYPE=${TYPE:-"FAIL"}
2098     local ERRLOG
2099     lctl set_param fail_loc=0 2>/dev/null || true
2100     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
2101     ERRLOG=$TMP/lustre_${TESTSUITE}_${TESTNAME}.$(date +%s)
2102     echo "Dumping lctl log to $ERRLOG"
2103     # We need to dump the logs on all nodes
2104     do_nodes $(comma_list $(nodes_list)) $NODE $LCTL dk $ERRLOG
2105     debugrestore
2106     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
2107     TEST_FAILED=true
2108 }
2109
2110 error() {
2111     error_noexit "$@"
2112     $FAIL_ON_ERROR && exit 1 || true
2113 }
2114
2115 error_exit() {
2116     error_noexit "$@"
2117     exit 1
2118 }
2119
2120 # use only if we are ignoring failures for this test, bugno required.
2121 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
2122 # e.g. error_ignore 5494 "your message"
2123 error_ignore() {
2124     local TYPE="IGNORE (bz$1)"
2125     shift
2126     error_noexit "$@"
2127 }
2128
2129 skip () {
2130     echo
2131     log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
2132     [ "$TESTSUITELOG" ] && \
2133         echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
2134 }
2135
2136 build_test_filter() {
2137     [ "$ONLY" ] && log "only running test `echo $ONLY`"
2138     for O in $ONLY; do
2139         eval ONLY_${O}=true
2140     done
2141     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
2142         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
2143     [ "$EXCEPT_SLOW" ] && \
2144         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
2145     for E in $EXCEPT $ALWAYS_EXCEPT; do
2146         eval EXCEPT_${E}=true
2147     done
2148     for E in $EXCEPT_SLOW; do
2149         eval EXCEPT_SLOW_${E}=true
2150     done
2151     for G in $GRANT_CHECK_LIST; do
2152         eval GCHECK_ONLY_${G}=true
2153         done
2154 }
2155
2156 _basetest() {
2157     echo $*
2158 }
2159
2160 basetest() {
2161     IFS=abcdefghijklmnopqrstuvwxyz _basetest $1
2162 }
2163
2164 # print a newline if the last test was skipped
2165 export LAST_SKIPPED=
2166 run_test() {
2167     assert_DIR
2168
2169     export base=`basetest $1`
2170     if [ ! -z "$ONLY" ]; then
2171         testname=ONLY_$1
2172         if [ ${!testname}x != x ]; then
2173             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2174             run_one $1 "$2"
2175             return $?
2176         fi
2177         testname=ONLY_$base
2178         if [ ${!testname}x != x ]; then
2179             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2180             run_one $1 "$2"
2181             return $?
2182         fi
2183         LAST_SKIPPED="y"
2184         echo -n "."
2185         return 0
2186     fi
2187     testname=EXCEPT_$1
2188     if [ ${!testname}x != x ]; then
2189         LAST_SKIPPED="y"
2190         TESTNAME=test_$1 skip "skipping excluded test $1"
2191         return 0
2192     fi
2193     testname=EXCEPT_$base
2194     if [ ${!testname}x != x ]; then
2195         LAST_SKIPPED="y"
2196         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
2197         return 0
2198     fi
2199     testname=EXCEPT_SLOW_$1
2200     if [ ${!testname}x != x ]; then
2201         LAST_SKIPPED="y"
2202         TESTNAME=test_$1 skip "skipping SLOW test $1"
2203         return 0
2204     fi
2205     testname=EXCEPT_SLOW_$base
2206     if [ ${!testname}x != x ]; then
2207         LAST_SKIPPED="y"
2208         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
2209         return 0
2210     fi
2211
2212     LAST_SKIPPED=
2213     run_one $1 "$2"
2214
2215     return $?
2216 }
2217
2218 EQUALS="======================================================================"
2219 equals_msg() {
2220     msg="$@"
2221
2222     local suffixlen=$((${#EQUALS} - ${#msg}))
2223     [ $suffixlen -lt 5 ] && suffixlen=5
2224     log `echo $(printf '===== %s %.*s\n' "$msg" $suffixlen $EQUALS)`
2225 }
2226
2227 log() {
2228     echo "$*"
2229     lsmod | grep lnet > /dev/null || load_modules
2230
2231     local MSG="$*"
2232     # Get rid of '
2233     MSG=${MSG//\'/\\\'}
2234     MSG=${MSG//\(/\\\(}
2235     MSG=${MSG//\)/\\\)}
2236     MSG=${MSG//\;/\\\;}
2237     MSG=${MSG//\|/\\\|}
2238     MSG=${MSG//\>/\\\>}
2239     MSG=${MSG//\</\\\<}
2240     MSG=${MSG//\//\\\/}
2241     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
2242 }
2243
2244 trace() {
2245         log "STARTING: $*"
2246         strace -o $TMP/$1.strace -ttt $*
2247         RC=$?
2248         log "FINISHED: $*: rc $RC"
2249         return 1
2250 }
2251
2252 pass() {
2253     $TEST_FAILED && echo -n "FAIL " || echo -n "PASS " 
2254     echo $@
2255 }
2256
2257 check_mds() {
2258     FFREE=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filesfree | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2259     FTOTAL=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filestotal | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2260     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
2261 }
2262
2263 reset_fail_loc () {
2264     echo -n "Resetting fail_loc on all nodes..."
2265     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
2266     echo done.
2267 }
2268
2269 run_one() {
2270     testnum=$1
2271     message=$2
2272     tfile=f${testnum}
2273     export tdir=d0.${TESTSUITE}/d${base}
2274
2275     local SAVE_UMASK=`umask`
2276     umask 0022
2277
2278     local BEFORE=`date +%s`
2279     echo
2280     log "== test $testnum: $message == `date +%H:%M:%S` ($BEFORE)"
2281     #check_mds
2282     export TESTNAME=test_$testnum
2283     TEST_FAILED=false
2284     test_${testnum} || error "test_$testnum failed with $?"
2285     #check_mds
2286     cd $SAVE_PWD
2287     reset_fail_loc
2288     check_grant ${testnum} || error "check_grant $testnum failed with $?"
2289     check_catastrophe || error "LBUG/LASSERT detected"
2290     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
2291     pass "($((`date +%s` - $BEFORE))s)"
2292     TEST_FAILED=false
2293     unset TESTNAME
2294     unset tdir
2295     umask $SAVE_UMASK
2296 }
2297
2298 canonical_path() {
2299     (cd `dirname $1`; echo $PWD/`basename $1`)
2300 }
2301
2302 sync_clients() {
2303     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
2304     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
2305         cd $SAVE_PWD
2306 }
2307
2308 check_grant() {
2309     export base=`basetest $1`
2310     [ "$CHECK_GRANT" == "no" ] && return 0
2311
2312         testname=GCHECK_ONLY_${base}
2313         [ ${!testname}x == x ] && return 0
2314
2315     echo -n "checking grant......"
2316         cd $SAVE_PWD
2317         # write some data to sync client lost_grant
2318         rm -f $DIR1/${tfile}_check_grant_* 2>&1
2319         for i in `seq $OSTCOUNT`; do
2320                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
2321                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
2322                                               count=1 > /dev/null 2>&1
2323         done
2324         # sync all the data and make sure no pending data on server
2325         sync_clients
2326         
2327         #get client grant and server grant
2328         client_grant=0
2329     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
2330                 client_grant=$((client_grant + $d))
2331         done
2332         server_grant=0
2333         for d in `lctl get_param -n obdfilter.*.tot_granted`; do
2334                 server_grant=$((server_grant + $d))
2335         done
2336
2337         # cleanup the check_grant file
2338         for i in `seq $OSTCOUNT`; do
2339                 rm $DIR1/${tfile}_check_grant_$i
2340         done
2341
2342         #check whether client grant == server grant
2343         if [ $client_grant != $server_grant ]; then
2344                 echo "failed: client:${client_grant} server: ${server_grant}"
2345                 return 1
2346         else
2347                 echo "pass"
2348         fi
2349 }
2350
2351 ########################
2352 # helper functions
2353
2354 osc_to_ost()
2355 {
2356     osc=$1
2357     ost=`echo $1 | awk -F_ '{print $3}'`
2358     if [ -z $ost ]; then
2359         ost=`echo $1 | sed 's/-osc.*//'`
2360     fi
2361     echo $ost
2362 }
2363
2364 remote_node () {
2365     local node=$1
2366     [ "$node" != "$(hostname)" ]
2367 }
2368
2369 remote_mds ()
2370 {
2371     local node
2372     for node in $(mdts_nodes); do
2373         remote_node $node && return 0
2374     done
2375     return 1
2376 }
2377
2378 remote_mds_nodsh()
2379 {
2380     [ "$CLIENTONLY" ] && return 0 || true
2381     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
2382 }
2383
2384 remote_ost ()
2385 {
2386     local node
2387     for node in $(osts_nodes) ; do
2388         remote_node $node && return 0
2389     done
2390     return 1
2391 }
2392
2393 remote_ost_nodsh()
2394 {
2395     [ "$CLIENTONLY" ] && return 0 || true 
2396     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2397 }
2398
2399 remote_mgs_nodsh()
2400 {
2401     local MGS 
2402     MGS=$(facet_host mgs)
2403     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2404 }
2405
2406 mdts_nodes () {
2407     local MDSNODES
2408     local NODES_sort
2409     for num in `seq $MDSCOUNT`; do
2410         MDSNODES="$MDSNODES $(facet_host mds$num)"
2411     done
2412     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
2413
2414     echo $NODES_sort
2415 }
2416
2417 remote_servers () {
2418     remote_ost && remote_mds
2419 }
2420
2421 osts_nodes () {
2422     local OSTNODES=$(facet_host ost1)
2423     local NODES_sort
2424
2425     for num in `seq $OSTCOUNT`; do
2426         local myOST=$(facet_host ost$num)
2427         OSTNODES="$OSTNODES $myOST"
2428     done
2429     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
2430
2431     echo $NODES_sort
2432 }
2433
2434 nodes_list () {
2435     # FIXME. We need a list of clients
2436     local myNODES=$HOSTNAME
2437     local myNODES_sort
2438
2439     # CLIENTS (if specified) contains the local client
2440     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
2441
2442     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
2443         myNODES="$myNODES $(osts_nodes) $(mdts_nodes)"
2444     fi
2445
2446     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
2447
2448     echo $myNODES_sort
2449 }
2450
2451 remote_nodes_list () {
2452     local rnodes=$(nodes_list)
2453     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2454     echo $rnodes
2455 }
2456
2457 init_clients_lists () {
2458     # Sanity check: exclude the local client from RCLIENTS
2459     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2460
2461     # Sanity check: exclude the dup entries
2462     rclients=$(for i in $rclients; do echo $i; done | sort -u)
2463
2464     local clients="$SINGLECLIENT $HOSTNAME $rclients"
2465
2466     # Sanity check: exclude the dup entries from CLIENTS
2467     # for those configs which has SINGLCLIENT set to local client
2468     clients=$(for i in $clients; do echo $i; done | sort -u)
2469
2470     CLIENTS=`comma_list $clients`
2471     local -a remoteclients=($rclients)
2472     for ((i=0; $i<${#remoteclients[@]}; i++)); do
2473             varname=CLIENT$((i + 2))
2474             eval $varname=${remoteclients[i]}
2475     done
2476
2477     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
2478 }
2479
2480 get_random_entry () {
2481     local rnodes=$1
2482
2483     rnodes=${rnodes//,/ }
2484
2485     local -a nodes=($rnodes)
2486     local num=${#nodes[@]} 
2487     local i=$((RANDOM * num * 2 / 65536))
2488
2489     echo ${nodes[i]}
2490 }
2491
2492 is_patchless ()
2493 {
2494     lctl get_param version | grep -q patchless
2495 }
2496
2497 check_versions () {
2498     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
2499 }
2500
2501 get_node_count() {
2502     local nodes="$@"
2503     echo $nodes | wc -w || true
2504 }
2505
2506 mixed_ost_devs () {
2507     local nodes=$(osts_nodes)
2508     local osscount=$(get_node_count "$nodes")
2509     [ ! "$OSTCOUNT" = "$osscount" ]
2510 }
2511
2512 mixed_mdt_devs () {
2513     local nodes=$(mdts_nodes)
2514     local mdtcount=$(get_node_count "$nodes")
2515     [ ! "$MDSCOUNT" = "$mdtcount" ]
2516 }
2517
2518 generate_machine_file() {
2519     local nodes=${1//,/ }
2520     local machinefile=$2
2521     rm -f $machinefile || error "can't rm $machinefile"
2522     for node in $nodes; do
2523         echo $node >>$machinefile
2524     done
2525 }
2526
2527 get_stripe () {
2528     local file=$1/stripe
2529     touch $file
2530     $LFS getstripe -v $file || error
2531     rm -f $file
2532 }
2533
2534 check_runas_id_ret() {
2535     local myRC=0
2536     local myRUNAS_UID=$1
2537     local myRUNAS_GID=$2
2538     shift 2
2539     local myRUNAS=$@
2540     if [ -z "$myRUNAS" ]; then
2541         error_exit "myRUNAS command must be specified for check_runas_id"
2542     fi
2543     if $GSS_KRB5; then
2544         $myRUNAS krb5_login.sh || \
2545             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
2546     fi
2547     mkdir $DIR/d0_runas_test
2548     chmod 0755 $DIR
2549     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
2550     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
2551     rm -rf $DIR/d0_runas_test
2552     return $myRC
2553 }
2554
2555 check_runas_id() {
2556     local myRUNAS_UID=$1
2557     local myRUNAS_GID=$2
2558     shift 2
2559     local myRUNAS=$@
2560     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
2561         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
2562         Please set RUNAS_ID to some UID which exists on MDS and client or
2563         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
2564 }
2565
2566 # Run multiop in the background, but wait for it to print
2567 # "PAUSING" to its stdout before returning from this function.
2568 multiop_bg_pause() {
2569     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
2570     FILE=$1
2571     ARGS=$2
2572
2573     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
2574     mkfifo $TMPPIPE
2575
2576     echo "$MULTIOP_PROG $FILE v$ARGS"
2577     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
2578
2579     echo "TMPPIPE=${TMPPIPE}"
2580     read -t 60 multiop_output < $TMPPIPE
2581     if [ $? -ne 0 ]; then
2582         rm -f $TMPPIPE
2583         return 1
2584     fi
2585     rm -f $TMPPIPE
2586     if [ "$multiop_output" != "PAUSING" ]; then
2587         echo "Incorrect multiop output: $multiop_output"
2588         kill -9 $PID
2589         return 1
2590     fi
2591
2592     return 0
2593 }
2594
2595 do_and_time () {
2596     local cmd=$1
2597     local rc
2598
2599     SECONDS=0
2600     eval '$cmd'
2601     
2602     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
2603
2604     echo $SECONDS
2605     return $rc
2606 }
2607
2608 inodes_available () {
2609     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
2610     echo $IFree
2611 }
2612
2613 # reset llite stat counters
2614 clear_llite_stats(){
2615         lctl set_param -n llite.*.stats 0
2616 }
2617
2618 # sum llite stat items
2619 calc_llite_stats() {
2620         local res=$(lctl get_param -n llite.*.stats |
2621                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
2622         echo $res
2623 }
2624
2625 # reset osc stat counters
2626 clear_osc_stats(){
2627         lctl set_param -n osc.*.osc_stats 0
2628 }
2629
2630 # sum osc stat items
2631 calc_osc_stats() {
2632         local res=$(lctl get_param -n osc.*.osc_stats |
2633                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
2634         echo $res
2635 }
2636
2637 calc_sum () {
2638         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
2639 }
2640
2641 calc_osc_kbytes () {
2642         df $MOUNT > /dev/null
2643         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
2644 }
2645
2646 # save_lustre_params(node, parameter_mask)
2647 # generate a stream of formatted strings (<node> <param name>=<param value>)
2648 save_lustre_params() {
2649         local s
2650         do_node $1 "lctl get_param $2" | while read s; do echo "$1 $s"; done
2651 }
2652
2653 # restore lustre parameters from input stream, produces by save_lustre_params
2654 restore_lustre_params() {
2655         local node
2656         local name
2657         local val
2658         while IFS=" =" read node name val; do
2659                 do_node $node "lctl set_param -n $name $val"
2660         done
2661 }
2662
2663 check_catastrophe() {
2664     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
2665     local C=$CATASTROPHE
2666     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
2667
2668     if [ $rnodes ]; then
2669         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
2670 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
2671 exit \\\$rc;"
2672     fi 
2673 }
2674
2675 # $1 node
2676 # $2 file
2677 # $3 $RUNAS
2678 get_stripe_info() {
2679         local tmp_file
2680
2681         stripe_size=0
2682         stripe_count=0
2683         stripe_index=0
2684         tmp_file=$(mktemp)
2685
2686         do_facet $1 $3 lfs getstripe -v $2 > $tmp_file
2687
2688         stripe_size=`awk '$1 ~ /size/ {print $2}' $tmp_file`
2689         stripe_count=`awk '$1 ~ /count/ {print $2}' $tmp_file`
2690         stripe_index=`awk '/obdidx/ {start = 1; getline; print $1; exit}' $tmp_file`
2691         rm -f $tmp_file
2692 }
2693
2694 # CMD: determine mds index where directory inode presents
2695 get_mds_dir () {
2696     local dir=$1
2697     local file=$dir/f0.get_mds_dir_tmpfile
2698
2699     rm -f $file
2700     sleep 1
2701     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
2702     local -a oldused=($iused)
2703
2704     touch $file
2705     sleep 1
2706     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
2707     local -a newused=($iused)
2708
2709     local num=0
2710     for ((i=0; i<${#newused[@]}; i++)); do
2711          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
2712              echo $(( i + 1 ))
2713              rm -f $file
2714              return 0
2715          fi
2716     done
2717     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
2718 }
2719
2720 mdsrate_cleanup () {
2721     mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
2722 }
2723
2724 delayed_recovery_enabled () {
2725     local var=${SINGLEMDS}_svc
2726     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
2727 }
2728
2729 ########################
2730 convert_facet2name() {
2731     case "$1" in
2732         "ost" ) echo "OST0000" ;;
2733         "ost1") echo "OST0000" ;;
2734         "ost2") echo "OST0001" ;;
2735         "ost3") echo "OST0002" ;;
2736         "ost4") echo "OST0003" ;;
2737         "ost5") echo "OST0004" ;;
2738         *) error "unknown facet!" ;;
2739     esac
2740 }
2741
2742 get_clientosc_proc_path() {
2743     local ost=$1
2744
2745     echo "{$1}-osc-*"
2746 }
2747
2748 get_lustre_version () {
2749     local node=${1:-"mds"}    
2750     do_facet $node $LCTL get_param -n version |  awk '/^lustre:/ {print $2}'
2751 }
2752
2753 get_mds_version_major () {
2754     local version=$(get_lustre_version mds)
2755     echo $version | awk -F. '{print $1}'
2756 }
2757
2758 get_mds_version_minor () {
2759     local version=$(get_lustre_version mds)
2760     echo $version | awk -F. '{print $2}'
2761 }
2762
2763 get_mdtosc_proc_path() {
2764     local ost=$1
2765     local major=$(get_mds_version_major)
2766     local minor=$(get_mds_version_minor)
2767     if [ $major -le 1 -a $minor -le 8 ] ; then
2768         echo "${ost}-osc"
2769     else
2770         echo "${ost}-osc-MDT0000"
2771     fi
2772 }
2773
2774 get_osc_import_name() {
2775     local node=$1
2776     local ost=$2
2777     local name=$(convert_facet2name $ost)
2778
2779     if [ "$node" == "mds" ]; then
2780         get_mdtosc_proc_path $name
2781         return 0
2782     fi
2783
2784     get_clientosc_proc_path $name
2785     return 0
2786 }
2787
2788 wait_osc_import_state() {
2789     local node=$1
2790     local ost_facet=$2
2791     local expected=$3
2792     local ost=$(get_osc_import_name $node $ost_facet)
2793     local CONN_PROC
2794     local CONN_STATE
2795     local i=0
2796
2797     CONN_PROC="osc.${FSNAME}-${ost}.ost_server_uuid"
2798     CONN_STATE=$(do_facet $node lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
2799     while [ "${CONN_STATE}" != "${expected}" ]; do
2800         # for disconn we can check after proc entry is removed
2801         [ "x${CONN_STATE}" == "x" -a "${expected}" == "DISCONN" ] && return 0
2802         # disconnect rpc should be wait not more obd_timeout
2803         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
2804             error "can't put import for ${ost}(${ost_facet}) into ${expected} state" && return 1
2805         sleep 1
2806         CONN_STATE=$(do_facet $node lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
2807         i=$(($i + 1))
2808     done
2809
2810     log "${ost_facet} now in ${CONN_STATE} state"
2811     return 0
2812 }