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