Whamcloud - gitweb
b=16799
[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 VERBOSE=false
11 export GMNALNID=${GMNALNID:-/usr/sbin/gmlndnid}
12 export CATASTROPHE=${CATASTROPHE:-/proc/sys/lnet/catastrophe}
13 export GSS=false
14 export GSS_KRB5=false
15 export GSS_PIPEFS=false
16 export IDENTITY_UPCALL=default
17 #export PDSH="pdsh -S -Rssh -w"
18
19 # eg, assert_env LUSTRE MDSNODES OSTNODES CLIENTS
20 assert_env() {
21     local failed=""
22     for name in $@; do
23         if [ -z "${!name}" ]; then
24             echo "$0: $name must be set"
25             failed=1
26         fi
27     done
28     [ $failed ] && exit 1 || true
29 }
30
31 assert_DIR () {
32     local failed=""
33     [ -z "`echo :$DIR: | grep :$MOUNT:`" ] && \
34         failed=1 && echo "DIR not in $MOUNT. Aborting."
35     [ -z "`echo :$DIR1: | grep :$MOUNT1:`" ] && \
36         failed=1 && echo "DIR1 not in $MOUNT1. Aborting."
37     [ -z "`echo :$DIR2: | grep :$MOUNT2:`" ] && \
38         failed=1 && echo "DIR2 not in $MOUNT2. Aborting"
39
40     [ -n "$failed" ] && exit 99 || true
41 }
42
43 usage() {
44     echo "usage: $0 [-r] [-f cfgfile]"
45     echo "       -r: reformat"
46
47     exit
48 }
49
50 print_summary () {
51     [ "$TESTSUITE" == "lfscktest" ] && return 0
52     [ -n "$ONLY" ] && echo "WARNING: ONLY is set to ${ONLY}."
53     local form="%-13s %-17s %s\n"
54     printf "$form" "status" "script" "skipped tests E(xcluded) S(low)"
55     echo "------------------------------------------------------------------------------------"
56     for O in $TESTSUITE_LIST; do
57         local skipped=""
58         local slow=""
59         local o=$(echo $O | tr "[:upper:]" "[:lower:]")
60         o=${o//_/-}
61         o=${o//tyn/tyN}
62         local log=${TMP}/${o}.log
63         [ -f $log ] && skipped=$(grep excluded $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
64         [ -f $log ] && slow=$(grep SLOW $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
65         [ "${!O}" = "done" ] && \
66             printf "$form" "Done" "$O" "E=$skipped" && \
67             [ -n "$slow" ] && printf "$form" "-" "-" "S=$slow"
68
69     done
70
71     for O in $TESTSUITE_LIST; do
72         [ "${!O}" = "no" ] && \
73             printf "$form" "Skipped" "$O" ""
74     done
75
76     for O in $TESTSUITE_LIST; do
77         [ "${!O}" = "done" -o "${!O}" = "no" ] || \
78             printf "$form" "UNFINISHED" "$O" ""
79     done
80 }
81
82 init_test_env() {
83     export LUSTRE=`absolute_path $LUSTRE`
84     export TESTSUITE=`basename $0 .sh`
85
86     #[ -d /r ] && export ROOT=${ROOT:-/r}
87     export TMP=${TMP:-$ROOT/tmp}
88     export TESTSUITELOG=${TMP}/${TESTSUITE}.log
89     export HOSTNAME=${HOSTNAME:-`hostname`}
90     if ! echo $PATH | grep -q $LUSTRE/utils; then
91         export PATH=$PATH:$LUSTRE/utils
92     fi
93     if ! echo $PATH | grep -q $LUSTRE/utils/gss; then
94         export PATH=$PATH:$LUSTRE/utils/gss
95     fi
96     if ! echo $PATH | grep -q $LUSTRE/tests; then
97         export PATH=$PATH:$LUSTRE/tests
98     fi
99     export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
100     [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
101     export LFS=${LFS:-"$LUSTRE/utils/lfs"}
102     [ ! -f "$LFS" ] && export LFS=$(which lfs)
103     export L_GETIDENTITY=${L_GETIDENTITY:-"$LUSTRE/utils/l_getidentity"}
104     if [ ! -f "$L_GETIDENTITY" ]; then
105         if `which l_getidentity > /dev/null 2>&1`; then
106             export L_GETIDENTITY=$(which l_getidentity)
107         else
108             export L_GETIDENTITY=NONE
109         fi
110     fi
111     export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
112     [ ! -f "$MKFS" ] && export MKFS=$(which mkfs.lustre)
113     export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
114     [ ! -f "$TUNEFS" ] && export TUNEFS=$(which tunefs.lustre)
115     export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
116     export FSYTPE=${FSTYPE:-"ldiskfs"}
117     export NAME=${NAME:-local}
118     export LPROC=/proc/fs/lustre
119     export LGSSD=${LGSSD:-"$LUSTRE/utils/gss/lgssd"}
120     [ "$GSS_PIPEFS" = "true" ] && [ ! -f "$LGSSD" ] && \
121         export LGSSD=$(which lgssd)
122     export LSVCGSSD=${LSVCGSSD:-"$LUSTRE/utils/gss/lsvcgssd"}
123     [ ! -f "$LSVCGSSD" ] && export LSVCGSSD=$(which lsvcgssd)
124     export KRB5DIR=${KRB5DIR:-"/usr/kerberos"}
125     export DIR2
126     export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
127     export AT_MAX_PATH
128
129     if [ "$ACCEPTOR_PORT" ]; then
130         export PORT_OPT="--port $ACCEPTOR_PORT"
131     fi
132
133     case "x$SEC" in
134         xkrb5*)
135             echo "Using GSS/krb5 ptlrpc security flavor"
136             which lgss_keyring > /dev/null 2>&1 || \
137                 error "built with gss disabled! SEC=$SEC"
138             GSS=true
139             GSS_KRB5=true
140             ;;
141     esac
142
143     case "x$IDUP" in
144         xtrue)
145             IDENTITY_UPCALL=true
146             ;;
147         xfalse)
148             IDENTITY_UPCALL=false
149             ;;
150     esac
151
152     # Paths on remote nodes, if different
153     export RLUSTRE=${RLUSTRE:-$LUSTRE}
154     export RPWD=${RPWD:-$PWD}
155     export I_MOUNTED=${I_MOUNTED:-"no"}
156
157     # command line
158
159     while getopts "rvf:" opt $*; do
160         case $opt in
161             f) CONFIG=$OPTARG;;
162             r) REFORMAT=--reformat;;
163             v) VERBOSE=true;;
164             \?) usage;;
165         esac
166     done
167
168     shift $((OPTIND - 1))
169     ONLY=${ONLY:-$*}
170
171     [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
172     rm -f $TMP/*active
173
174 }
175
176 load_module() {
177     EXT=".ko"
178     module=$1
179     shift
180     BASE=`basename $module $EXT`
181     lsmod | grep -q ${BASE} || \
182       if [ -f ${LUSTRE}/${module}${EXT} ]; then
183         insmod ${LUSTRE}/${module}${EXT} $@
184     else
185         # must be testing a "make install" or "rpm" installation
186         # note failed to load ptlrpc_gss is considered not fatal
187         if [ "$BASE" == "ptlrpc_gss" ]; then
188             modprobe $BASE $@ 2>/dev/null || echo "gss/krb5 is not supported"
189         else
190             modprobe $BASE $@
191         fi
192     fi
193 }
194
195 load_modules() {
196     if [ -n "$MODPROBE" ]; then
197         # use modprobe
198     return 0
199     fi
200     if [ "$HAVE_MODULES" = true ]; then
201     # we already loaded
202         return 0
203     fi
204     HAVE_MODULES=true
205
206     echo Loading modules from $LUSTRE
207     load_module ../libcfs/libcfs/libcfs
208     [ "$PTLDEBUG" ] && lctl set_param debug=$PTLDEBUG
209     [ "$SUBSYSTEM" ] && lctl set_param subsystem_debug=${SUBSYSTEM# }
210     [ -f /etc/modprobe.conf ] && MODPROBECONF=/etc/modprobe.conf
211     [ -f /etc/modprobe.d/Lustre ] && MODPROBECONF=/etc/modprobe.d/Lustre
212     [ -z "$LNETOPTS" -a -n "$MODPROBECONF" ] && \
213         LNETOPTS=$(awk '/^options lnet/ { print $0}' $MODPROBECONF | sed 's/^options lnet //g')
214     echo "lnet options: '$LNETOPTS'"
215     # note that insmod will ignore anything in modprobe.conf
216     load_module ../lnet/lnet/lnet $LNETOPTS
217     LNETLND=${LNETLND:-"socklnd/ksocklnd"}
218     load_module ../lnet/klnds/$LNETLND
219     load_module lvfs/lvfs
220     load_module obdclass/obdclass
221     load_module ptlrpc/ptlrpc
222     load_module ptlrpc/gss/ptlrpc_gss
223     # Now, some modules depend on lquota without USE_QUOTA check,
224     # will fix later. Disable check "$USE_QUOTA" = "yes" temporary.
225     #[ "$USE_QUOTA" = "yes" ] && load_module quota/lquota
226     load_module quota/lquota
227     load_module fid/fid
228     load_module fld/fld
229     load_module lmv/lmv
230     load_module mdc/mdc
231     load_module osc/osc
232     load_module lov/lov
233     load_module mgc/mgc
234     if [ -z "$CLIENTONLY" ] && [ -z "$CLIENTMODSONLY" ]; then
235         grep -q crc16 /proc/kallsyms || { modprobe crc16 2>/dev/null || true; }
236         [ "$FSTYPE" = "ldiskfs" ] && load_module ../ldiskfs/ldiskfs/ldiskfs
237         load_module mgs/mgs
238         load_module mds/mds
239         load_module mdd/mdd
240         load_module mdt/mdt
241         load_module lvfs/fsfilt_$FSTYPE
242         load_module cmm/cmm
243         load_module osd/osd
244         load_module ost/ost
245         load_module obdfilter/obdfilter
246     fi
247
248     load_module llite/lustre
249     load_module llite/llite_lloop
250     rm -f $TMP/ogdb-$HOSTNAME
251     OGDB=$TMP
252     [ -d /r ] && OGDB="/r/tmp"
253     $LCTL modules > $OGDB/ogdb-$HOSTNAME
254
255     # 'mount' doesn't look in $PATH, just sbin
256     [ -f $LUSTRE/utils/mount.lustre ] && cp $LUSTRE/utils/mount.lustre /sbin/. || true
257 }
258
259 RMMOD=rmmod
260 if [ `uname -r | cut -c 3` -eq 4 ]; then
261     RMMOD="modprobe -r"
262 fi
263
264 wait_for_lnet() {
265     local UNLOADED=0
266     local WAIT=0
267     local MAX=60
268     MODULES=$($LCTL modules | awk '{ print $2 }')
269     while [ -n "$MODULES" ]; do
270     sleep 5
271     $RMMOD $MODULES > /dev/null 2>&1 || true
272     MODULES=$($LCTL modules | awk '{ print $2 }')
273         if [ -z "$MODULES" ]; then
274         return 0
275         else
276             WAIT=$((WAIT + 5))
277             echo "waiting, $((MAX - WAIT)) secs left"
278         fi
279         if [ $WAIT -eq $MAX ]; then
280             echo "LNET modules $MODULES will not unload"
281         lsmod
282             return 3
283         fi
284     done
285 }
286
287 unload_dep_module() {
288     #lsmod output
289     #libcfs                107852  17 llite_lloop,lustre,obdfilter,ost,...
290     local MODULE=$1
291     local DEPS=$(lsmod | awk '($1 == "'$MODULE'") { print $4 }' | tr ',' ' ')
292     for SUBMOD in $DEPS; do
293         unload_dep_module $SUBMOD
294     done
295     [ "$MODULE" = "libcfs" ] && $LCTL dk $TMP/debug || true
296     $RMMOD $MODULE || true
297 }
298
299 check_mem_leak () {
300     LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
301     LEAK_PORTALS=$(dmesg | tail -n 20 | grep "Portals memory leaked" || true)
302     if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
303         echo "$LEAK_LUSTRE" 1>&2
304         echo "$LEAK_PORTALS" 1>&2
305         mv $TMP/debug $TMP/debug-leak.`date +%s` || true
306         log "Memory leaks detected"
307         [ -n "$IGNORE_LEAK" ] && { echo "ignoring leaks" && return 0; } || true
308         return 1
309     fi
310 }
311
312 unload_modules() {
313     wait_exit_ST client # bug 12845
314
315     lsmod | grep libcfs > /dev/null && $LCTL dl
316     unload_dep_module $FSTYPE
317     unload_dep_module libcfs
318
319     local MODULES=$($LCTL modules | awk '{ print $2 }')
320     if [ -n "$MODULES" ]; then
321         echo "Modules still loaded: "
322         echo $MODULES 
323         if [ "$(lctl dl)" ]; then
324             echo "Lustre still loaded"
325             lctl dl || true
326             lsmod
327             return 2
328         else
329             echo "Lustre stopped but LNET is still loaded, waiting..."
330             wait_for_lnet || return 3
331         fi
332
333     fi
334     HAVE_MODULES=false
335
336     check_mem_leak || return 254
337
338     echo "modules unloaded."
339     return 0
340 }
341
342 check_gss_daemon_facet() {
343     facet=$1
344     dname=$2
345
346     num=`do_facet $facet ps -o cmd -C $dname | grep $dname | wc -l`
347     if [ $num -ne 1 ]; then
348         echo "$num instance of $dname on $facet"
349         return 1
350     fi
351     return 0
352 }
353
354 send_sigint() {
355     local facet=$1
356     shift
357     do_facet $facet "killall -2 $@ 2>/dev/null || true"
358 }
359
360 start_gss_daemons() {
361     # starting on MDT
362     for num in `seq $MDSCOUNT`; do
363         do_facet mds$num "$LSVCGSSD -v"
364         if $GSS_PIPEFS; then
365             do_facet mds$num "$LGSSD -v"
366         fi
367     done
368     # starting on OSTs
369     for num in `seq $OSTCOUNT`; do
370         do_facet ost$num "$LSVCGSSD -v"
371     done
372     # starting on client
373     # FIXME: is "client" the right facet name?
374     if $GSS_PIPEFS; then
375         do_facet client "$LGSSD -v"
376     fi
377
378     # wait daemons entering "stable" status
379     sleep 5
380
381     #
382     # check daemons are running
383     #
384     for num in `seq $MDSCOUNT`; do
385         check_gss_daemon_facet mds$num lsvcgssd
386         if $GSS_PIPEFS; then
387             check_gss_daemon_facet mds$num lgssd
388         fi
389     done
390     for num in `seq $OSTCOUNT`; do
391         check_gss_daemon_facet ost$num lsvcgssd
392     done
393     if $GSS_PIPEFS; then
394         check_gss_daemon_facet client lgssd
395     fi
396 }
397
398 stop_gss_daemons() {
399     for num in `seq $MDSCOUNT`; do
400         send_sigint mds$num lsvcgssd lgssd
401     done
402     for num in `seq $OSTCOUNT`; do
403         send_sigint ost$num lsvcgssd
404     done
405     send_sigint client lgssd
406 }
407
408 init_gss() {
409     if $GSS; then
410         start_gss_daemons
411     fi
412 }
413
414 cleanup_gss() {
415     if $GSS; then
416         stop_gss_daemons
417         # maybe cleanup credential cache?
418     fi
419 }
420
421 mdsdevlabel() {
422     local num=$1
423     local device=`mdsdevname $num`
424     local label=`do_facet mds$num "e2label ${device}" | grep -v "CMD: "`
425     echo -n $label
426 }
427
428 ostdevlabel() {
429     local num=$1
430     local device=`ostdevname $num`
431     local label=`do_facet ost$num "e2label ${device}" | grep -v "CMD: "`
432     echo -n $label
433 }
434
435 # Facet functions
436 mount_facet() {
437     local facet=$1
438     shift
439     local dev=${facet}_dev
440     local opt=${facet}_opt
441     echo "Starting ${facet}: ${!opt} $@ ${!dev} ${MOUNT%/*}/${facet}"
442     do_facet ${facet} mount -t lustre ${!opt} $@ ${!dev} ${MOUNT%/*}/${facet}     
443     RC=${PIPESTATUS[0]}
444     if [ $RC -ne 0 ]; then
445         echo "mount -t lustre $@ ${!dev} ${MOUNT%/*}/${facet}"
446         echo "Start of ${!dev} on ${facet} failed ${RC}"
447     else
448         do_facet ${facet} "lctl set_param debug=$PTLDEBUG; \
449             lctl set_param subsystem_debug=${SUBSYSTEM# }; \
450             lctl set_param debug_mb=${DEBUG_SIZE}; \
451             sync"
452  
453         label=$(do_facet ${facet} "e2label ${!dev}")
454         [ -z "$label" ] && echo no label for ${!dev} && exit 1
455         eval export ${facet}_svc=${label}
456         echo Started ${label}
457     fi
458     return $RC
459 }
460
461 # start facet device options
462 start() {
463     facet=$1
464     shift
465     device=$1
466     shift
467     eval export ${facet}_dev=${device}
468     eval export ${facet}_opt=\"$@\"
469     do_facet ${facet} mkdir -p ${MOUNT%/*}/${facet}
470     mount_facet ${facet}
471     RC=$?
472     return $RC
473 }
474
475 stop() {
476     local running
477     facet=$1
478     shift
479     HOST=`facet_active_host $facet`
480     [ -z $HOST ] && echo stop: no host for $facet && return 0
481
482     running=$(do_facet ${facet} "grep -c ${MOUNT%/*}/${facet}' ' /proc/mounts") || true
483     if [ ${running} -ne 0 ]; then
484         echo "Stopping ${MOUNT%/*}/${facet} (opts:$@)"
485         do_facet ${facet} umount -d $@ ${MOUNT%/*}/${facet}
486     fi
487
488     # umount should block, but we should wait for unrelated obd's
489     # like the MGS or MGC to also stop.
490     wait_exit_ST ${facet}
491 }
492
493 zconf_mount() {
494     local OPTIONS
495     local client=$1
496     local mnt=$2
497     # Only supply -o to mount if we have options
498     if [ -n "$MOUNTOPT" ]; then
499         OPTIONS="-o $MOUNTOPT"
500     fi
501     local device=$MGSNID:/$FSNAME
502     if [ -z "$mnt" -o -z "$FSNAME" ]; then
503         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
504         exit 1
505     fi
506
507     echo "Starting client: $client: $OPTIONS $device $mnt"
508     do_node $client mkdir -p $mnt
509     do_node $client mount -t lustre $OPTIONS $device $mnt || return 1
510
511     do_node $client "lctl set_param debug=$PTLDEBUG;
512         lctl set_param subsystem_debug=${SUBSYSTEM# };
513         lctl set_param debug_mb=${DEBUG_SIZE}"
514     
515     return 0
516 }
517
518 zconf_umount() {
519     local client=$1
520     local mnt=$2
521     [ "$3" ] && force=-f
522     local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
523     if [ $running -ne 0 ]; then
524         echo "Stopping client $client $mnt (opts:$force)"
525         lsof | grep "$mnt" || true
526         do_node $client umount $force $mnt
527     fi
528 }
529
530 # mount clients if not mouted
531 zconf_mount_clients() {
532     local OPTIONS
533     local clients=$1
534     local mnt=$2
535
536
537     # Only supply -o to mount if we have options
538     if [ -n "$MOUNTOPT" ]; then
539         OPTIONS="-o $MOUNTOPT"
540     fi
541     local device=$MGSNID:/$FSNAME
542     if [ -z "$mnt" -o -z "$FSNAME" ]; then
543         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
544         exit 1
545     fi
546
547     echo "Starting client $clients: $OPTIONS $device $mnt"
548     do_nodes $clients "mount | grep $mnt || { mkdir -p $mnt && mount -t lustre $OPTIONS $device $mnt || false; }"
549
550     echo "Started clients $clients: "
551     do_nodes $clients "mount | grep $mnt"
552
553     do_nodes $clients "lctl set_param debug=$PTLDEBUG;
554         lctl set_param subsystem_debug=${SUBSYSTEM# };
555         lctl set_param debug_mb=${DEBUG_SIZE};"
556
557     return 0
558 }
559
560 zconf_umount_clients() {
561     local clients=$1
562     local mnt=$2
563     [ "$3" ] && force=-f
564
565     echo "Umounting clients: $clients"
566     echo "Stopping clients: $clients $mnt (opts:$force)"
567     do_nodes $clients umount $force $mnt
568 }
569
570 shutdown_facet() {
571     facet=$1
572     if [ "$FAILURE_MODE" = HARD ]; then
573         $POWER_DOWN `facet_active_host $facet`
574         sleep 2
575     elif [ "$FAILURE_MODE" = SOFT ]; then
576         stop $facet
577     fi
578 }
579
580 reboot_facet() {
581     facet=$1
582     if [ "$FAILURE_MODE" = HARD ]; then
583         $POWER_UP `facet_active_host $facet`
584     else
585         sleep 10
586     fi
587 }
588
589 # verify that lustre actually cleaned up properly
590 cleanup_check() {
591     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
592         error "LBUG/LASSERT detected"
593     BUSY=`dmesg | grep -i destruct || true`
594     if [ "$BUSY" ]; then
595         echo "$BUSY" 1>&2
596         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
597         exit 205
598     fi
599
600     check_mem_leak || exit 204
601
602     [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl && \
603         echo "$0: lustre didn't clean up..." 1>&2 && return 202 || true
604
605     if [ "`/sbin/lsmod 2>&1 | egrep 'lnet|libcfs'`" ]; then
606         echo "$0: modules still loaded..." 1>&2
607         /sbin/lsmod 1>&2
608         return 203
609     fi
610     return 0
611 }
612
613 wait_delete_completed () {
614     local TOTALPREV=`lctl get_param -n osc.*.kbytesavail | \
615                      awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
616
617     local WAIT=0
618     local MAX_WAIT=20
619     while [ "$WAIT" -ne "$MAX_WAIT" ]; do
620         sleep 1
621         TOTAL=`lctl get_param -n osc.*.kbytesavail | \
622                awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
623         [ "$TOTAL" -eq "$TOTALPREV" ] && break
624         echo "Waiting delete completed ... prev: $TOTALPREV current: $TOTAL "
625         TOTALPREV=$TOTAL
626         WAIT=$(( WAIT + 1))
627     done
628     echo "Delete completed."
629 }
630
631 wait_for_host() {
632     HOST=$1
633     check_network "$HOST" 900
634     while ! do_node $HOST "ls -d $LUSTRE " > /dev/null; do sleep 5; done
635 }
636
637 wait_for() {
638     facet=$1
639     HOST=`facet_active_host $facet`
640     wait_for_host $HOST
641 }
642
643 wait_mds_recovery_done () {
644     local timeout=`do_facet mds lctl get_param  -n timeout`
645 #define OBD_RECOVERY_TIMEOUT (obd_timeout * 5 / 2)
646 # as we are in process of changing obd_timeout in different ways
647 # let's set MAX longer than that
648     MAX=$(( timeout * 4 ))
649     WAIT=0
650     while [ $WAIT -lt $MAX ]; do
651         STATUS=`do_facet $SINGLEMDS "lctl get_param -n mdt.*-MDT*.recovery_status | grep status"`
652         echo $STATUS | grep COMPLETE && return 0
653         sleep 5
654         WAIT=$((WAIT + 5))
655         echo "Waiting $(($MAX - $WAIT)) secs for MDS recovery done"
656     done
657     echo "MDS recovery not done in $MAX sec"
658     return 1
659 }
660
661 wait_exit_ST () {
662     local facet=$1
663
664     local WAIT=0
665     local INTERVAL=1
666     # conf-sanity 31 takes a long time cleanup
667     while [ $WAIT -lt 300 ]; do
668         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
669         [ -z "${running}" ] && return 0
670         echo "waited $WAIT for${running}"
671         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
672         sleep $INTERVAL
673         WAIT=$((WAIT + INTERVAL))
674     done
675     echo "service didn't stop after $WAIT seconds.  Still running:"
676     echo ${running}
677     return 1
678 }
679
680 wait_remote_prog () {
681    local prog=$1
682    local WAIT=0
683    local INTERVAL=5
684    local rc=0
685
686    [ "$PDSH" = "no_dsh" ] && return 0
687    
688    while [ $WAIT -lt $2 ]; do
689         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep)
690         [ -z "${running}" ] && return 0
691         echo "waited $WAIT for: "
692         echo "$running"
693         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
694         sleep $INTERVAL
695         WAIT=$((WAIT + INTERVAL))
696     done
697     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
698     [ -z "$pids" ] && return 0
699     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
700     for pid in $pids; do
701         cat /proc/${pid}/status || true
702         cat /proc/${pid}/wchan || true
703         echo "Killing $pid"
704         kill -9 $pid || true
705         sleep 1
706         ps -P $pid && rc=1 
707     done
708
709     return $rc
710 }
711
712 client_df() {
713     # not every config has many clients
714     if [ ! -z "$CLIENTS" ]; then
715         $PDSH $CLIENTS "df $MOUNT" > /dev/null
716     else
717         df $MOUNT > /dev/null
718     fi
719 }
720
721 client_reconnect() {
722     uname -n >> $MOUNT/recon
723     if [ -z "$CLIENTS" ]; then
724         df $MOUNT; uname -n >> $MOUNT/recon
725     else
726         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
727     fi
728     echo Connected clients:
729     cat $MOUNT/recon
730     ls -l $MOUNT/recon > /dev/null
731     rm $MOUNT/recon
732 }
733
734 facet_failover() {
735     facet=$1
736     echo "Failing $facet on node `facet_active_host $facet`"
737     shutdown_facet $facet
738     reboot_facet $facet
739     client_df &
740     DFPID=$!
741     echo "df pid is $DFPID"
742     change_active $facet
743     TO=`facet_active_host $facet`
744     echo "Failover $facet to $TO"
745     wait_for $facet
746     mount_facet $facet || error "Restart of $facet failed"
747 }
748
749 obd_name() {
750     local facet=$1
751 }
752
753 replay_barrier() {
754     local facet=$1
755     do_facet $facet sync
756     df $MOUNT
757     local svc=${facet}_svc
758     do_facet $facet $LCTL --device %${!svc} readonly
759     do_facet $facet $LCTL --device %${!svc} notransno
760     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
761     $LCTL mark "local REPLAY BARRIER on ${!svc}"
762 }
763
764 replay_barrier_nodf() {
765     local facet=$1    echo running=${running}
766     do_facet $facet sync
767     local svc=${facet}_svc
768     echo Replay barrier on ${!svc}
769     do_facet $facet $LCTL --device %${!svc} readonly
770     do_facet $facet $LCTL --device %${!svc} notransno
771     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
772     $LCTL mark "local REPLAY BARRIER on ${!svc}"
773 }
774
775 mds_evict_client() {
776     UUID=`lctl get_param -n mdc.${mds1_svc}-mdc-*.uuid`
777     do_facet mds1 "lctl set_param -n mdt.${mds1_svc}.evict_client $UUID"
778 }
779
780 ost_evict_client() {
781     UUID=`lctl get_param -n devices| grep ${ost1_svc}-osc- | egrep -v 'MDT' | awk '{print $5}'`
782     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
783 }
784
785 fail() {
786     facet_failover $* || error "failover: $?"
787     df $MOUNT || error "post-failover df: $?"
788 }
789
790 fail_nodf() {
791         local facet=$1
792         facet_failover $facet
793 }
794
795 fail_abort() {
796     local facet=$1
797     stop $facet
798     change_active $facet
799     mount_facet $facet -o abort_recovery
800     df $MOUNT || echo "first df failed: $?"
801     sleep 1
802     df $MOUNT || error "post-failover df: $?"
803 }
804
805 do_lmc() {
806     echo There is no lmc.  This is mountconf, baby.
807     exit 1
808 }
809
810 h2gm () {
811     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
812         ID=`$PDSH $1 $GMNALNID -l | cut -d\  -f2`
813         echo $ID"@gm"
814     fi
815 }
816
817 h2name_or_ip() {
818     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
819         echo $1"@$2"
820     fi
821 }
822
823 h2ptl() {
824    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
825        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
826        if [ -z "$ID" ]; then
827            echo "Could not get a ptl id for $1..."
828            exit 1
829        fi
830        echo $ID"@ptl"
831    fi
832 }
833 declare -fx h2ptl
834
835 h2tcp() {
836     h2name_or_ip "$1" "tcp"
837 }
838 declare -fx h2tcp
839
840 h2elan() {
841     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
842         if type __h2elan >/dev/null 2>&1; then
843             ID=$(__h2elan $1)
844         else
845             ID=`echo $1 | sed 's/[^0-9]*//g'`
846         fi
847         echo $ID"@elan"
848     fi
849 }
850 declare -fx h2elan
851
852 h2openib() {
853     h2name_or_ip "$1" "openib"
854 }
855 declare -fx h2openib
856
857 h2o2ib() {
858     h2name_or_ip "$1" "o2ib"
859 }
860 declare -fx h2o2ib
861
862 facet_host() {
863     local facet=$1
864     varname=${facet}_HOST
865     if [ -z "${!varname}" ]; then
866         if [ "${facet:0:3}" == "ost" ]; then
867             eval ${facet}_HOST=${ost_HOST}
868         fi
869     fi
870     echo -n ${!varname}
871 }
872
873 facet_active() {
874     local facet=$1
875     local activevar=${facet}active
876
877     if [ -f $TMP/${facet}active ] ; then
878         source $TMP/${facet}active
879     fi
880
881     active=${!activevar}
882     if [ -z "$active" ] ; then
883         echo -n ${facet}
884     else
885         echo -n ${active}
886     fi
887 }
888
889 facet_active_host() {
890     local facet=$1
891     local active=`facet_active $facet`
892     if [ "$facet" == client ]; then
893         echo $HOSTNAME
894     else
895         echo `facet_host $active`
896     fi
897 }
898
899 change_active() {
900     local facet=$1
901     failover=${facet}failover
902     host=`facet_host $failover`
903     [ -z "$host" ] && return
904     curactive=`facet_active $facet`
905     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
906         eval export ${facet}active=$facet
907     else
908         eval export ${facet}active=$failover
909     fi
910     # save the active host for this facet
911     activevar=${facet}active
912     echo "$activevar=${!activevar}" > $TMP/$activevar
913 }
914
915 do_node() {
916     HOST=$1
917     shift
918     local myPDSH=$PDSH
919     if [ "$HOST" = "$HOSTNAME" ]; then
920         myPDSH="no_dsh"
921     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
922         echo "cannot run remote command on $HOST with $myPDSH"
923         return 128
924     fi
925     if $VERBOSE; then
926         echo "CMD: $HOST $@" >&2
927         $myPDSH $HOST $LCTL mark "$@" > /dev/null 2>&1 || :
928     fi
929
930     if [ "$myPDSH" = "rsh" ]; then
931 # we need this because rsh does not return exit code of an executed command
932         local command_status="$TMP/cs"
933         rsh $HOST ":> $command_status"
934         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
935                     cd $RPWD; sh -c \"$@\") || 
936                     echo command failed >$command_status"
937         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
938         return 0
939     fi
940     $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed "s/^${HOST}: //"
941     return ${PIPESTATUS[0]}
942 }
943
944 do_nodes() {
945     local rnodes=$1
946     shift
947
948     # This is part from do_node
949     local myPDSH=$PDSH
950
951     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
952         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
953
954     if $VERBOSE; then
955         echo "CMD: $rnodes $@" >&2
956         $myPDSH $rnodes $LCTL mark "$@" > /dev/null 2>&1 || :
957     fi
958
959     $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed -re "s/\w+:\s//g"
960     return ${PIPESTATUS[0]}
961 }
962
963 do_facet() {
964     facet=$1
965     shift
966     HOST=`facet_active_host $facet`
967     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
968     do_node $HOST "$@"
969 }
970
971 add() {
972     local facet=$1
973     shift
974     # make sure its not already running
975     stop ${facet} -f
976     rm -f $TMP/${facet}active
977     do_facet ${facet} $MKFS $*
978 }
979
980 ostdevname() {
981     num=$1
982     DEVNAME=OSTDEV$num
983     #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
984     eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}}
985     echo -n $DEVPTR
986 }
987
988 mdsdevname() {
989     num=$1
990     DEVNAME=MDSDEV$num
991     #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
992     eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}}
993     echo -n $DEVPTR
994 }
995
996 ########
997 ## MountConf setup
998
999 stopall() {
1000     # make sure we are using the primary server, so test-framework will
1001     # be able to clean up properly.
1002     activemds=`facet_active mds1`
1003     if [ $activemds != "mds1" ]; then
1004         fail mds1
1005     fi
1006
1007     # assume client mount is local
1008     grep " $MOUNT " /proc/mounts && zconf_umount $HOSTNAME $MOUNT $*
1009     grep " $MOUNT2 " /proc/mounts && zconf_umount $HOSTNAME $MOUNT2 $*
1010
1011     if [ -n "$CLIENTS" ]; then
1012             zconf_umount_clients $CLIENTS $MOUNT "$*" || true
1013             [ -n "$MOUNT2" ] && zconf_umount_clients $CLIENTS $MOUNT2 "$*" || true
1014     fi
1015
1016     [ "$CLIENTONLY" ] && return
1017     # The add fn does rm ${facet}active file, this would be enough
1018     # if we use do_facet <facet> only after the facet added, but
1019     # currently we use do_facet mds in local.sh
1020     for num in `seq $MDSCOUNT`; do
1021         stop mds$num -f
1022         rm -f ${TMP}/mds${num}active
1023     done
1024
1025     for num in `seq $OSTCOUNT`; do
1026         stop ost$num -f
1027         rm -f $TMP/ost${num}active
1028     done
1029
1030     return 0
1031 }
1032
1033 cleanupall() {
1034     stopall $*
1035     unload_modules
1036     cleanup_gss
1037 }
1038
1039 mdsmkfsopts()
1040 {
1041     local nr=$1
1042     test $nr = 1 && echo -n $MDS_MKFS_OPTS || echo -n $MDSn_MKFS_OPTS
1043 }
1044
1045 formatall() {
1046     [ "$FSTYPE" ] && FSTYPE_OPT="--backfstype $FSTYPE"
1047
1048     if [ ! -z $SEC ]; then
1049         MDS_MKFS_OPTS="$MDS_MKFS_OPTS --param srpc.flavor.default=$SEC"
1050         OST_MKFS_OPTS="$OST_MKFS_OPTS --param srpc.flavor.default=$SEC"
1051     fi
1052
1053     stopall
1054     # We need ldiskfs here, may as well load them all
1055     load_modules
1056     [ "$CLIENTONLY" ] && return
1057     echo "Formatting mdts, osts"
1058     for num in `seq $MDSCOUNT`; do
1059         echo "Format mds$num: $(mdsdevname $num)"
1060         if $VERBOSE; then
1061             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` || exit 9
1062         else
1063             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` > /dev/null || exit 9
1064         fi
1065     done
1066
1067     for num in `seq $OSTCOUNT`; do
1068         echo "Format ost$num: $(ostdevname $num)"
1069         if $VERBOSE; then
1070             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` || exit 10
1071         else
1072             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` > /dev/null || exit 10
1073         fi
1074     done
1075 }
1076
1077 mount_client() {
1078     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
1079 }
1080
1081 umount_client() {
1082     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
1083 }
1084
1085 # return value:
1086 # 0: success, the old identity set already.
1087 # 1: success, the old identity does not set.
1088 # 2: fail.
1089 switch_identity() {
1090     local num=$1
1091     local switch=$2
1092     local j=`expr $num - 1`
1093     local MDT="`do_facet mds$num lctl get_param -N mdt.*MDT*$j | cut -d"." -f2 2>/dev/null || true`"
1094
1095     if [ -z "$MDT" ]; then
1096         return 2
1097     fi
1098
1099     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
1100
1101     if $switch; then
1102         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
1103     else
1104         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
1105     fi
1106
1107     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush \"-1\""
1108
1109     if [ $old = "NONE" ]; then
1110         return 1
1111     else
1112         return 0
1113     fi
1114 }
1115
1116 remount_client()
1117 {
1118         zconf_umount `hostname` $1 || error "umount failed"
1119         zconf_mount `hostname` $1 || error "mount failed"
1120 }
1121
1122 set_obd_timeout() {
1123     local facet=$1
1124     local timeout=$2
1125
1126     do_facet $facet lsmod | grep -q obdclass || \
1127         do_facet $facet "modprobe obdclass"
1128
1129     do_facet $facet "lctl set_param timeout=$timeout"
1130 }
1131
1132 setupall() {
1133     load_modules
1134     init_gss
1135     if [ -z "$CLIENTONLY" ]; then
1136         echo "Setup mdts, osts"
1137         for num in `seq $MDSCOUNT`; do
1138             DEVNAME=$(mdsdevname $num)
1139             echo $REFORMAT | grep -q "reformat" \
1140             || do_facet mds$num "$TUNEFS --writeconf $DEVNAME"
1141             set_obd_timeout mds$num $TIMEOUT
1142             start mds$num $DEVNAME $MDS_MOUNT_OPTS
1143
1144             # We started mds, now we should set failover variables properly.
1145             # Set mds${num}failover_HOST if it is not set (the default failnode).
1146             local varname=mds${num}failover_HOST
1147             if [ -z "${!varname}" ]; then
1148                 eval mds${num}failover_HOST=$(facet_host mds$num)
1149             fi
1150
1151             if [ $IDENTITY_UPCALL != "default" ]; then
1152                 switch_identity $num $IDENTITY_UPCALL
1153             fi
1154         done
1155         for num in `seq $OSTCOUNT`; do
1156             DEVNAME=$(ostdevname $num)
1157             set_obd_timeout ost$num $TIMEOUT
1158             start ost$num $DEVNAME $OST_MOUNT_OPTS
1159
1160             # We started ost$num, now we should set ost${num}failover variable properly.
1161             # Set ost${num}failover_HOST if it is not set (the default failnode).
1162             varname=ost${num}failover_HOST
1163             if [ -z "${!varname}" ]; then
1164                 eval ost${num}failover_HOST=$(facet_host ost${num})
1165             fi
1166
1167         done
1168     fi
1169     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
1170     mount_client $MOUNT
1171     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
1172
1173     if [ "$MOUNT_2" ]; then
1174         mount_client $MOUNT2
1175         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
1176     fi
1177
1178     # by remounting mdt before ost, initial connect from mdt to ost might
1179     # timeout because ost is not ready yet. wait some time to its fully
1180     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
1181     # by a context negotiation rpc with $TIMEOUT.
1182     # FIXME better by monitoring import status.
1183     if $GSS; then
1184         sleep $((TIMEOUT + 5))
1185     else
1186         sleep 5
1187     fi
1188 }
1189
1190 mounted_lustre_filesystems() {
1191         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
1192 }
1193
1194 check_and_setup_lustre() {
1195     MOUNTED="`mounted_lustre_filesystems`"
1196     if [ -z "$MOUNTED" ]; then
1197         [ "$REFORMAT" ] && formatall
1198         setupall
1199         MOUNTED="`mounted_lustre_filesystems`"
1200         [ -z "$MOUNTED" ] && error "NAME=$NAME not mounted"
1201         export I_MOUNTED=yes
1202     fi
1203     if [ "$ONLY" == "setup" ]; then
1204         exit 0
1205     fi
1206 }
1207
1208 cleanup_and_setup_lustre() {
1209     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
1210         lctl set_param debug=0 || true
1211         cleanupall
1212         if [ "$ONLY" == "cleanup" ]; then
1213             exit 0
1214         fi
1215     fi
1216     check_and_setup_lustre
1217 }
1218
1219 check_and_cleanup_lustre() {
1220     if [ "`mount | grep $MOUNT`" ]; then
1221         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
1222     fi
1223     if [ "$I_MOUNTED" = "yes" ]; then
1224         cleanupall -f || error "cleanup failed"
1225     fi
1226     unset I_MOUNTED
1227 }
1228
1229 #######
1230 # General functions
1231
1232 check_network() {
1233     local NETWORK=0
1234     local WAIT=0
1235     local MAX=$2
1236     while [ $NETWORK -eq 0 ]; do
1237         ping -c 1 -w 3 $1 > /dev/null
1238         if [ $? -eq 0 ]; then
1239             NETWORK=1
1240         else
1241             WAIT=$((WAIT + 5))
1242             echo "waiting for $1, $((MAX - WAIT)) secs left"
1243             sleep 5
1244         fi
1245         if [ $WAIT -gt $MAX ]; then
1246             echo "Network not available"
1247             exit 1
1248         fi
1249     done
1250 }
1251 check_port() {
1252     while( !($DSH2 $1 "netstat -tna | grep -q $2") ) ; do
1253         sleep 9
1254     done
1255 }
1256
1257 no_dsh() {
1258     shift
1259     eval $@
1260 }
1261
1262 comma_list() {
1263     # the sed converts spaces to commas, but leaves the last space
1264     # alone, so the line doesn't end with a comma.
1265     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
1266 }
1267
1268 absolute_path() {
1269     (cd `dirname $1`; echo $PWD/`basename $1`)
1270 }
1271
1272 ##################################
1273 # Adaptive Timeouts funcs
1274
1275 at_is_valid() {
1276     if [ -z "$AT_MAX_PATH" ]; then
1277         AT_MAX_PATH=$(do_facet mds "find /sys/ -name at_max")
1278         [ -z "$AT_MAX_PATH" ] && echo "missing /sys/.../at_max " && return 1
1279     fi
1280     return 0
1281 }
1282
1283 at_is_enabled() {
1284     at_is_valid || error "invalid call"
1285
1286     # only check mds, we assume at_max is the same on all nodes
1287     local at_max=$(do_facet mds "cat $AT_MAX_PATH")
1288     if [ $at_max -eq 0 ]; then
1289         return 1
1290     else
1291         return 0
1292     fi
1293 }
1294
1295 at_max_get() {
1296     local facet=$1
1297
1298     at_is_valid || error "invalid call"
1299
1300     # suppose that all ost-s has the same at_max set
1301     if [ $facet == "ost" ]; then
1302         do_facet ost1 "cat $AT_MAX_PATH"
1303     else
1304         do_facet $facet "cat $AT_MAX_PATH"
1305     fi
1306 }
1307
1308 at_max_set() {
1309     local at_max=$1
1310     shift
1311
1312     at_is_valid || error "invalid call"
1313
1314     local facet
1315     for facet in $@; do
1316         if [ $facet == "ost" ]; then
1317             for i in `seq $OSTCOUNT`; do
1318                 do_facet ost$i "echo $at_max > $AT_MAX_PATH"
1319             done
1320         elif [ $facet == "mds" ]; then
1321             for i in `seq $MDSCOUNT`; do
1322                 do_facet mds$i "echo $at_max > $AT_MAX_PATH"
1323             done
1324         else
1325             do_facet $facet "echo $at_max > $AT_MAX_PATH"
1326         fi
1327     done
1328 }
1329
1330 ##################################
1331 # OBD_FAIL funcs
1332
1333 drop_request() {
1334 # OBD_FAIL_MDS_ALL_REQUEST_NET
1335     RC=0
1336     do_facet mds lctl set_param fail_loc=0x123
1337     do_facet client "$1" || RC=$?
1338     do_facet mds lctl set_param fail_loc=0
1339     return $RC
1340 }
1341
1342 drop_reply() {
1343 # OBD_FAIL_MDS_ALL_REPLY_NET
1344     RC=0
1345     do_facet mds lctl set_param fail_loc=0x122
1346     do_facet client "$@" || RC=$?
1347     do_facet mds lctl set_param fail_loc=0
1348     return $RC
1349 }
1350
1351 drop_reint_reply() {
1352 # OBD_FAIL_MDS_REINT_NET_REP
1353     RC=0
1354     do_facet mds lctl set_param fail_loc=0x119
1355     do_facet client "$@" || RC=$?
1356     do_facet mds lctl set_param fail_loc=0
1357     return $RC
1358 }
1359
1360 pause_bulk() {
1361 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
1362     RC=0
1363     do_facet ost1 lctl set_param fail_loc=0x214
1364     do_facet client "$1" || RC=$?
1365     do_facet client "sync"
1366     do_facet ost1 lctl set_param fail_loc=0
1367     return $RC
1368 }
1369
1370 drop_ldlm_cancel() {
1371 #define OBD_FAIL_LDLM_CANCEL             0x304
1372     RC=0
1373     do_facet client lctl set_param fail_loc=0x304
1374     do_facet client "$@" || RC=$?
1375     do_facet client lctl set_param fail_loc=0
1376     return $RC
1377 }
1378
1379 drop_bl_callback() {
1380 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
1381     RC=0
1382     do_facet client lctl set_param fail_loc=0x305
1383     do_facet client "$@" || RC=$?
1384     do_facet client lctl set_param fail_loc=0
1385     return $RC
1386 }
1387
1388 drop_ldlm_reply() {
1389 #define OBD_FAIL_LDLM_REPLY              0x30c
1390     RC=0
1391     do_facet mds lctl set_param fail_loc=0x30c
1392     do_facet client "$@" || RC=$?
1393     do_facet mds lctl set_param fail_loc=0
1394     return $RC
1395 }
1396
1397 clear_failloc() {
1398     facet=$1
1399     pause=$2
1400     sleep $pause
1401     echo "clearing fail_loc on $facet"
1402     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
1403 }
1404
1405 set_nodes_failloc () {
1406     local nodes=$1
1407     local node
1408
1409     for node in $nodes ; do
1410         do_node $node lctl set_param fail_loc=$2
1411     done
1412 }
1413
1414 set_nodes_failloc () {
1415     local nodes=$1
1416     local node
1417
1418     for node in $nodes ; do
1419         do_node $node lctl set_param fail_loc=$2
1420     done
1421 }
1422
1423 cancel_lru_locks() {
1424     $LCTL mark "cancel_lru_locks $1 start"
1425     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
1426         $LCTL set_param -n $d=clear
1427     done
1428     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
1429     $LCTL mark "cancel_lru_locks $1 stop"
1430 }
1431
1432 default_lru_size()
1433 {
1434         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
1435         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
1436         echo "$DEFAULT_LRU_SIZE"
1437 }
1438
1439 lru_resize_enable()
1440 {
1441     lctl set_param ldlm.namespaces.*$1*.lru_size=0
1442 }
1443
1444 lru_resize_disable()
1445 {
1446     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
1447 }
1448
1449 pgcache_empty() {
1450     local FILE
1451     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
1452         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
1453             echo there is still data in page cache $FILE ?
1454             lctl get_param -n $FILE
1455             return 1
1456         fi
1457     done
1458     return 0
1459 }
1460
1461 debugsave() {
1462     DEBUGSAVE="$(lctl get_param -n debug)"
1463 }
1464
1465 debugrestore() {
1466     [ -n "$DEBUGSAVE" ] && lctl set_param debug="${DEBUGSAVE}"
1467     DEBUGSAVE=""
1468 }
1469
1470 ##################################
1471 # Test interface
1472 ##################################
1473
1474 error_noexit() {
1475     local TYPE=${TYPE:-"FAIL"}
1476     local ERRLOG
1477     lctl set_param fail_loc=0 2>/dev/null || true
1478     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
1479     ERRLOG=$TMP/lustre_${TESTSUITE}_${TESTNAME}.$(date +%s)
1480     echo "Dumping lctl log to $ERRLOG"
1481     # We need to dump the logs on all nodes
1482     local NODES=$(nodes_list)
1483     for NODE in $NODES; do
1484         do_node $NODE $LCTL dk $ERRLOG
1485     done
1486     debugrestore
1487     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
1488 }
1489
1490 error() {
1491     error_noexit "$@"
1492     $FAIL_ON_ERROR && exit 1 || true
1493 }
1494
1495 error_exit() {
1496     error_noexit "$@"
1497     exit 1
1498 }
1499
1500 # use only if we are ignoring failures for this test, bugno required.
1501 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
1502 # e.g. error_ignore 5494 "your message"
1503 error_ignore() {
1504     local TYPE="IGNORE (bz$1)"
1505     shift
1506     error_noexit "$@"
1507 }
1508
1509 skip () {
1510         log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
1511         [ "$TESTSUITELOG" ] && \
1512                 echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
1513 }
1514
1515 build_test_filter() {
1516     [ "$ONLY" ] && log "only running test `echo $ONLY`"
1517     for O in $ONLY; do
1518         eval ONLY_${O}=true
1519     done
1520     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
1521         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
1522     [ "$EXCEPT_SLOW" ] && \
1523         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
1524     for E in $EXCEPT $ALWAYS_EXCEPT; do
1525         eval EXCEPT_${E}=true
1526     done
1527     for E in $EXCEPT_SLOW; do
1528         eval EXCEPT_SLOW_${E}=true
1529     done
1530     for G in $GRANT_CHECK_LIST; do
1531         eval GCHECK_ONLY_${G}=true
1532         done
1533 }
1534
1535 _basetest() {
1536     echo $*
1537 }
1538
1539 basetest() {
1540     IFS=abcdefghijklmnopqrstuvwxyz _basetest $1
1541 }
1542
1543 run_test() {
1544     assert_DIR
1545
1546     export base=`basetest $1`
1547     if [ ! -z "$ONLY" ]; then
1548         testname=ONLY_$1
1549         if [ ${!testname}x != x ]; then
1550             run_one $1 "$2"
1551             return $?
1552         fi
1553         testname=ONLY_$base
1554         if [ ${!testname}x != x ]; then
1555             run_one $1 "$2"
1556             return $?
1557         fi
1558         echo -n "."
1559         return 0
1560     fi
1561     testname=EXCEPT_$1
1562     if [ ${!testname}x != x ]; then
1563         TESTNAME=test_$1 skip "skipping excluded test $1"
1564         return 0
1565     fi
1566     testname=EXCEPT_$base
1567     if [ ${!testname}x != x ]; then
1568         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
1569         return 0
1570     fi
1571     testname=EXCEPT_SLOW_$1
1572     if [ ${!testname}x != x ]; then
1573         TESTNAME=test_$1 skip "skipping SLOW test $1"
1574         return 0
1575     fi
1576     testname=EXCEPT_SLOW_$base
1577     if [ ${!testname}x != x ]; then
1578         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
1579         return 0
1580     fi
1581
1582     run_one $1 "$2"
1583
1584     return $?
1585 }
1586
1587 EQUALS="======================================================================"
1588 equals_msg() {
1589     msg="$@"
1590
1591     local suffixlen=$((${#EQUALS} - ${#msg}))
1592     [ $suffixlen -lt 5 ] && suffixlen=5
1593     log `echo $(printf '===== %s %.*s\n' "$msg" $suffixlen $EQUALS)`
1594 }
1595
1596 log() {
1597     echo "$*"
1598     lsmod | grep lnet > /dev/null || load_modules
1599
1600     local MSG="$*"
1601     # Get rif of '
1602     MSG=${MSG//\'/\\\'}
1603     MSG=${MSG//\(/\\\(}
1604     MSG=${MSG//\)/\\\)}
1605     MSG=${MSG//\;/\\\;}
1606     MSG=${MSG//\|/\\\|}
1607     MSG=${MSG//\>/\\\>}
1608     MSG=${MSG//\</\\\<}
1609     MSG=${MSG//\//\\\/}
1610     local NODES=$(nodes_list)
1611     for NODE in $NODES; do
1612         do_node $NODE $LCTL mark "$MSG" 2> /dev/null || true
1613     done
1614 }
1615
1616 trace() {
1617         log "STARTING: $*"
1618         strace -o $TMP/$1.strace -ttt $*
1619         RC=$?
1620         log "FINISHED: $*: rc $RC"
1621         return 1
1622 }
1623
1624 pass() {
1625     echo PASS $@
1626 }
1627
1628 check_mds() {
1629     FFREE=`lctl get_param -n osd.*MDT*.filesfree`
1630     FTOTAL=`lctl get_param -n osd.*MDT*.filestotal`
1631     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
1632 }
1633
1634 reset_fail_loc () {
1635     local myNODES=$(nodes_list)
1636     local NODE
1637
1638     for NODE in $myNODES; do
1639         do_node $NODE "lctl set_param fail_loc=0 2>/dev/null || true"
1640     done
1641 }
1642
1643 run_one() {
1644     testnum=$1
1645     message=$2
1646     tfile=f${testnum}
1647     export tdir=d0.${TESTSUITE}/d${base}
1648     local SAVE_UMASK=`umask`
1649     umask 0022
1650
1651     BEFORE=`date +%s`
1652     log "== test $testnum: $message ============ `date +%H:%M:%S` ($BEFORE)"
1653     #check_mds
1654     export TESTNAME=test_$testnum
1655     test_${testnum} || error "test_$testnum failed with $?"
1656     #check_mds
1657     cd $SAVE_PWD
1658     reset_fail_loc
1659     check_grant ${testnum} || error "check_grant $testnum failed with $?"
1660     check_catastrophe || error "LBUG/LASSERT detected"
1661     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
1662     pass "($((`date +%s` - $BEFORE))s)"
1663     unset TESTNAME
1664     unset tdir
1665     umask $SAVE_UMASK
1666     $CLEANUP
1667 }
1668
1669 canonical_path() {
1670     (cd `dirname $1`; echo $PWD/`basename $1`)
1671 }
1672
1673 sync_clients() {
1674     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
1675     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
1676         cd $SAVE_PWD
1677 }
1678
1679 check_grant() {
1680     export base=`basetest $1`
1681     [ "$CHECK_GRANT" == "no" ] && return 0
1682
1683         testname=GCHECK_ONLY_${base}
1684         [ ${!testname}x == x ] && return 0
1685
1686     echo -n "checking grant......"
1687         cd $SAVE_PWD
1688         # write some data to sync client lost_grant
1689         rm -f $DIR1/${tfile}_check_grant_* 2>&1
1690         for i in `seq $OSTCOUNT`; do
1691                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
1692                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
1693                                               count=1 > /dev/null 2>&1
1694         done
1695         # sync all the data and make sure no pending data on server
1696         sync_clients
1697         
1698         #get client grant and server grant
1699         client_grant=0
1700     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
1701                 client_grant=$((client_grant + $d))
1702         done
1703         server_grant=0
1704         for d in `lctl get_param -n obdfilter.*.tot_granted`; do
1705                 server_grant=$((server_grant + $d))
1706         done
1707
1708         # cleanup the check_grant file
1709         for i in `seq $OSTCOUNT`; do
1710                 rm $DIR1/${tfile}_check_grant_$i
1711         done
1712
1713         #check whether client grant == server grant
1714         if [ $client_grant != $server_grant ]; then
1715                 echo "failed: client:${client_grant} server: ${server_grant}"
1716                 return 1
1717         else
1718                 echo "pass"
1719         fi
1720 }
1721
1722 ########################
1723 # helper functions
1724
1725 osc_to_ost()
1726 {
1727     osc=$1
1728     ost=`echo $1 | awk -F_ '{print $3}'`
1729     if [ -z $ost ]; then
1730         ost=`echo $1 | sed 's/-osc.*//'`
1731     fi
1732     echo $ost
1733 }
1734
1735 remote_mds ()
1736 {
1737     [ -z "$(lctl dl | grep mdt)" ]
1738 }
1739
1740 remote_mds_nodsh()
1741 {
1742     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
1743 }
1744
1745 remote_ost ()
1746 {
1747     [ -z "$(lctl dl | grep ost)" ]
1748 }
1749
1750 remote_ost_nodsh()
1751 {
1752     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
1753 }
1754
1755 mdts_nodes () {
1756     local MDSNODES=$(facet_host $SINGLEMDS)
1757     local NODES_sort
1758
1759     # FIXME: Currenly we use only $SINGLEMDS,
1760     # should be fixed when we will start to test cmd.
1761     echo $MDSNODES
1762     return
1763
1764     for num in `seq $MDSCOUNT`; do
1765         local myMDS=$(facet_host mds$num)
1766         MDSNODES="$MDSNODES $myMDS"
1767     done
1768     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
1769
1770     echo $NODES_sort
1771 }
1772
1773 osts_nodes () {
1774     local OSTNODES=$(facet_host ost1)
1775     local NODES_sort
1776
1777     for num in `seq $OSTCOUNT`; do
1778         local myOST=$(facet_host ost$num)
1779         OSTNODES="$OSTNODES $myOST"
1780     done
1781     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
1782
1783     echo $NODES_sort
1784 }
1785
1786 nodes_list () {
1787     # FIXME. We need a list of clients
1788     local myNODES=$HOSTNAME
1789     local myNODES_sort
1790
1791     # CLIENTS (if specified) contains the local client
1792     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
1793
1794     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
1795         myNODES="$myNODES $(osts_nodes) $(mdts_nodes)"
1796     fi
1797
1798     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
1799
1800     echo $myNODES_sort
1801 }
1802
1803 remote_nodes_list () {
1804     local rnodes=$(nodes_list)
1805     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
1806     echo $rnodes 
1807 }
1808
1809 init_clients_lists () {
1810     # Sanity check: exclude the local client from RCLIENTS
1811     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
1812
1813     # Sanity check: exclude the dup entries
1814     rclients=$(for i in $rclients; do echo $i; done | sort -u)
1815
1816     local clients="$SINGLECLIENT $HOSTNAME $rclients"
1817
1818     # Sanity check: exclude the dup entries from CLIENTS
1819     # for those configs which has SINGLCLIENT set to local client 
1820     clients=$(for i in $clients; do echo $i; done | sort -u)
1821
1822     CLIENTS=`comma_list $clients`
1823     local -a remoteclients=($rclients)
1824     for ((i=0; $i<${#remoteclients[@]}; i++)); do
1825             varname=CLIENT$((i + 2))
1826             eval $varname=${remoteclients[i]}
1827     done
1828
1829     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
1830 }
1831
1832 is_patchless ()
1833 {
1834     lctl get_param version | grep -q patchless
1835 }
1836
1837 get_node_count() {
1838    local nodes="$@"
1839    echo $nodes | wc -w || true
1840 }
1841
1842 mixed_ost_devs () {
1843     local nodes=$(osts_nodes)
1844     local osscount=$(get_node_count "$nodes")
1845     [ ! "$OSTCOUNT" = "$osscount" ]
1846 }
1847
1848 check_runas_id_ret() {
1849     local myRC=0
1850     local myRUNAS_ID=$1
1851     shift
1852     local myRUNAS=$@
1853     if [ -z "$myRUNAS" ]; then
1854         error_exit "myRUNAS command must be specified for check_runas_id"
1855     fi
1856     if $GSS_KRB5; then
1857         $myRUNAS krb5_login.sh || \
1858             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
1859     fi
1860     mkdir $DIR/d0_runas_test
1861     chmod 0755 $DIR
1862     chown $myRUNAS_ID:$myRUNAS_ID $DIR/d0_runas_test
1863     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
1864     rm -rf $DIR/d0_runas_test
1865     return $myRC
1866 }
1867
1868 check_runas_id() {
1869     local myRUNAS_ID=$1
1870     shift
1871     local myRUNAS=$@
1872     check_runas_id_ret $myRUNAS_ID $myRUNAS || \
1873         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_ID. 
1874         Please set RUNAS_ID to some UID which exists on MDS and client or 
1875         add user $myRUNAS_ID:$myRUNAS_ID on these nodes."
1876 }
1877
1878 # Run multiop in the background, but wait for it to print
1879 # "PAUSING" to its stdout before returning from this function.
1880 multiop_bg_pause() {
1881     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
1882     FILE=$1
1883     ARGS=$2
1884
1885     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
1886     mkfifo $TMPPIPE
1887
1888     echo "$MULTIOP_PROG $FILE v$ARGS"
1889     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
1890
1891     echo "TMPPIPE=${TMPPIPE}"
1892     read -t 60 multiop_output < $TMPPIPE
1893     if [ $? -ne 0 ]; then
1894         rm -f $TMPPIPE
1895         return 1
1896     fi
1897     rm -f $TMPPIPE
1898     if [ "$multiop_output" != "PAUSING" ]; then
1899         echo "Incorrect multiop output: $multiop_output"
1900         kill -9 $PID
1901         return 1
1902     fi
1903
1904     return 0
1905 }
1906
1907 # reset llite stat counters
1908 clear_llite_stats(){
1909         lctl set_param -n llite.*.stats 0
1910 }
1911
1912 # sum llite stat items
1913 calc_llite_stats() {
1914         local res=$(lctl get_param -n llite.*.stats |
1915                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
1916         echo $res
1917 }
1918
1919 # save_lustre_params(node, parameter_mask)
1920 # generate a stream of formatted strings (<node> <param name>=<param value>)
1921 save_lustre_params() {
1922         local s
1923         do_node $1 "lctl get_param $2" | while read s; do echo "$1 $s"; done
1924 }
1925
1926 # restore lustre parameters from input stream, produces by save_lustre_params
1927 restore_lustre_params() {
1928         local node
1929         local name
1930         local val
1931         while IFS=" =" read node name val; do
1932                 do_node $node "lctl set_param -n $name $val"
1933         done
1934 }
1935
1936 check_catastrophe () {
1937     local rnodes=$(comma_list $(remote_nodes_list))
1938
1939     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && return 1
1940     if [ $rnodes ]; then
1941         do_nodes $rnodes "[ -f $CATASTROPHE ] && { [ \`cat $CATASTROPHE\` -eq 0 ] || false; } || true"
1942     fi 
1943 }
1944