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