Whamcloud - gitweb
b=19116
[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 # nodes is comma list
638 sanity_mount_check_nodes () {
639     local nodes=$1
640     shift
641     local mnts="$@"
642     local mnt
643
644     # FIXME: assume that all cluster nodes run the same os
645     [ "$(uname)" = Linux ] || return 0
646
647     local rc=0
648     for mnt in $mnts ; do
649         do_nodes $nodes "set -x; running=\\\$(grep -c $mnt' ' /proc/mounts);
650 mpts=\\\$(mount | grep -w -c $mnt);
651 if [ \\\$running -ne \\\$mpts ]; then
652     echo \\\$(hostname) env are INSANE!;
653     exit 1;
654 fi"
655     [ $? -eq 0 ] || rc=1 
656     done
657     return $rc
658 }
659
660 sanity_mount_check_servers () {
661     echo Checking servers environments
662
663     # FIXME: modify get_facets to display all facets wo params
664     local facets="$(get_facets OST),$(get_facets MDS)"
665     local node
666     local mnt
667     local facet
668     for facet in ${facets//,/ }; do
669         node=$(facet_host ${facet})
670         mnt=${MOUNT%/*}/${facet}
671         sanity_mount_check_nodes $node $mnt ||
672             { error "server $node environments are insane!"; return 1; }
673     done
674 }
675
676 sanity_mount_check_clients () {
677     local clients=${1:-$CLIENTS}
678     local mntpt=${2:-$MOUNT}
679     local mntpt2=${3:-$MOUNT2}
680
681     [ -z $clients ] && clients=$(hostname)
682     echo Checking clients $clients environments
683
684     sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
685        error "clients environments are insane!"
686 }
687
688 sanity_mount_check () {
689     sanity_mount_check_servers || return 1
690     sanity_mount_check_clients || return 2
691 }
692
693 # mount clients if not mouted
694 zconf_mount_clients() {
695     local OPTIONS
696     local clients=$1
697     local mnt=$2
698
699
700     # Only supply -o to mount if we have options
701     if [ -n "$MOUNTOPT" ]; then
702         OPTIONS="-o $MOUNTOPT"
703     fi
704     local device=$MGSNID:/$FSNAME
705     if [ -z "$mnt" -o -z "$FSNAME" ]; then
706         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
707         exit 1
708     fi
709
710     echo "Starting client $clients: $OPTIONS $device $mnt"
711
712     do_nodes $clients "set -x;
713 running=\\\$(mount | grep -c $mnt' ');
714 rc=0;
715 if [ \\\$running -eq 0 ] ; then
716     mkdir -p $mnt;
717     mount -t lustre $OPTIONS $device $mnt;
718     rc=$?;
719 fi;
720 exit $rc"
721
722     echo "Started clients $clients: "
723     do_nodes $clients "mount | grep -w $mnt"
724
725     do_nodes $clients "lctl set_param debug=\\\"$PTLDEBUG\\\";
726         lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
727         lctl set_param debug_mb=${DEBUG_SIZE};"
728
729     return 0
730 }
731
732 zconf_umount_clients() {
733     local clients=$1
734     local mnt=$2
735     local force
736
737     [ "$3" ] && force=-f
738
739     echo "Stopping clients: $clients $mnt (opts:$force)"
740     do_nodes $clients "set -x; running=\\\$(grep -c $mnt' ' /proc/mounts);
741 if [ \\\$running -ne 0 ] ; then
742 echo Stopping client \\\$(hostname) client $mnt opts:$force;
743 lsof -t $mnt || need_kill=no;
744 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
745     pids=\\\$(lsof -t $mnt | sort -u);
746     if [ -n \\\"\\\$pids\\\" ]; then
747              kill -9 \\\$pids;
748     fi
749 fi;
750 busy=\\\$(umount $force $mnt 2>&1 | grep -c "busy");
751 if [ \\\$busy -ne 0 ] ; then
752     echo "$mnt is still busy, wait one second" && sleep 1;
753     umount $force $mnt;
754 fi
755 fi"
756 }
757
758 shudown_node_hard () {
759     local host=$1
760     local attempts=3
761
762     for i in $(seq $attempts) ; do
763         $POWER_DOWN $host
764         sleep 1
765         ping -w 3 -c 1 $host > /dev/null 2>&1 || return 0
766         echo "waiting for $host to fail attempts=$attempts"
767         [ $i -lt $attempts ] || \
768             { echo "$host still pingable after power down! attempts=$attempts" && return 1; } 
769     done
770 }
771
772 shutdown_client() {
773     local client=$1
774     local mnt=${2:-$MOUNT}
775     local attempts=3
776
777     if [ "$FAILURE_MODE" = HARD ]; then
778         shudown_node_hard $client 
779     else
780        zconf_umount_clients $client $mnt -f
781     fi
782 }
783
784 shutdown_facet() {
785     local facet=$1
786     if [ "$FAILURE_MODE" = HARD ]; then
787         shudown_node_hard $(facet_active_host $facet)
788     elif [ "$FAILURE_MODE" = SOFT ]; then
789         stop $facet
790     fi
791 }
792
793 reboot_facet() {
794     facet=$1
795     if [ "$FAILURE_MODE" = HARD ]; then
796         $POWER_UP `facet_active_host $facet`
797     else
798         sleep 10
799     fi
800 }
801
802 boot_node() {
803     local node=$1
804     if [ "$FAILURE_MODE" = HARD ]; then
805        $POWER_UP $node
806     fi
807 }
808
809 # recovery-scale functions
810 check_progs_installed () {
811     local clients=$1
812     shift
813     local progs=$@
814
815     do_nodes $clients "set -x ; PATH=:$PATH status=true; for prog in $progs; do
816         which \\\$prog || { echo \\\$prog missing on \\\$(hostname) && status=false; }
817         done;
818         eval \\\$status"
819 }
820
821 client_var_name() {
822     echo __$(echo $1 | tr '-' 'X')
823 }
824
825 start_client_load() {
826     local client=$1
827     local load=$2
828     local var=$(client_var_name $client)_load
829     eval export ${var}=$load
830
831     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
832                               BREAK_ON_ERROR=$BREAK_ON_ERROR \
833                               END_RUN_FILE=$END_RUN_FILE \
834                               LOAD_PID_FILE=$LOAD_PID_FILE \
835                               TESTSUITELOG=$TESTSUITELOG \
836                               run_${load}.sh" &
837     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $!"
838     log "Started client load: ${load} on $client"
839
840     return 0
841 }
842
843 start_client_loads () {
844     local -a clients=(${1//,/ })
845     local numloads=${#CLIENT_LOADS[@]}
846     local testnum
847
848     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
849         testnum=$((nodenum % numloads))
850         start_client_load ${clients[nodenum]} ${CLIENT_LOADS[testnum]}
851     done
852 }
853
854 # only for remote client 
855 check_client_load () {
856     local client=$1
857     local var=$(client_var_name $client)_load
858     local TESTLOAD=run_${!var}.sh
859
860     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
861
862     check_catastrophe $client || return 2
863
864     # see if the load is still on the client
865     local tries=3
866     local RC=254
867     while [ $RC = 254 -a $tries -gt 0 ]; do
868         let tries=$tries-1
869         # assume success
870         RC=0
871         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
872             RC=${PIPESTATUS[0]}
873             sleep 30
874         fi
875     done
876     if [ $RC = 254 ]; then
877         echo "got a return status of $RC from do_node while checking (i.e. with 'ps') the client load on the remote system"
878         # see if we can diagnose a bit why this is
879     fi
880
881     return $RC
882 }
883 check_client_loads () {
884    local clients=${1//,/ }
885    local client=
886    local rc=0
887
888    for client in $clients; do
889       check_client_load $client
890       rc=${PIPESTATUS[0]}
891       if [ "$rc" != 0 ]; then
892         log "Client load failed on node $client, rc=$rc"
893         return $rc
894       fi
895    done
896 }
897
898 restart_client_loads () {
899     local clients=${1//,/ }
900     local expectedfail=${2:-""}
901     local client=
902     local rc=0
903
904     for client in $clients; do
905         check_client_load $client
906         rc=${PIPESTATUS[0]}
907         if [ "$rc" != 0 -a "$expectedfail" ]; then
908             start_client_load $client
909             echo "Restarted client load: on $client. Checking ..."
910             check_client_load $client 
911             rc=${PIPESTATUS[0]}
912             if [ "$rc" != 0 ]; then
913                 log "Client load failed to restart on node $client, rc=$rc"
914                 # failure one client load means test fail
915                 # we do not need to check other 
916                 return $rc
917             fi
918         else
919             return $rc
920         fi
921     done
922 }
923 # End recovery-scale functions
924
925 # verify that lustre actually cleaned up properly
926 cleanup_check() {
927     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
928         error "LBUG/LASSERT detected"
929     BUSY=`dmesg | grep -i destruct || true`
930     if [ "$BUSY" ]; then
931         echo "$BUSY" 1>&2
932         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
933         exit 205
934     fi
935
936     check_mem_leak || exit 204
937
938     [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl && \
939         echo "$0: lustre didn't clean up..." 1>&2 && return 202 || true
940
941     if [ "`/sbin/lsmod 2>&1 | egrep 'lnet|libcfs'`" ]; then
942         echo "$0: modules still loaded..." 1>&2
943         /sbin/lsmod 1>&2
944         return 203
945     fi
946     return 0
947 }
948
949 wait_update () {
950     local node=$1
951     local TEST=$2
952     local FINAL=$3
953     local MAX=${4:-90}
954
955         local RESULT
956         local WAIT=0
957         local sleep=5
958         while [ $WAIT -lt $MAX ]; do
959             RESULT=$(do_node $node "$TEST")
960             if [ "$RESULT" == "$FINAL" ]; then
961                 echo "Updated after $WAIT sec: wanted '$FINAL' got '$RESULT'"
962                 return 0
963             fi
964             echo "Waiting $((MAX - WAIT)) secs for update"
965             WAIT=$((WAIT + sleep))
966             sleep $sleep
967         done
968         echo "Update not seen after $MAX sec: wanted '$FINAL' got '$RESULT'"
969         return 3
970 }
971
972 wait_update_facet () {
973     local facet=$1
974     wait_update  $(facet_host $facet) $@
975 }
976
977 wait_delete_completed () {
978     local TOTALPREV=`lctl get_param -n osc.*.kbytesavail | \
979                      awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
980
981     local WAIT=0
982     local MAX_WAIT=20
983     while [ "$WAIT" -ne "$MAX_WAIT" ]; do
984         sleep 1
985         TOTAL=`lctl get_param -n osc.*.kbytesavail | \
986                awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
987         [ "$TOTAL" -eq "$TOTALPREV" ] && break
988         echo "Waiting delete completed ... prev: $TOTALPREV current: $TOTAL "
989         TOTALPREV=$TOTAL
990         WAIT=$(( WAIT + 1))
991     done
992     echo "Delete completed."
993 }
994
995 wait_for_host() {
996     local host=$1
997     check_network "$host" 900
998     while ! do_node $host "ls -d $LUSTRE " > /dev/null; do sleep 5; done
999 }
1000
1001 wait_for() {
1002     local facet=$1
1003     local host=`facet_active_host $facet`
1004     wait_for_host $host
1005 }
1006
1007 wait_recovery_complete () {
1008     local facet=$1
1009
1010     # Use default policy if $2 is not passed by caller. 
1011     #define OBD_RECOVERY_TIMEOUT (obd_timeout * 5 / 2)
1012     # as we are in process of changing obd_timeout in different ways
1013     # let's set MAX longer than that
1014     local MAX=${2:-$(( TIMEOUT * 4 ))}
1015  
1016     local var_svc=${facet}_svc
1017     local procfile="*.${!var_svc}.recovery_status"
1018     local WAIT=0
1019     local STATUS=
1020
1021     while [ $WAIT -lt $MAX ]; do
1022         STATUS=$(do_facet $facet lctl get_param -n $procfile | grep status)
1023         [[ $STATUS = "status: COMPLETE" ]] && return 0
1024         sleep 5
1025         WAIT=$((WAIT + 5))
1026         echo "Waiting $((MAX - WAIT)) secs for $facet recovery done. $STATUS"
1027     done
1028     echo "$facet recovery not done in $MAX sec. $STATUS"
1029     return 1
1030 }
1031
1032 wait_exit_ST () {
1033     local facet=$1
1034
1035     local WAIT=0
1036     local INTERVAL=1
1037     local running
1038     # conf-sanity 31 takes a long time cleanup
1039     while [ $WAIT -lt 300 ]; do
1040         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
1041         [ -z "${running}" ] && return 0
1042         echo "waited $WAIT for${running}"
1043         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
1044         sleep $INTERVAL
1045         WAIT=$((WAIT + INTERVAL))
1046     done
1047     echo "service didn't stop after $WAIT seconds.  Still running:"
1048     echo ${running}
1049     return 1
1050 }
1051
1052 wait_remote_prog () {
1053    local prog=$1
1054    local WAIT=0
1055    local INTERVAL=5
1056    local rc=0
1057
1058    [ "$PDSH" = "no_dsh" ] && return 0
1059
1060    while [ $WAIT -lt $2 ]; do
1061         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
1062         [ -z "${running}" ] && return 0 || true
1063         echo "waited $WAIT for: "
1064         echo "$running"
1065         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
1066         sleep $INTERVAL
1067         WAIT=$((WAIT + INTERVAL))
1068     done
1069     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
1070     [ -z "$pids" ] && return 0
1071     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
1072     # FIXME: not portable
1073     for pid in $pids; do
1074         cat /proc/${pid}/status || true
1075         cat /proc/${pid}/wchan || true
1076         echo "Killing $pid"
1077         kill -9 $pid || true
1078         sleep 1
1079         ps -P $pid && rc=1
1080     done
1081
1082     return $rc
1083 }
1084
1085 client_df() {
1086     # not every config has many clients
1087     if [ ! -z "$CLIENTS" ]; then
1088         $PDSH $CLIENTS "df $MOUNT" > /dev/null
1089     else
1090         df $MOUNT > /dev/null
1091     fi
1092 }
1093
1094 client_reconnect() {
1095     uname -n >> $MOUNT/recon
1096     if [ -z "$CLIENTS" ]; then
1097         df $MOUNT; uname -n >> $MOUNT/recon
1098     else
1099         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
1100     fi
1101     echo Connected clients:
1102     cat $MOUNT/recon
1103     ls -l $MOUNT/recon > /dev/null
1104     rm $MOUNT/recon
1105 }
1106
1107 facet_failover() {
1108     local facet=$1
1109     local sleep_time=$2
1110     echo "Failing $facet on node `facet_active_host $facet`"
1111     shutdown_facet $facet
1112     [ -n "$sleep_time" ] && sleep $sleep_time
1113     reboot_facet $facet
1114     client_df &
1115     DFPID=$!
1116     echo "df pid is $DFPID"
1117     change_active $facet
1118     local TO=`facet_active_host $facet`
1119     echo "Failover $facet to $TO"
1120     wait_for $facet
1121     mount_facet $facet || error "Restart of $facet failed"
1122 }
1123
1124 obd_name() {
1125     local facet=$1
1126 }
1127
1128 replay_barrier() {
1129     local facet=$1
1130     do_facet $facet sync
1131     df $MOUNT
1132     local svc=${facet}_svc
1133     do_facet $facet $LCTL --device %${!svc} readonly
1134     do_facet $facet $LCTL --device %${!svc} notransno
1135     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1136     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1137 }
1138
1139 replay_barrier_nodf() {
1140     local facet=$1    echo running=${running}
1141     do_facet $facet sync
1142     local svc=${facet}_svc
1143     echo Replay barrier on ${!svc}
1144     do_facet $facet $LCTL --device %${!svc} readonly
1145     do_facet $facet $LCTL --device %${!svc} notransno
1146     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1147     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1148 }
1149
1150 replay_barrier_nosync() {
1151     local facet=$1    echo running=${running}
1152     local svc=${facet}_svc
1153     echo Replay barrier on ${!svc}
1154     do_facet $facet $LCTL --device %${!svc} readonly
1155     do_facet $facet $LCTL --device %${!svc} notransno
1156     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1157     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1158 }
1159
1160 mds_evict_client() {
1161     UUID=`lctl get_param -n mdc.${mds1_svc}-mdc-*.uuid`
1162     do_facet mds1 "lctl set_param -n mdt.${mds1_svc}.evict_client $UUID"
1163 }
1164
1165 ost_evict_client() {
1166     UUID=`lctl get_param -n devices| grep ${ost1_svc}-osc- | egrep -v 'MDT' | awk '{print $5}'`
1167     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
1168 }
1169
1170 fail() {
1171     facet_failover $* || error "failover: $?"
1172     df $MOUNT || error "post-failover df: $?"
1173 }
1174
1175 fail_nodf() {
1176         local facet=$1
1177         facet_failover $facet
1178 }
1179
1180 fail_abort() {
1181     local facet=$1
1182     stop $facet
1183     change_active $facet
1184     mount_facet $facet -o abort_recovery
1185     df $MOUNT || echo "first df failed: $?"
1186     sleep 1
1187     df $MOUNT || error "post-failover df: $?"
1188 }
1189
1190 do_lmc() {
1191     echo There is no lmc.  This is mountconf, baby.
1192     exit 1
1193 }
1194
1195 h2gm () {
1196     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1197         ID=`$PDSH $1 $GMNALNID -l | cut -d\  -f2`
1198         echo $ID"@gm"
1199     fi
1200 }
1201
1202 h2name_or_ip() {
1203     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1204         echo $1"@$2"
1205     fi
1206 }
1207
1208 h2ptl() {
1209    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1210        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
1211        if [ -z "$ID" ]; then
1212            echo "Could not get a ptl id for $1..."
1213            exit 1
1214        fi
1215        echo $ID"@ptl"
1216    fi
1217 }
1218 declare -fx h2ptl
1219
1220 h2tcp() {
1221     h2name_or_ip "$1" "tcp"
1222 }
1223 declare -fx h2tcp
1224
1225 h2elan() {
1226     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1227         if type __h2elan >/dev/null 2>&1; then
1228             ID=$(__h2elan $1)
1229         else
1230             ID=`echo $1 | sed 's/[^0-9]*//g'`
1231         fi
1232         echo $ID"@elan"
1233     fi
1234 }
1235 declare -fx h2elan
1236
1237 h2openib() {
1238     h2name_or_ip "$1" "openib"
1239 }
1240 declare -fx h2openib
1241
1242 h2o2ib() {
1243     h2name_or_ip "$1" "o2ib"
1244 }
1245 declare -fx h2o2ib
1246
1247 facet_host() {
1248     local facet=$1
1249
1250     [ "$facet" == client ] && echo -n $HOSTNAME && return
1251     varname=${facet}_HOST
1252     if [ -z "${!varname}" ]; then
1253         if [ "${facet:0:3}" == "ost" ]; then
1254             eval ${facet}_HOST=${ost_HOST}
1255         fi
1256     fi
1257     echo -n ${!varname}
1258 }
1259
1260 facet_active() {
1261     local facet=$1
1262     local activevar=${facet}active
1263
1264     if [ -f $TMP/${facet}active ] ; then
1265         source $TMP/${facet}active
1266     fi
1267
1268     active=${!activevar}
1269     if [ -z "$active" ] ; then
1270         echo -n ${facet}
1271     else
1272         echo -n ${active}
1273     fi
1274 }
1275
1276 facet_active_host() {
1277     local facet=$1
1278     local active=`facet_active $facet`
1279     if [ "$facet" == client ]; then
1280         echo $HOSTNAME
1281     else
1282         echo `facet_host $active`
1283     fi
1284 }
1285
1286 change_active() {
1287     local facet=$1
1288     failover=${facet}failover
1289     host=`facet_host $failover`
1290     [ -z "$host" ] && return
1291     curactive=`facet_active $facet`
1292     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
1293         eval export ${facet}active=$facet
1294     else
1295         eval export ${facet}active=$failover
1296     fi
1297     # save the active host for this facet
1298     activevar=${facet}active
1299     echo "$activevar=${!activevar}" > $TMP/$activevar
1300 }
1301
1302 do_node() {
1303     HOST=$1
1304     shift
1305     local myPDSH=$PDSH
1306     if [ "$HOST" = "$HOSTNAME" ]; then
1307         myPDSH="no_dsh"
1308     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
1309         echo "cannot run remote command on $HOST with $myPDSH"
1310         return 128
1311     fi
1312     if $VERBOSE; then
1313         echo "CMD: $HOST $@" >&2
1314         $myPDSH $HOST $LCTL mark "$@" > /dev/null 2>&1 || :
1315     fi
1316
1317     if [ "$myPDSH" = "rsh" ]; then
1318 # we need this because rsh does not return exit code of an executed command
1319         local command_status="$TMP/cs"
1320         rsh $HOST ":> $command_status"
1321         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
1322                     cd $RPWD; sh -c \"$@\") ||
1323                     echo command failed >$command_status"
1324         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
1325         return 0
1326     fi
1327     $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed "s/^${HOST}: //"
1328     return ${PIPESTATUS[0]}
1329 }
1330
1331 single_local_node () {
1332    [ "$1" = "$HOSTNAME" ]
1333 }
1334
1335 do_nodes() {
1336     local rnodes=$1
1337     shift
1338
1339     if $(single_local_node $rnodes); then
1340         do_node $rnodes $@
1341         return $?
1342     fi
1343
1344     # This is part from do_node
1345     local myPDSH=$PDSH
1346
1347     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
1348         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
1349
1350     if $VERBOSE; then
1351         echo "CMD: $rnodes $@" >&2
1352         $myPDSH $rnodes $LCTL mark "$@" > /dev/null 2>&1 || :
1353     fi
1354
1355     $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed -re "s/\w+:\s//g"
1356     return ${PIPESTATUS[0]}
1357 }
1358
1359 do_facet() {
1360     facet=$1
1361     shift
1362     HOST=`facet_active_host $facet`
1363     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
1364     do_node $HOST "$@"
1365 }
1366
1367 add() {
1368     local facet=$1
1369     shift
1370     # make sure its not already running
1371     stop ${facet} -f
1372     rm -f $TMP/${facet}active
1373     do_facet ${facet} $MKFS $*
1374 }
1375
1376 ostdevname() {
1377     num=$1
1378     DEVNAME=OSTDEV$num
1379     #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
1380     eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}}
1381     echo -n $DEVPTR
1382 }
1383
1384 mdsdevname() {
1385     num=$1
1386     DEVNAME=MDSDEV$num
1387     #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
1388     eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}}
1389     echo -n $DEVPTR
1390 }
1391
1392 ########
1393 ## MountConf setup
1394
1395 stopall() {
1396     # make sure we are using the primary server, so test-framework will
1397     # be able to clean up properly.
1398     activemds=`facet_active mds1`
1399     if [ $activemds != "mds1" ]; then
1400         fail mds1
1401     fi
1402
1403     local clients=$CLIENTS
1404     [ -z $clients ] && clients=$(hostname)
1405
1406     zconf_umount_clients $clients $MOUNT "$*" || true
1407     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
1408
1409     [ "$CLIENTONLY" ] && return
1410     # The add fn does rm ${facet}active file, this would be enough
1411     # if we use do_facet <facet> only after the facet added, but
1412     # currently we use do_facet mds in local.sh
1413     for num in `seq $MDSCOUNT`; do
1414         stop mds$num -f
1415         rm -f ${TMP}/mds${num}active
1416     done
1417
1418     for num in `seq $OSTCOUNT`; do
1419         stop ost$num -f
1420         rm -f $TMP/ost${num}active
1421     done
1422
1423     return 0
1424 }
1425
1426 cleanupall() {
1427     stopall $*
1428     unload_modules
1429     cleanup_gss
1430 }
1431
1432 mdsmkfsopts()
1433 {
1434     local nr=$1
1435     test $nr = 1 && echo -n $MDS_MKFS_OPTS || echo -n $MDSn_MKFS_OPTS
1436 }
1437
1438 formatall() {
1439     if [ "$IAMDIR" == "yes" ]; then
1440         MDS_MKFS_OPTS="$MDS_MKFS_OPTS --iam-dir"
1441         MDSn_MKFS_OPTS="$MDSn_MKFS_OPTS --iam-dir"
1442     fi
1443
1444     [ "$FSTYPE" ] && FSTYPE_OPT="--backfstype $FSTYPE"
1445
1446     if [ ! -z $SEC ]; then
1447         MDS_MKFS_OPTS="$MDS_MKFS_OPTS --param srpc.flavor.default=$SEC"
1448         MDSn_MKFS_OPTS="$MDSn_MKFS_OPTS --param srpc.flavor.default=$SEC"
1449         OST_MKFS_OPTS="$OST_MKFS_OPTS --param srpc.flavor.default=$SEC"
1450     fi
1451
1452     stopall
1453     # We need ldiskfs here, may as well load them all
1454     load_modules
1455     [ "$CLIENTONLY" ] && return
1456     echo "Formatting mdts, osts"
1457     for num in `seq $MDSCOUNT`; do
1458         echo "Format mds$num: $(mdsdevname $num)"
1459         if $VERBOSE; then
1460             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` || exit 9
1461         else
1462             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` > /dev/null || exit 9
1463         fi
1464     done
1465
1466     for num in `seq $OSTCOUNT`; do
1467         echo "Format ost$num: $(ostdevname $num)"
1468         if $VERBOSE; then
1469             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` || exit 10
1470         else
1471             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` > /dev/null || exit 10
1472         fi
1473     done
1474 }
1475
1476 mount_client() {
1477     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
1478 }
1479
1480 umount_client() {
1481     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
1482 }
1483
1484 # return value:
1485 # 0: success, the old identity set already.
1486 # 1: success, the old identity does not set.
1487 # 2: fail.
1488 switch_identity() {
1489     local num=$1
1490     local switch=$2
1491     local j=`expr $num - 1`
1492     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
1493
1494     if [ -z "$MDT" ]; then
1495         return 2
1496     fi
1497
1498     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
1499
1500     if $switch; then
1501         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
1502     else
1503         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
1504     fi
1505
1506     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush \"-1\""
1507
1508     if [ $old = "NONE" ]; then
1509         return 1
1510     else
1511         return 0
1512     fi
1513 }
1514
1515 remount_client()
1516 {
1517         zconf_umount `hostname` $1 || error "umount failed"
1518         zconf_mount `hostname` $1 || error "mount failed"
1519 }
1520
1521 writeconf_facet () {
1522     local facet=$1
1523     local dev=$2
1524
1525     do_facet $facet "$TUNEFS --writeconf $dev"
1526 }
1527
1528 writeconf_all () {
1529     for num in `seq $MDSCOUNT`; do
1530         DEVNAME=$(mdsdevname $num)
1531         writeconf_facet mds$num $DEVNAME
1532     done
1533
1534     for num in `seq $OSTCOUNT`; do
1535         DEVNAME=$(ostdevname $num)
1536         writeconf_facet ost$num $DEVNAME
1537     done
1538 }
1539
1540 setupall() {
1541     sanity_mount_check ||
1542         error "environments are insane!"
1543
1544     load_modules
1545     init_gss
1546     if [ -z "$CLIENTONLY" ]; then
1547         echo "Setup mdts, osts"
1548         echo $WRITECONF | grep -q "writeconf" && \
1549             writeconf_all
1550         for num in `seq $MDSCOUNT`; do
1551             DEVNAME=$(mdsdevname $num)
1552             start mds$num $DEVNAME $MDS_MOUNT_OPTS
1553
1554             # We started mds, now we should set failover variables properly.
1555             # Set mds${num}failover_HOST if it is not set (the default failnode).
1556             local varname=mds${num}failover_HOST
1557             if [ -z "${!varname}" ]; then
1558                 eval mds${num}failover_HOST=$(facet_host mds$num)
1559             fi
1560
1561             if [ $IDENTITY_UPCALL != "default" ]; then
1562                 switch_identity $num $IDENTITY_UPCALL
1563             fi
1564         done
1565         for num in `seq $OSTCOUNT`; do
1566             DEVNAME=$(ostdevname $num)
1567             start ost$num $DEVNAME $OST_MOUNT_OPTS
1568
1569             # We started ost$num, now we should set ost${num}failover variable properly.
1570             # Set ost${num}failover_HOST if it is not set (the default failnode).
1571             varname=ost${num}failover_HOST
1572             if [ -z "${!varname}" ]; then
1573                 eval ost${num}failover_HOST=$(facet_host ost${num})
1574             fi
1575
1576         done
1577     fi
1578     # wait a while to allow sptlrpc configuration be propogated to targets,
1579     # only needed when mounting new target devices.
1580     $GSS && sleep 10
1581
1582     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
1583     mount_client $MOUNT
1584     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
1585
1586     if [ "$MOUNT_2" ]; then
1587         mount_client $MOUNT2
1588         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
1589     fi
1590
1591     init_param_vars
1592
1593     # by remounting mdt before ost, initial connect from mdt to ost might
1594     # timeout because ost is not ready yet. wait some time to its fully
1595     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
1596     # by a context negotiation rpc with $TIMEOUT.
1597     # FIXME better by monitoring import status.
1598     if $GSS; then
1599         sleep $((TIMEOUT + 5))
1600     else
1601         sleep 5
1602     fi
1603 }
1604
1605 mounted_lustre_filesystems() {
1606         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
1607 }
1608
1609 init_facet_vars () {
1610     local facet=$1
1611     shift
1612     local device=$1
1613
1614     shift
1615
1616     eval export ${facet}_dev=${device}
1617     eval export ${facet}_opt=\"$@\"
1618
1619     local dev=${facet}_dev
1620     local label=$(do_facet ${facet} "$E2LABEL ${!dev}")
1621     [ -z "$label" ] && echo no label for ${!dev} && exit 1
1622
1623     eval export ${facet}_svc=${label}
1624
1625     local varname=${facet}failover_HOST
1626     if [ -z "${!varname}" ]; then
1627        eval $varname=$(facet_host $facet) 
1628     fi
1629 }
1630
1631 init_facets_vars () {
1632     local DEVNAME
1633
1634     if ! remote_mds_nodsh; then 
1635         for num in `seq $MDSCOUNT`; do
1636             DEVNAME=`mdsdevname $num`
1637             init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
1638         done
1639     fi
1640
1641     remote_ost_nodsh && return
1642
1643     for num in `seq $OSTCOUNT`; do
1644         DEVNAME=`ostdevname $num`
1645         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
1646     done
1647 }
1648
1649 init_param_vars () {
1650     if ! remote_ost_nodsh && ! remote_mds_nodsh; then
1651         export MDSVER=$(do_facet $SINGLEMDS "lctl get_param version" | cut -d. -f1,2)
1652         export OSTVER=$(do_facet ost1 "lctl get_param version" | cut -d. -f1,2)
1653         export CLIVER=$(lctl get_param version | cut -d. -f 1,2)
1654     fi
1655
1656     remote_mds_nodsh ||
1657         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
1658
1659     log "Using TIMEOUT=$TIMEOUT"
1660
1661     if [ "$ENABLE_QUOTA" ]; then
1662         setup_quota $MOUNT  || return 2
1663     fi
1664 }
1665
1666 check_config () {
1667     local mntpt=$1
1668     local myMGS_host=$mgs_HOST   
1669     if [ "$NETTYPE" = "ptl" ]; then
1670         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
1671     fi
1672
1673     echo Checking config lustre mounted on $mntpt
1674     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
1675     mgshost=$(echo $mgshost | awk -F: '{print $1}')
1676
1677     if [ "$mgshost" != "$myMGS_host" ]; then
1678         FAIL_ON_ERROR=true \
1679             error "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
1680                    Please use correct config or set mds_HOST correctly!"
1681     fi
1682
1683     sanity_mount_check ||
1684         error "environments are insane!"
1685 }
1686
1687 check_timeout () {
1688     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
1689     local cltimeout=$(lctl get_param -n timeout)
1690     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
1691         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
1692         return 1
1693     fi
1694 }
1695
1696 check_and_setup_lustre() {
1697     local MOUNTED=$(mounted_lustre_filesystems)
1698     if [ -z "$MOUNTED" ] || ! $(echo $MOUNTED | grep -w -q $MOUNT); then
1699         [ "$REFORMAT" ] && formatall
1700         setupall
1701         MOUNTED=$(mounted_lustre_filesystems | head -1)
1702         [ -z "$MOUNTED" ] && error "NAME=$NAME not mounted"
1703         export I_MOUNTED=yes
1704     else
1705         check_config $MOUNT
1706         init_facets_vars
1707         init_param_vars
1708     fi
1709     if [ "$ONLY" == "setup" ]; then
1710         exit 0
1711     fi
1712 }
1713
1714 cleanup_and_setup_lustre() {
1715     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
1716         lctl set_param debug=0 || true
1717         cleanupall
1718         if [ "$ONLY" == "cleanup" ]; then
1719             exit 0
1720         fi
1721     fi
1722     check_and_setup_lustre
1723 }
1724
1725 check_and_cleanup_lustre() {
1726     if [ "`mount | grep $MOUNT`" ]; then
1727         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
1728         [ "$ENABLE_QUOTA" ] && restore_quota_type || true
1729     fi
1730     if [ "$I_MOUNTED" = "yes" ]; then
1731         cleanupall -f || error "cleanup failed"
1732     fi
1733     unset I_MOUNTED
1734 }
1735
1736 #######
1737 # General functions
1738
1739 check_network() {
1740     local NETWORK=0
1741     local WAIT=0
1742     local MAX=$2
1743     while [ $NETWORK -eq 0 ]; do
1744         ping -c 1 -w 3 $1 > /dev/null
1745         if [ $? -eq 0 ]; then
1746             NETWORK=1
1747         else
1748             WAIT=$((WAIT + 5))
1749             echo "waiting for $1, $((MAX - WAIT)) secs left"
1750             sleep 5
1751         fi
1752         if [ $WAIT -gt $MAX ]; then
1753             echo "Network not available"
1754             exit 1
1755         fi
1756     done
1757 }
1758 check_port() {
1759     while( !($DSH2 $1 "netstat -tna | grep -q $2") ) ; do
1760         sleep 9
1761     done
1762 }
1763
1764 no_dsh() {
1765     shift
1766     eval $@
1767 }
1768
1769 comma_list() {
1770     # the sed converts spaces to commas, but leaves the last space
1771     # alone, so the line doesn't end with a comma.
1772     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
1773 }
1774
1775 # list, excluded are the comma separated lists
1776 exclude_items_from_list () {
1777     local list=$1
1778     local excluded=$2
1779     local item
1780
1781     list=${list//,/ }
1782     for item in ${excluded//,/ }; do
1783         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
1784     done
1785     echo $(comma_list $list) 
1786 }
1787
1788 # list, expand  are the comma separated lists
1789 expand_list () {
1790     local list=${1//,/ }
1791     local expand=${2//,/ }
1792     local expanded=
1793
1794     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
1795     echo $(comma_list $expanded)
1796 }
1797
1798 absolute_path() {
1799     (cd `dirname $1`; echo $PWD/`basename $1`)
1800 }
1801
1802 get_facets () {
1803     local name=$(echo $1 | tr "[:upper:]" "[:lower:]")
1804     local type=$(echo $1 | tr "[:lower:]" "[:upper:]")
1805
1806     local list=""
1807     local count=${type}COUNT
1808     for ((i=1; i<=${!count}; i++)) do
1809         list="$list ${name}$i"
1810     done
1811     echo $(comma_list $list)
1812 }
1813
1814 ##################################
1815 # Adaptive Timeouts funcs
1816
1817 at_is_valid() {
1818     if [ -z "$AT_MAX_PATH" ]; then
1819         AT_MAX_PATH=$(do_facet $SINGLEMDS "find /sys/ -name at_max")
1820         [ -z "$AT_MAX_PATH" ] && echo "missing /sys/.../at_max " && return 1
1821     fi
1822     return 0
1823 }
1824
1825 at_is_enabled() {
1826     at_is_valid || error "invalid call"
1827
1828     # only check mds, we assume at_max is the same on all nodes
1829     local at_max=$(do_facet $SINGLEMDS "cat $AT_MAX_PATH")
1830     if [ $at_max -eq 0 ]; then
1831         return 1
1832     else
1833         return 0
1834     fi
1835 }
1836
1837 at_max_get() {
1838     local facet=$1
1839
1840     at_is_valid || error "invalid call"
1841
1842     # suppose that all ost-s has the same at_max set
1843     if [ $facet == "ost" ]; then
1844         do_facet ost1 "cat $AT_MAX_PATH"
1845     else
1846         do_facet $facet "cat $AT_MAX_PATH"
1847     fi
1848 }
1849
1850 at_max_set() {
1851     local at_max=$1
1852     shift
1853
1854     at_is_valid || error "invalid call"
1855
1856     local facet
1857     for facet in $@; do
1858         if [ $facet == "ost" ]; then
1859             for i in `seq $OSTCOUNT`; do
1860                 do_facet ost$i "echo $at_max > $AT_MAX_PATH"
1861             done
1862         elif [ $facet == "mds" ]; then
1863             for i in `seq $MDSCOUNT`; do
1864                 do_facet mds$i "echo $at_max > $AT_MAX_PATH"
1865             done
1866         else
1867             do_facet $facet "echo $at_max > $AT_MAX_PATH"
1868         fi
1869     done
1870 }
1871
1872 ##################################
1873 # OBD_FAIL funcs
1874
1875 drop_request() {
1876 # OBD_FAIL_MDS_ALL_REQUEST_NET
1877     RC=0
1878     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
1879     do_facet client "$1" || RC=$?
1880     do_facet $SINGLEMDS lctl set_param fail_loc=0
1881     return $RC
1882 }
1883
1884 drop_reply() {
1885 # OBD_FAIL_MDS_ALL_REPLY_NET
1886     RC=0
1887     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
1888     do_facet client "$@" || RC=$?
1889     do_facet $SINGLEMDS lctl set_param fail_loc=0
1890     return $RC
1891 }
1892
1893 drop_reint_reply() {
1894 # OBD_FAIL_MDS_REINT_NET_REP
1895     RC=0
1896     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
1897     do_facet client "$@" || RC=$?
1898     do_facet $SINGLEMDS lctl set_param fail_loc=0
1899     return $RC
1900 }
1901
1902 pause_bulk() {
1903 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
1904     RC=0
1905     do_facet ost1 lctl set_param fail_loc=0x214
1906     do_facet client "$1" || RC=$?
1907     do_facet client "sync"
1908     do_facet ost1 lctl set_param fail_loc=0
1909     return $RC
1910 }
1911
1912 drop_ldlm_cancel() {
1913 #define OBD_FAIL_LDLM_CANCEL             0x304
1914     RC=0
1915     do_facet client lctl set_param fail_loc=0x304
1916     do_facet client "$@" || RC=$?
1917     do_facet client lctl set_param fail_loc=0
1918     return $RC
1919 }
1920
1921 drop_bl_callback() {
1922 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
1923     RC=0
1924     do_facet client lctl set_param fail_loc=0x305
1925     do_facet client "$@" || RC=$?
1926     do_facet client lctl set_param fail_loc=0
1927     return $RC
1928 }
1929
1930 drop_ldlm_reply() {
1931 #define OBD_FAIL_LDLM_REPLY              0x30c
1932     RC=0
1933     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
1934     do_facet client "$@" || RC=$?
1935     do_facet $SINGLEMDS lctl set_param fail_loc=0
1936     return $RC
1937 }
1938
1939 clear_failloc() {
1940     facet=$1
1941     pause=$2
1942     sleep $pause
1943     echo "clearing fail_loc on $facet"
1944     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
1945 }
1946
1947 set_nodes_failloc () {
1948     local nodes=$1
1949     local node
1950
1951     for node in $nodes ; do
1952         do_node $node lctl set_param fail_loc=$2
1953     done
1954 }
1955
1956 cancel_lru_locks() {
1957     $LCTL mark "cancel_lru_locks $1 start"
1958     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
1959         $LCTL set_param -n $d=clear
1960     done
1961     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
1962     $LCTL mark "cancel_lru_locks $1 stop"
1963 }
1964
1965 default_lru_size()
1966 {
1967         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
1968         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
1969         echo "$DEFAULT_LRU_SIZE"
1970 }
1971
1972 lru_resize_enable()
1973 {
1974     lctl set_param ldlm.namespaces.*$1*.lru_size=0
1975 }
1976
1977 lru_resize_disable()
1978 {
1979     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
1980 }
1981
1982 pgcache_empty() {
1983     local FILE
1984     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
1985         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
1986             echo there is still data in page cache $FILE ?
1987             lctl get_param -n $FILE
1988             return 1
1989         fi
1990     done
1991     return 0
1992 }
1993
1994 debugsave() {
1995     DEBUGSAVE="$(lctl get_param -n debug)"
1996 }
1997
1998 debugrestore() {
1999     [ -n "$DEBUGSAVE" ] && lctl set_param debug="${DEBUGSAVE}"
2000     DEBUGSAVE=""
2001 }
2002
2003 ##################################
2004 # Test interface
2005 ##################################
2006
2007 error_noexit() {
2008     local TYPE=${TYPE:-"FAIL"}
2009     local ERRLOG
2010     lctl set_param fail_loc=0 2>/dev/null || true
2011     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
2012     ERRLOG=$TMP/lustre_${TESTSUITE}_${TESTNAME}.$(date +%s)
2013     echo "Dumping lctl log to $ERRLOG"
2014     # We need to dump the logs on all nodes
2015     local NODES=$(nodes_list)
2016     for NODE in $NODES; do
2017         do_node $NODE $LCTL dk $ERRLOG
2018     done
2019     debugrestore
2020     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
2021     TEST_FAILED=true
2022 }
2023
2024 error() {
2025     error_noexit "$@"
2026     $FAIL_ON_ERROR && exit 1 || true
2027 }
2028
2029 error_exit() {
2030     error_noexit "$@"
2031     exit 1
2032 }
2033
2034 # use only if we are ignoring failures for this test, bugno required.
2035 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
2036 # e.g. error_ignore 5494 "your message"
2037 error_ignore() {
2038     local TYPE="IGNORE (bz$1)"
2039     shift
2040     error_noexit "$@"
2041 }
2042
2043 skip () {
2044         log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
2045         [ "$TESTSUITELOG" ] && \
2046                 echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
2047 }
2048
2049 build_test_filter() {
2050     [ "$ONLY" ] && log "only running test `echo $ONLY`"
2051     for O in $ONLY; do
2052         eval ONLY_${O}=true
2053     done
2054     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
2055         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
2056     [ "$EXCEPT_SLOW" ] && \
2057         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
2058     for E in $EXCEPT $ALWAYS_EXCEPT; do
2059         eval EXCEPT_${E}=true
2060     done
2061     for E in $EXCEPT_SLOW; do
2062         eval EXCEPT_SLOW_${E}=true
2063     done
2064     for G in $GRANT_CHECK_LIST; do
2065         eval GCHECK_ONLY_${G}=true
2066         done
2067 }
2068
2069 _basetest() {
2070     echo $*
2071 }
2072
2073 basetest() {
2074     IFS=abcdefghijklmnopqrstuvwxyz _basetest $1
2075 }
2076
2077 # print a newline if the last test was skipped
2078 export LAST_SKIPPED=
2079 run_test() {
2080     assert_DIR
2081
2082     export base=`basetest $1`
2083     if [ ! -z "$ONLY" ]; then
2084         testname=ONLY_$1
2085         if [ ${!testname}x != x ]; then
2086             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2087             run_one $1 "$2"
2088             return $?
2089         fi
2090         testname=ONLY_$base
2091         if [ ${!testname}x != x ]; then
2092             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2093             run_one $1 "$2"
2094             return $?
2095         fi
2096         LAST_SKIPPED="y"
2097         echo -n "."
2098         return 0
2099     fi
2100     testname=EXCEPT_$1
2101     if [ ${!testname}x != x ]; then
2102         LAST_SKIPPED="y"
2103         TESTNAME=test_$1 skip "skipping excluded test $1"
2104         return 0
2105     fi
2106     testname=EXCEPT_$base
2107     if [ ${!testname}x != x ]; then
2108         LAST_SKIPPED="y"
2109         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
2110         return 0
2111     fi
2112     testname=EXCEPT_SLOW_$1
2113     if [ ${!testname}x != x ]; then
2114         LAST_SKIPPED="y"
2115         TESTNAME=test_$1 skip "skipping SLOW test $1"
2116         return 0
2117     fi
2118     testname=EXCEPT_SLOW_$base
2119     if [ ${!testname}x != x ]; then
2120         LAST_SKIPPED="y"
2121         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
2122         return 0
2123     fi
2124
2125     LAST_SKIPPED=
2126     run_one $1 "$2"
2127
2128     return $?
2129 }
2130
2131 EQUALS="======================================================================"
2132 equals_msg() {
2133     msg="$@"
2134
2135     local suffixlen=$((${#EQUALS} - ${#msg}))
2136     [ $suffixlen -lt 5 ] && suffixlen=5
2137     log `echo $(printf '===== %s %.*s\n' "$msg" $suffixlen $EQUALS)`
2138 }
2139
2140 log() {
2141     echo "$*"
2142     lsmod | grep lnet > /dev/null || load_modules
2143
2144     local MSG="$*"
2145     # Get rid of '
2146     MSG=${MSG//\'/\\\'}
2147     MSG=${MSG//\(/\\\(}
2148     MSG=${MSG//\)/\\\)}
2149     MSG=${MSG//\;/\\\;}
2150     MSG=${MSG//\|/\\\|}
2151     MSG=${MSG//\>/\\\>}
2152     MSG=${MSG//\</\\\<}
2153     MSG=${MSG//\//\\\/}
2154     local NODES=$(nodes_list)
2155     for NODE in $NODES; do
2156         do_node $NODE $LCTL mark "$MSG" 2> /dev/null || true
2157     done
2158 }
2159
2160 trace() {
2161         log "STARTING: $*"
2162         strace -o $TMP/$1.strace -ttt $*
2163         RC=$?
2164         log "FINISHED: $*: rc $RC"
2165         return 1
2166 }
2167
2168 pass() {
2169     $TEST_FAILED && echo -n "FAIL " || echo -n "PASS " 
2170     echo $@
2171 }
2172
2173 check_mds() {
2174     FFREE=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filesfree | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2175     FTOTAL=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filestotal | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2176     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
2177 }
2178
2179 reset_fail_loc () {
2180     local myNODES=$(nodes_list)
2181     local NODE
2182
2183     echo -n "Resetting fail_loc on all nodes..."
2184     for NODE in $myNODES; do
2185         do_node $NODE "lctl set_param -n fail_loc=0 2>/dev/null || true"
2186     done
2187     echo done.
2188 }
2189
2190 run_one() {
2191     testnum=$1
2192     message=$2
2193     tfile=f${testnum}
2194     export tdir=d0.${TESTSUITE}/d${base}
2195
2196     local SAVE_UMASK=`umask`
2197     umask 0022
2198
2199     local BEFORE=`date +%s`
2200     echo
2201     log "== test $testnum: $message == `date +%H:%M:%S` ($BEFORE)"
2202     #check_mds
2203     export TESTNAME=test_$testnum
2204     TEST_FAILED=false
2205     test_${testnum} || error "test_$testnum failed with $?"
2206     #check_mds
2207     cd $SAVE_PWD
2208     reset_fail_loc
2209     check_grant ${testnum} || error "check_grant $testnum failed with $?"
2210     check_catastrophe || error "LBUG/LASSERT detected"
2211     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
2212     pass "($((`date +%s` - $BEFORE))s)"
2213     TEST_FAILED=false
2214     unset TESTNAME
2215     unset tdir
2216     umask $SAVE_UMASK
2217 }
2218
2219 canonical_path() {
2220     (cd `dirname $1`; echo $PWD/`basename $1`)
2221 }
2222
2223 sync_clients() {
2224     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
2225     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
2226         cd $SAVE_PWD
2227 }
2228
2229 check_grant() {
2230     export base=`basetest $1`
2231     [ "$CHECK_GRANT" == "no" ] && return 0
2232
2233         testname=GCHECK_ONLY_${base}
2234         [ ${!testname}x == x ] && return 0
2235
2236     echo -n "checking grant......"
2237         cd $SAVE_PWD
2238         # write some data to sync client lost_grant
2239         rm -f $DIR1/${tfile}_check_grant_* 2>&1
2240         for i in `seq $OSTCOUNT`; do
2241                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
2242                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
2243                                               count=1 > /dev/null 2>&1
2244         done
2245         # sync all the data and make sure no pending data on server
2246         sync_clients
2247         
2248         #get client grant and server grant
2249         client_grant=0
2250     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
2251                 client_grant=$((client_grant + $d))
2252         done
2253         server_grant=0
2254         for d in `lctl get_param -n obdfilter.*.tot_granted`; do
2255                 server_grant=$((server_grant + $d))
2256         done
2257
2258         # cleanup the check_grant file
2259         for i in `seq $OSTCOUNT`; do
2260                 rm $DIR1/${tfile}_check_grant_$i
2261         done
2262
2263         #check whether client grant == server grant
2264         if [ $client_grant != $server_grant ]; then
2265                 echo "failed: client:${client_grant} server: ${server_grant}"
2266                 return 1
2267         else
2268                 echo "pass"
2269         fi
2270 }
2271
2272 ########################
2273 # helper functions
2274
2275 osc_to_ost()
2276 {
2277     osc=$1
2278     ost=`echo $1 | awk -F_ '{print $3}'`
2279     if [ -z $ost ]; then
2280         ost=`echo $1 | sed 's/-osc.*//'`
2281     fi
2282     echo $ost
2283 }
2284
2285 remote_node () {
2286     local node=$1
2287     [ "$node" != "$(hostname)" ]
2288 }
2289
2290 remote_mds ()
2291 {
2292     local node
2293     for node in $(mdts_nodes); do
2294         remote_node $node && return 0
2295     done
2296     return 1
2297 }
2298
2299 remote_mds_nodsh()
2300 {
2301     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
2302 }
2303
2304 remote_ost ()
2305 {
2306     local node
2307     for node in $(osts_nodes) ; do
2308         remote_node $node && return 0
2309     done
2310     return 1
2311 }
2312
2313 remote_ost_nodsh()
2314 {
2315     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2316 }
2317
2318 remote_mgs_nodsh()
2319 {
2320     local MGS 
2321     MGS=$(facet_host mgs)
2322     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2323 }
2324
2325 mdts_nodes () {
2326     local MDSNODES
2327     local NODES_sort
2328     for num in `seq $MDSCOUNT`; do
2329         MDSNODES="$MDSNODES $(facet_host mds$num)"
2330     done
2331     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
2332
2333     echo $NODES_sort
2334 }
2335
2336 remote_servers () {
2337     remote_ost && remote_mds
2338 }
2339
2340 osts_nodes () {
2341     local OSTNODES=$(facet_host ost1)
2342     local NODES_sort
2343
2344     for num in `seq $OSTCOUNT`; do
2345         local myOST=$(facet_host ost$num)
2346         OSTNODES="$OSTNODES $myOST"
2347     done
2348     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
2349
2350     echo $NODES_sort
2351 }
2352
2353 nodes_list () {
2354     # FIXME. We need a list of clients
2355     local myNODES=$HOSTNAME
2356     local myNODES_sort
2357
2358     # CLIENTS (if specified) contains the local client
2359     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
2360
2361     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
2362         myNODES="$myNODES $(osts_nodes) $(mdts_nodes)"
2363     fi
2364
2365     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
2366
2367     echo $myNODES_sort
2368 }
2369
2370 remote_nodes_list () {
2371     local rnodes=$(nodes_list)
2372     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2373     echo $rnodes
2374 }
2375
2376 init_clients_lists () {
2377     # Sanity check: exclude the local client from RCLIENTS
2378     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2379
2380     # Sanity check: exclude the dup entries
2381     rclients=$(for i in $rclients; do echo $i; done | sort -u)
2382
2383     local clients="$SINGLECLIENT $HOSTNAME $rclients"
2384
2385     # Sanity check: exclude the dup entries from CLIENTS
2386     # for those configs which has SINGLCLIENT set to local client
2387     clients=$(for i in $clients; do echo $i; done | sort -u)
2388
2389     CLIENTS=`comma_list $clients`
2390     local -a remoteclients=($rclients)
2391     for ((i=0; $i<${#remoteclients[@]}; i++)); do
2392             varname=CLIENT$((i + 2))
2393             eval $varname=${remoteclients[i]}
2394     done
2395
2396     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
2397 }
2398
2399 get_random_entry () {
2400     local rnodes=$1
2401
2402     rnodes=${rnodes//,/ }
2403
2404     local -a nodes=($rnodes)
2405     local num=${#nodes[@]} 
2406     local i=$((RANDOM * num * 2 / 65536))
2407
2408     echo ${nodes[i]}
2409 }
2410
2411 is_patchless ()
2412 {
2413     lctl get_param version | grep -q patchless
2414 }
2415
2416 check_versions () {
2417     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
2418 }
2419
2420 get_node_count() {
2421     local nodes="$@"
2422     echo $nodes | wc -w || true
2423 }
2424
2425 mixed_ost_devs () {
2426     local nodes=$(osts_nodes)
2427     local osscount=$(get_node_count "$nodes")
2428     [ ! "$OSTCOUNT" = "$osscount" ]
2429 }
2430
2431 mixed_mdt_devs () {
2432     local nodes=$(mdts_nodes)
2433     local mdtcount=$(get_node_count "$nodes")
2434     [ ! "$MDSCOUNT" = "$mdtcount" ]
2435 }
2436
2437 generate_machine_file() {
2438     local nodes=${1//,/ }
2439     local machinefile=$2
2440     rm -f $machinefile || error "can't rm $machinefile"
2441     for node in $nodes; do
2442         echo $node >>$machinefile
2443     done
2444 }
2445
2446 get_stripe () {
2447     local file=$1/stripe
2448     touch $file
2449     $LFS getstripe -v $file || error
2450     rm -f $file
2451 }
2452
2453 check_runas_id_ret() {
2454     local myRC=0
2455     local myRUNAS_UID=$1
2456     local myRUNAS_GID=$2
2457     shift 2
2458     local myRUNAS=$@
2459     if [ -z "$myRUNAS" ]; then
2460         error_exit "myRUNAS command must be specified for check_runas_id"
2461     fi
2462     if $GSS_KRB5; then
2463         $myRUNAS krb5_login.sh || \
2464             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
2465     fi
2466     mkdir $DIR/d0_runas_test
2467     chmod 0755 $DIR
2468     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
2469     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
2470     rm -rf $DIR/d0_runas_test
2471     return $myRC
2472 }
2473
2474 check_runas_id() {
2475     local myRUNAS_UID=$1
2476     local myRUNAS_GID=$2
2477     shift 2
2478     local myRUNAS=$@
2479     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
2480         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
2481         Please set RUNAS_ID to some UID which exists on MDS and client or
2482         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
2483 }
2484
2485 # Run multiop in the background, but wait for it to print
2486 # "PAUSING" to its stdout before returning from this function.
2487 multiop_bg_pause() {
2488     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
2489     FILE=$1
2490     ARGS=$2
2491
2492     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
2493     mkfifo $TMPPIPE
2494
2495     echo "$MULTIOP_PROG $FILE v$ARGS"
2496     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
2497
2498     echo "TMPPIPE=${TMPPIPE}"
2499     read -t 60 multiop_output < $TMPPIPE
2500     if [ $? -ne 0 ]; then
2501         rm -f $TMPPIPE
2502         return 1
2503     fi
2504     rm -f $TMPPIPE
2505     if [ "$multiop_output" != "PAUSING" ]; then
2506         echo "Incorrect multiop output: $multiop_output"
2507         kill -9 $PID
2508         return 1
2509     fi
2510
2511     return 0
2512 }
2513
2514 inodes_available () {
2515     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
2516     echo $IFree
2517 }
2518
2519 # reset llite stat counters
2520 clear_llite_stats(){
2521         lctl set_param -n llite.*.stats 0
2522 }
2523
2524 # sum llite stat items
2525 calc_llite_stats() {
2526         local res=$(lctl get_param -n llite.*.stats |
2527                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
2528         echo $res
2529 }
2530
2531 # reset osc stat counters
2532 clear_osc_stats(){
2533         lctl set_param -n osc.*.osc_stats 0
2534 }
2535
2536 # sum osc stat items
2537 calc_osc_stats() {
2538         local res=$(lctl get_param -n osc.*.osc_stats |
2539                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
2540         echo $res
2541 }
2542
2543 calc_sum () {
2544         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
2545 }
2546
2547 calc_osc_kbytes () {
2548         df $MOUNT > /dev/null
2549         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
2550 }
2551
2552 # save_lustre_params(node, parameter_mask)
2553 # generate a stream of formatted strings (<node> <param name>=<param value>)
2554 save_lustre_params() {
2555         local s
2556         do_node $1 "lctl get_param $2" | while read s; do echo "$1 $s"; done
2557 }
2558
2559 # restore lustre parameters from input stream, produces by save_lustre_params
2560 restore_lustre_params() {
2561         local node
2562         local name
2563         local val
2564         while IFS=" =" read node name val; do
2565                 do_node $node "lctl set_param -n $name $val"
2566         done
2567 }
2568
2569 check_catastrophe() {
2570     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
2571     local C=$CATASTROPHE
2572     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
2573
2574     if [ $rnodes ]; then
2575         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
2576 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
2577 exit \\\$rc;"
2578     fi 
2579 }
2580
2581 # $1 node
2582 # $2 file
2583 # $3 $RUNAS
2584 get_stripe_info() {
2585         local tmp_file
2586
2587         stripe_size=0
2588         stripe_count=0
2589         stripe_index=0
2590         tmp_file=$(mktemp)
2591
2592         do_facet $1 $3 lfs getstripe -v $2 > $tmp_file
2593
2594         stripe_size=`awk '$1 ~ /size/ {print $2}' $tmp_file`
2595         stripe_count=`awk '$1 ~ /count/ {print $2}' $tmp_file`
2596         stripe_index=`awk '/obdidx/ {start = 1; getline; print $1; exit}' $tmp_file`
2597         rm -f $tmp_file
2598 }
2599
2600 # CMD: determine mds index where directory inode presents
2601 get_mds_dir () {
2602     local dir=$1
2603     local file=$dir/f0.get_mds_dir_tmpfile
2604
2605     rm -f $file
2606     sleep 1
2607     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
2608     local oldused=($iused)
2609
2610     touch $file
2611     sleep 1
2612     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
2613     local newused=($iused)
2614
2615     local num=0
2616     for ((i=0; i<${#newused[@]}; i++)); do
2617          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
2618              echo $(( i + 1 ))
2619              rm -f $file
2620              return 0
2621          fi
2622     done
2623     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
2624 }
2625
2626 mpi_run () {
2627     local mpirun="$MPIRUN $MPIRUN_OPTIONS"
2628     local command="$mpirun $@"
2629     local mpilog=$TMP/mpi.log
2630     local rc
2631
2632     if [ "$MPI_USER" != root -a $mpirun ]; then
2633         echo "+ chmod 0777 $MOUNT"
2634         chmod 0777 $MOUNT
2635         command="su $MPI_USER sh -c \"$command \""
2636     fi
2637
2638     ls -ald $MOUNT
2639     echo "+ $command"
2640     eval $command 2>&1 > $mpilog || true
2641
2642     rc=${PIPESTATUS[0]}
2643     if [ $rc -eq 0 ] && grep -q "p4_error: : [^0]" $mpilog ; then
2644        rc=1
2645     fi
2646     cat $mpilog
2647     return $rc
2648 }
2649
2650 mdsrate_cleanup () {
2651     mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
2652 }
2653
2654 delayed_recovery_enabled () {
2655     local var=${SINGLEMDS}_svc
2656     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
2657 }
2658