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