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