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