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