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