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