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