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