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