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