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