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