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