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