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