Whamcloud - gitweb
b=20057 Add the timestamp back to the test headers.
[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 QUOTA_AUTO=1
19
20 #export PDSH="pdsh -S -Rssh -w"
21
22 # function used by scripts run on remote nodes
23 LUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}
24 . $LUSTRE/tests/functions.sh
25 . $LUSTRE/tests/yaml.sh
26
27 LUSTRE_TESTS_CFG_DIR=${LUSTRE_TESTS_CFG_DIR:-${LUSTRE}/tests/cfg}
28
29 EXCEPT_LIST_FILE=${EXCEPT_LIST_FILE:-${LUSTRE_TESTS_CFG_DIR}/tests-to-skip.sh}
30
31 if [ -f "$EXCEPT_LIST_FILE" ]; then
32     echo "Reading test skip list from $EXCEPT_LIST_FILE"
33     cat $EXCEPT_LIST_FILE
34     . $EXCEPT_LIST_FILE
35 fi
36
37 assert_DIR () {
38     local failed=""
39     [[ $DIR/ = $MOUNT/* ]] || \
40         { failed=1 && echo "DIR=$DIR not in $MOUNT. Aborting."; }
41     [[ $DIR1/ = $MOUNT1/* ]] || \
42         { failed=1 && echo "DIR1=$DIR1 not in $MOUNT1. Aborting."; }
43     [[ $DIR2/ = $MOUNT2/* ]] || \
44         { failed=1 && echo "DIR2=$DIR2 not in $MOUNT2. Aborting"; }
45
46     [ -n "$failed" ] && exit 99 || true
47 }
48
49 usage() {
50     echo "usage: $0 [-r] [-f cfgfile]"
51     echo "       -r: reformat"
52
53     exit
54 }
55
56 print_summary () {
57     trap 0
58     [ "$TESTSUITE" == "lfsck" ] && return 0
59     [ -n "$ONLY" ] && echo "WARNING: ONLY is set to ${ONLY}."
60     local form="%-13s %-17s %s\n"
61     printf "$form" "status" "script" "skipped tests E(xcluded) S(low)"
62     echo "------------------------------------------------------------------------------------"
63     for O in $DEFAULT_SUITES; do
64         local skipped=""
65         local slow=""
66         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
67         local o=$(echo $O  | tr "[:upper:]" "[:lower:]")
68         o=${o//_/-}
69         local log=${TMP}/${o}.log
70         [ -f $log ] && skipped=$(grep excluded $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
71         [ -f $log ] && slow=$(grep SLOW $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
72         [ "${!O}" = "done" ] && \
73             printf "$form" "Done" "$O" "E=$skipped" && \
74             [ -n "$slow" ] && printf "$form" "-" "-" "S=$slow"
75
76     done
77
78     for O in $DEFAULT_SUITES; do
79         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
80         if [ "${!O}" = "no" ]; then
81             # FIXME.
82             # only for those tests suits which are run directly from acc-sm script:
83             # bonnie, iozone, etc.
84             if [ -f "$TESTSUITELOG" ] && grep FAIL $TESTSUITELOG | grep -q ' '$O  ; then
85                printf "$form" "UNFINISHED" "$O" ""  
86             else
87                printf "$form" "Skipped" "$O" ""
88             fi
89         fi
90     done
91
92     for O in $DEFAULT_SUITES; do
93         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
94         [ "${!O}" = "done" -o "${!O}" = "no" ] || \
95             printf "$form" "UNFINISHED" "$O" ""
96     done
97 }
98
99 init_test_env() {
100     export LUSTRE=`absolute_path $LUSTRE`
101     export TESTSUITE=`basename $0 .sh`
102     export TEST_FAILED=false
103     export FAIL_ON_SKIP_ENV=${FAIL_ON_SKIP_ENV:-false}
104
105     export MKE2FS=${MKE2FS:-mke2fs}
106     export DEBUGFS=${DEBUGFS:-debugfs}
107     export TUNE2FS=${TUNE2FS:-tune2fs}
108     export E2LABEL=${E2LABEL:-e2label}
109     export DUMPE2FS=${DUMPE2FS:-dumpe2fs}
110     export E2FSCK=${E2FSCK:-e2fsck}
111
112     #[ -d /r ] && export ROOT=${ROOT:-/r}
113     export TMP=${TMP:-$ROOT/tmp}
114     export TESTSUITELOG=${TMP}/${TESTSUITE}.log
115     if [[ -z $LOGDIRSET ]]; then
116         export LOGDIR=${LOGDIR:-${TMP}/test_logs/}/$(date +%s)
117         export LOGDIRSET=true
118     fi
119     export HOSTNAME=${HOSTNAME:-`hostname`}
120     if ! echo $PATH | grep -q $LUSTRE/utils; then
121         export PATH=$PATH:$LUSTRE/utils
122     fi
123     if ! echo $PATH | grep -q $LUSTRE/utils/gss; then
124         export PATH=$PATH:$LUSTRE/utils/gss
125     fi
126     if ! echo $PATH | grep -q $LUSTRE/tests; then
127         export PATH=$PATH:$LUSTRE/tests
128     fi
129     export LST=${LST:-"$LUSTRE/../lnet/utils/lst"}
130     [ ! -f "$LST" ] && export LST=$(which lst)
131     export MDSRATE=${MDSRATE:-"$LUSTRE/tests/mpi/mdsrate"}
132     [ ! -f "$MDSRATE" ] && export MDSRATE=$(which mdsrate 2> /dev/null)
133     if ! echo $PATH | grep -q $LUSTRE/tests/racer; then
134         export PATH=$LUSTRE/tests/racer:$PATH:
135     fi
136     if ! echo $PATH | grep -q $LUSTRE/tests/mpi; then
137         export PATH=$PATH:$LUSTRE/tests/mpi
138     fi
139     export RSYNC_RSH=${RSYNC_RSH:-rsh}
140     export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
141     [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
142     export LFS=${LFS:-"$LUSTRE/utils/lfs"}
143     [ ! -f "$LFS" ] && export LFS=$(which lfs)
144     export L_GETIDENTITY=${L_GETIDENTITY:-"$LUSTRE/utils/l_getidentity"}
145     if [ ! -f "$L_GETIDENTITY" ]; then
146         if `which l_getidentity > /dev/null 2>&1`; then
147             export L_GETIDENTITY=$(which l_getidentity)
148         else
149             export L_GETIDENTITY=NONE
150         fi
151     fi
152     export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
153     [ ! -f "$MKFS" ] && export MKFS=$(which mkfs.lustre)
154     export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
155     [ ! -f "$TUNEFS" ] && export TUNEFS=$(which tunefs.lustre)
156     export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
157     export LUSTRE_RMMOD=${LUSTRE_RMMOD:-$LUSTRE/scripts/lustre_rmmod}
158     [ ! -f "$LUSTRE_RMMOD" ] && export LUSTRE_RMMOD=$(which lustre_rmmod 2> /dev/null)
159     export FSTYPE=${FSTYPE:-"ldiskfs"}
160     export NAME=${NAME:-local}
161     export LGSSD=${LGSSD:-"$LUSTRE/utils/gss/lgssd"}
162     [ "$GSS_PIPEFS" = "true" ] && [ ! -f "$LGSSD" ] && \
163         export LGSSD=$(which lgssd)
164     export LSVCGSSD=${LSVCGSSD:-"$LUSTRE/utils/gss/lsvcgssd"}
165     [ ! -f "$LSVCGSSD" ] && export LSVCGSSD=$(which lsvcgssd 2> /dev/null)
166     export KRB5DIR=${KRB5DIR:-"/usr/kerberos"}
167     export DIR2
168     export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
169     export AT_MAX_PATH
170
171     if [ "$ACCEPTOR_PORT" ]; then
172         export PORT_OPT="--port $ACCEPTOR_PORT"
173     fi
174
175     case "x$SEC" in
176         xkrb5*)
177             echo "Using GSS/krb5 ptlrpc security flavor"
178             which lgss_keyring > /dev/null 2>&1 || \
179                 error_exit "built with gss disabled! SEC=$SEC"
180             GSS=true
181             GSS_KRB5=true
182             ;;
183     esac
184
185     case "x$IDUP" in
186         xtrue)
187             IDENTITY_UPCALL=true
188             ;;
189         xfalse)
190             IDENTITY_UPCALL=false
191             ;;
192     esac
193     export LOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}
194
195     # Paths on remote nodes, if different
196     export RLUSTRE=${RLUSTRE:-$LUSTRE}
197     export RPWD=${RPWD:-$PWD}
198     export I_MOUNTED=${I_MOUNTED:-"no"}
199     if [ ! -f /lib/modules/$(uname -r)/kernel/fs/lustre/mds.ko -a \
200         ! -f `dirname $0`/../mds/mds.ko ]; then
201         export CLIENTMODSONLY=yes
202     fi
203
204     # command line
205
206     while getopts "rvwf:" opt $*; do
207         case $opt in
208             f) CONFIG=$OPTARG;;
209             r) REFORMAT=--reformat;;
210             v) VERBOSE=true;;
211             w) WRITECONF=writeconf;;
212             \?) usage;;
213         esac
214     done
215
216     shift $((OPTIND - 1))
217     ONLY=${ONLY:-$*}
218
219     [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
220     rm -f $TMP/*active
221 }
222
223 case `uname -r` in
224 2.4.*) EXT=".o"; USE_QUOTA=no; [ ! "$CLIENTONLY" ] && FSTYPE=ext3;;
225     *) EXT=".ko"; USE_QUOTA=yes;;
226 esac
227
228
229 module_loaded () {
230    /sbin/lsmod | grep -q $1
231 }
232
233 load_module() {
234     EXT=".ko"
235     module=$1
236     shift
237     BASE=`basename $module $EXT`
238
239     module_loaded ${BASE} && return
240
241     if [ "$BASE" == "lnet_selftest" ] && \
242             [ -f ${LUSTRE}/../lnet/selftest/${module}${EXT} ]; then
243         insmod ${LUSTRE}/../lnet/selftest/${module}${EXT}
244
245     elif [ -f ${LUSTRE}/${module}${EXT} ]; then
246         insmod ${LUSTRE}/${module}${EXT} $@
247     else
248         # must be testing a "make install" or "rpm" installation
249         # note failed to load ptlrpc_gss is considered not fatal
250         if [ "$BASE" == "ptlrpc_gss" ]; then
251             modprobe $BASE $@ 2>/dev/null || echo "gss/krb5 is not supported"
252         else
253             modprobe $BASE $@
254         fi
255     fi
256 }
257
258 load_modules_local() {
259     if [ -n "$MODPROBE" ]; then
260         # use modprobe
261     return 0
262     fi
263     if [ "$HAVE_MODULES" = true ]; then
264     # we already loaded
265         return 0
266     fi
267     HAVE_MODULES=true
268
269     echo Loading modules from $LUSTRE
270     load_module ../libcfs/libcfs/libcfs
271     [ "$PTLDEBUG" ] && lctl set_param debug="$PTLDEBUG"
272     [ "$SUBSYSTEM" ] && lctl set_param subsystem_debug="${SUBSYSTEM# }"
273     local MODPROBECONF=
274     [ -f /etc/modprobe.conf ] && MODPROBECONF=/etc/modprobe.conf
275     [ ! "$MODPROBECONF" -a -d /etc/modprobe.d ] && MODPROBECONF=/etc/modprobe.d/Lustre
276     [ -z "$LNETOPTS" -a "$MODPROBECONF" ] && \
277         LNETOPTS=$(awk '/^options lnet/ { print $0}' $MODPROBECONF | sed 's/^options lnet //g')
278     echo $LNETOPTS | grep -q "accept=all"  || LNETOPTS="$LNETOPTS accept=all";
279     echo "lnet options: '$LNETOPTS'"
280     # note that insmod will ignore anything in modprobe.conf
281     load_module ../lnet/lnet/lnet $LNETOPTS
282     LNETLND=${LNETLND:-"socklnd/ksocklnd"}
283     load_module ../lnet/klnds/$LNETLND
284     load_module lvfs/lvfs
285     load_module obdclass/obdclass
286     load_module ptlrpc/ptlrpc
287     load_module ptlrpc/gss/ptlrpc_gss
288     [ "$USE_QUOTA" = "yes" -a "$LQUOTA" != "no" ] && load_module quota/lquota
289     load_module fld/fld
290     load_module fid/fid
291     load_module lmv/lmv
292     load_module mdc/mdc
293     load_module osc/osc
294     load_module lov/lov
295     load_module mgc/mgc
296     if ! client_only; then
297         grep -q crc16 /proc/kallsyms || { modprobe crc16 2>/dev/null || true; }
298         grep -q jbd /proc/kallsyms || { modprobe jbd 2>/dev/null || true; }
299         [ "$FSTYPE" = "ldiskfs" ] && load_module ../ldiskfs/ldiskfs/ldiskfs
300         load_module mgs/mgs
301         load_module mds/mds
302         load_module mdd/mdd
303         load_module mdt/mdt
304         load_module lvfs/fsfilt_$FSTYPE
305         load_module cmm/cmm
306         load_module osd/osd
307         load_module ost/ost
308         load_module obdfilter/obdfilter
309     fi
310
311     load_module llite/lustre
312     load_module llite/llite_lloop
313     [ -d /r ] && OGDB=${OGDB:-"/r/tmp"}
314     OGDB=${OGDB:-$TMP}
315     rm -f $OGDB/ogdb-$HOSTNAME
316     $LCTL modules > $OGDB/ogdb-$HOSTNAME
317
318     # 'mount' doesn't look in $PATH, just sbin
319     [ -f $LUSTRE/utils/mount.lustre ] && cp $LUSTRE/utils/mount.lustre /sbin/. || true
320 }
321
322 load_modules () {
323     load_modules_local
324     # bug 19124
325     # load modules on remote nodes optionally
326     # lustre-tests have to be installed on these nodes
327     if $LOAD_MODULES_REMOTE ; then
328         local list=$(comma_list $(remote_nodes_list))
329         echo loading modules on $list
330         do_rpc_nodes $list load_modules 
331     fi
332 }
333
334 check_mem_leak () {
335     LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
336     LEAK_PORTALS=$(dmesg | tail -n 20 | grep "Portals memory leaked" || true)
337     if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
338         echo "$LEAK_LUSTRE" 1>&2
339         echo "$LEAK_PORTALS" 1>&2
340         mv $TMP/debug $TMP/debug-leak.`date +%s` || true
341         echo "Memory leaks detected"
342         [ -n "$IGNORE_LEAK" ] && { echo "ignoring leaks" && return 0; } || true
343         return 1
344     fi
345 }
346
347 unload_modules() {
348     wait_exit_ST client # bug 12845
349
350     $LUSTRE_RMMOD $FSTYPE || return 2
351
352     if $LOAD_MODULES_REMOTE ; then
353         local list=$(comma_list $(remote_nodes_list))
354         if [ ! -z $list ]; then
355             echo unloading modules on $list
356             do_rpc_nodes $list $LUSTRE_RMMOD $FSTYPE
357             do_rpc_nodes $list check_mem_leak
358         fi
359     fi
360
361     HAVE_MODULES=false
362
363     check_mem_leak || return 254
364
365     echo "modules unloaded."
366     return 0
367 }
368
369 check_gss_daemon_nodes() {
370     local list=$1
371     dname=$2
372
373     do_nodes --verbose $list "num=\\\$(ps -o cmd -C $dname | grep $dname | wc -l);
374 if [ \\\"\\\$num\\\" -ne 1 ]; then
375     echo \\\$num instance of $dname;
376     exit 1;
377 fi; "
378 }
379
380 check_gss_daemon_facet() {
381     facet=$1
382     dname=$2
383
384     num=`do_facet $facet ps -o cmd -C $dname | grep $dname | wc -l`
385     if [ $num -ne 1 ]; then
386         echo "$num instance of $dname on $facet"
387         return 1
388     fi
389     return 0
390 }
391
392 send_sigint() {
393     local list=$1
394     shift
395     echo Stopping $@ on $list
396     do_nodes $list "killall -2 $@ 2>/dev/null || true"
397 }
398
399 # start gss daemons on all nodes, or
400 # "daemon" on "list" if set
401 start_gss_daemons() {
402     local list=$1
403     local daemon=$2
404
405     if [ "$list" ] && [ "$daemon" ] ; then
406         echo "Starting gss daemon on nodes: $list"
407         do_nodes $list "$daemon" || return 8
408         return 0
409     fi
410
411     local list=$(comma_list $(mdts_nodes))
412
413     echo "Starting gss daemon on mds: $list"
414     do_nodes $list "$LSVCGSSD -v" || return 1
415     if $GSS_PIPEFS; then
416         do_nodes $list "$LGSSD -v" || return 2
417     fi
418
419     list=$(comma_list $(osts_nodes))
420     echo "Starting gss daemon on ost: $list"
421     do_nodes $list "$LSVCGSSD -v" || return 3
422     # starting on clients
423
424     local clients=${CLIENTS:-`hostname`}
425     if $GSS_PIPEFS; then
426         echo "Starting $LGSSD on clients $clients "
427         do_nodes $clients  "$LGSSD -v" || return 4
428     fi
429
430     # wait daemons entering "stable" status
431     sleep 5
432
433     #
434     # check daemons are running
435     #
436     list=$(comma_list $(mdts_nodes) $(osts_nodes))
437     check_gss_daemon_nodes $list lsvcgssd || return 5
438     if $GSS_PIPEFS; then
439         list=$(comma_list $(mdts_nodes))
440         check_gss_daemon_nodes $list lgssd || return 6
441     fi
442     if $GSS_PIPEFS; then
443         check_gss_daemon_nodes $clients lgssd || return 7
444     fi
445 }
446
447 stop_gss_daemons() {
448     local list=$(comma_list $(mdts_nodes))
449     
450     send_sigint $list lsvcgssd lgssd
451
452     list=$(comma_list $(osts_nodes))
453     send_sigint $list lsvcgssd
454
455     list=${CLIENTS:-`hostname`}
456     send_sigint $list lgssd
457 }
458
459 init_gss() {
460     if $GSS; then
461         if ! module_loaded ptlrpc_gss; then
462             load_module ptlrpc/gss/ptlrpc_gss
463             module_loaded ptlrpc_gss ||
464                 error_exit "init_gss : GSS=$GSS, but gss/krb5 is not supported!"
465         fi
466         start_gss_daemons || error_exit "start gss daemon failed! rc=$?"
467
468         if [ -n "$LGSS_KEYRING_DEBUG" ]; then
469             echo $LGSS_KEYRING_DEBUG > /proc/fs/lustre/sptlrpc/gss/lgss_keyring/debug_level
470         fi
471     fi
472 }
473
474 cleanup_gss() {
475     if $GSS; then
476         stop_gss_daemons
477         # maybe cleanup credential cache?
478     fi
479 }
480
481 mdsdevlabel() {
482     local num=$1
483     local device=`mdsdevname $num`
484     local label=`do_facet mds$num "e2label ${device}" | grep -v "CMD: "`
485     echo -n $label
486 }
487
488 ostdevlabel() {
489     local num=$1
490     local device=`ostdevname $num`
491     local label=`do_facet ost$num "e2label ${device}" | grep -v "CMD: "`
492     echo -n $label
493 }
494
495 # Facet functions
496 mount_facet() {
497     local facet=$1
498     shift
499     local dev=$(facet_active $facet)_dev
500     local opt=${facet}_opt
501     echo "Starting ${facet}: ${!opt} $@ ${!dev} ${MOUNT%/*}/${facet}"
502     do_facet ${facet} mount -t lustre ${!opt} $@ ${!dev} ${MOUNT%/*}/${facet}
503     RC=${PIPESTATUS[0]}
504     if [ $RC -ne 0 ]; then
505         echo "mount -t lustre $@ ${!dev} ${MOUNT%/*}/${facet}"
506         echo "Start of ${!dev} on ${facet} failed ${RC}"
507     else
508         do_facet ${facet} "lctl set_param debug=\\\"$PTLDEBUG\\\"; \
509             lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\"; \
510             lctl set_param debug_mb=${DEBUG_SIZE}; \
511             sync"
512
513         label=$(do_facet ${facet} "$E2LABEL ${!dev}")
514         [ -z "$label" ] && echo no label for ${!dev} && exit 1
515         eval export ${facet}_svc=${label}
516         echo Started ${label}
517     fi
518     return $RC
519 }
520
521 # start facet device options
522 start() {
523     local facet=$1
524     shift
525     local device=$1
526     shift
527     eval export ${facet}_dev=${device}
528     eval export ${facet}_opt=\"$@\"
529
530     local varname=${facet}failover_dev
531     if [ -n "${!varname}" ] ; then
532         eval export ${facet}failover_dev=${!varname}
533     else
534         eval export ${facet}failover_dev=$device
535     fi
536
537     do_facet ${facet} mkdir -p ${MOUNT%/*}/${facet}
538     mount_facet ${facet}
539     RC=$?
540     return $RC
541 }
542
543 stop() {
544     local running
545     local facet=$1
546     shift
547     HOST=`facet_active_host $facet`
548     [ -z $HOST ] && echo stop: no host for $facet && return 0
549
550     running=$(do_facet ${facet} "grep -c ${MOUNT%/*}/${facet}' ' /proc/mounts") || true
551     if [ ${running} -ne 0 ]; then
552         echo "Stopping ${MOUNT%/*}/${facet} (opts:$@)"
553         do_facet ${facet} umount -d $@ ${MOUNT%/*}/${facet}
554     fi
555
556     # umount should block, but we should wait for unrelated obd's
557     # like the MGS or MGC to also stop.
558     wait_exit_ST ${facet}
559 }
560
561 # save quota version (both administrative and operational quotas)
562 # add an additional parameter if mountpoint is ever different from $MOUNT
563 quota_save_version() {
564     local fsname=${2:-$FSNAME}
565     local spec=$1
566     local ver=$(tr -c -d "123" <<< $spec)
567     local type=$(tr -c -d "ug" <<< $spec)
568
569     [ -n "$ver" -a "$ver" != "3" ] && error "wrong quota version specifier"
570
571     [ -n "$type" ] && { $LFS quotacheck -$type $MOUNT || error "quotacheck has failed"; }
572
573     do_facet mgs "lctl conf_param ${fsname}-MDT*.mdd.quota_type=$spec"
574     local varsvc
575     local osts=$(get_facets OST)
576     for ost in ${osts//,/ }; do
577         varsvc=${ost}_svc
578         do_facet mgs "lctl conf_param ${!varsvc}.ost.quota_type=$spec"
579     done
580 }
581
582 # client could mount several lustre 
583 quota_type () {
584     local fsname=${1:-$FSNAME}
585     local rc=0
586     do_facet mgs lctl get_param mdd.${fsname}-MDT*.quota_type || rc=$?
587     do_nodes $(comma_list $(osts_nodes)) \
588         lctl get_param obdfilter.${fsname}-OST*.quota_type || rc=$?
589     return $rc 
590 }
591
592 restore_quota_type () {
593    local mntpt=${1:-$MOUNT}
594    local quota_type=$(quota_type $FSNAME | grep MDT | cut -d "=" -f2)
595    if [ ! "$old_QUOTA_TYPE" ] || [ "$quota_type" = "$old_QUOTA_TYPE" ]; then
596         return
597    fi
598    quota_save_version $old_QUOTA_TYPE
599 }
600
601 setup_quota(){
602     local mntpt=$1
603
604     # We need save the original quota_type params, and restore them after testing
605
606     # Suppose that quota type the same on mds and ost
607     local quota_type=$(quota_type | grep MDT | cut -d "=" -f2)
608     [ ${PIPESTATUS[0]} -eq 0 ] || error "quota_type failed!"
609     echo "[HOST:$HOSTNAME] [old_quota_type:$quota_type] [new_quota_type:$QUOTA_TYPE]"
610     if [ "$quota_type" != "$QUOTA_TYPE" ]; then
611         export old_QUOTA_TYPE=$quota_type
612         quota_save_version $QUOTA_TYPE
613     else
614         qtype=$(tr -c -d "ug" <<< $QUOTA_TYPE)
615         $LFS quotacheck -$qtype $mntpt || error "quotacheck has failed for $type"
616     fi
617
618     local quota_usrs=$QUOTA_USERS
619
620     # get_filesystem_size
621     local disksz=$(lfs df $mntpt | grep "filesystem summary:"  | awk '{print $3}')
622     local blk_soft=$((disksz + 1024))
623     local blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over
624
625     local Inodes=$(lfs df -i $mntpt | grep "filesystem summary:"  | awk '{print $3}')
626     local i_soft=$Inodes
627     local i_hard=$((i_soft + i_soft / 20))
628
629     echo "Total disk size: $disksz  block-softlimit: $blk_soft block-hardlimit:
630         $blk_hard inode-softlimit: $i_soft inode-hardlimit: $i_hard"
631
632     local cmd
633     for usr in $quota_usrs; do
634         echo "Setting up quota on $HOSTNAME:$mntpt for $usr..."
635         for type in u g; do
636             cmd="$LFS setquota -$type $usr -b $blk_soft -B $blk_hard -i $i_soft -I $i_hard $mntpt"
637             echo "+ $cmd"
638             eval $cmd || error "$cmd FAILED!"
639         done
640         # display the quota status
641         echo "Quota settings for $usr : "
642         $LFS quota -v -u $usr $mntpt || true
643     done
644 }
645
646 zconf_mount() {
647     local OPTIONS
648     local client=$1
649     local mnt=$2
650     # Only supply -o to mount if we have options
651     if [ -n "$MOUNTOPT" ]; then
652         OPTIONS="-o $MOUNTOPT"
653     fi
654     local device=$MGSNID:/$FSNAME
655     if [ -z "$mnt" -o -z "$FSNAME" ]; then
656         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
657         exit 1
658     fi
659
660     echo "Starting client: $client: $OPTIONS $device $mnt"
661     do_node $client mkdir -p $mnt
662     do_node $client mount -t lustre $OPTIONS $device $mnt || return 1
663
664     do_node $client "lctl set_param debug=\\\"$PTLDEBUG\\\";
665         lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
666         lctl set_param debug_mb=${DEBUG_SIZE}"
667
668     return 0
669 }
670
671 zconf_umount() {
672     local client=$1
673     local mnt=$2
674     local force
675     local busy 
676     local need_kill
677
678     [ "$3" ] && force=-f
679     local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
680     if [ $running -ne 0 ]; then
681         echo "Stopping client $client $mnt (opts:$force)"
682         do_node $client lsof -t $mnt || need_kill=no
683         if [ "x$force" != "x" -a "x$need_kill" != "xno" ]; then
684             pids=$(do_node $client lsof -t $mnt | sort -u);
685             if [ -n $pids ]; then
686                 do_node $client kill -9 $pids || true
687             fi
688         fi
689
690         busy=$(do_node $client "umount $force $mnt 2>&1" | grep -c "busy") || true
691         if [ $busy -ne 0 ] ; then
692             echo "$mnt is still busy, wait one second" && sleep 1
693             do_node $client umount $force $mnt
694         fi
695     fi
696 }
697
698 # nodes is comma list
699 sanity_mount_check_nodes () {
700     local nodes=$1
701     shift
702     local mnts="$@"
703     local mnt
704
705     # FIXME: assume that all cluster nodes run the same os
706     [ "$(uname)" = Linux ] || return 0
707
708     local rc=0
709     for mnt in $mnts ; do
710         do_nodes $nodes "running=\\\$(grep -c $mnt' ' /proc/mounts);
711 mpts=\\\$(mount | grep -w -c $mnt);
712 if [ \\\$running -ne \\\$mpts ]; then
713     echo \\\$(hostname) env are INSANE!;
714     exit 1;
715 fi"
716     [ $? -eq 0 ] || rc=1 
717     done
718     return $rc
719 }
720
721 sanity_mount_check_servers () {
722     [ "$CLIENTONLY" ] && 
723         { echo "CLIENTONLY mode, skip mount_check_servers"; return 0; } || true
724     echo Checking servers environments
725
726     # FIXME: modify get_facets to display all facets wo params
727     local facets="$(get_facets OST),$(get_facets MDS),mgs"
728     local node
729     local mnt
730     local facet
731     for facet in ${facets//,/ }; do
732         node=$(facet_host ${facet})
733         mnt=${MOUNT%/*}/${facet}
734         sanity_mount_check_nodes $node $mnt ||
735             { error "server $node environments are insane!"; return 1; }
736     done
737 }
738
739 sanity_mount_check_clients () {
740     local clients=${1:-$CLIENTS}
741     local mntpt=${2:-$MOUNT}
742     local mntpt2=${3:-$MOUNT2}
743
744     [ -z $clients ] && clients=$(hostname)
745     echo Checking clients $clients environments
746
747     sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
748        error "clients environments are insane!"
749 }
750
751 sanity_mount_check () {
752     sanity_mount_check_servers || return 1
753     sanity_mount_check_clients || return 2
754 }
755
756 # mount clients if not mouted
757 zconf_mount_clients() {
758     local clients=$1
759     local mnt=$2
760     local OPTIONS=${3:-$MOUNTOPT}
761
762     # Only supply -o to mount if we have options
763     if [ "$OPTIONS" ]; then
764         OPTIONS="-o $OPTIONS"
765     fi
766     local device=$MGSNID:/$FSNAME
767     if [ -z "$mnt" -o -z "$FSNAME" ]; then
768         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
769         exit 1
770     fi
771
772     echo "Starting client $clients: $OPTIONS $device $mnt"
773
774     do_nodes $clients "
775 running=\\\$(mount | grep -c $mnt' ');
776 rc=0;
777 if [ \\\$running -eq 0 ] ; then
778     mkdir -p $mnt;
779     mount -t lustre $OPTIONS $device $mnt;
780     rc=\\\$?;
781 fi;
782 exit \\\$rc" || return ${PIPESTATUS[0]}
783
784     echo "Started clients $clients: "
785     do_nodes $clients "mount | grep -w $mnt"
786
787     do_nodes $clients "lctl set_param debug=\\\"$PTLDEBUG\\\";
788         lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
789         lctl set_param debug_mb=${DEBUG_SIZE};"
790
791     return 0
792 }
793
794 zconf_umount_clients() {
795     local clients=$1
796     local mnt=$2
797     local force
798
799     [ "$3" ] && force=-f
800
801     echo "Stopping clients: $clients $mnt (opts:$force)"
802     do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
803 if [ \\\$running -ne 0 ] ; then
804 echo Stopping client \\\$(hostname) $mnt opts:$force;
805 lsof -t $mnt || need_kill=no;
806 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
807     pids=\\\$(lsof -t $mnt | sort -u);
808     if [ -n \\\"\\\$pids\\\" ]; then
809              kill -9 \\\$pids;
810     fi
811 fi;
812 busy=\\\$(umount $force $mnt 2>&1 | grep -c "busy");
813 if [ \\\$busy -ne 0 ] ; then
814     echo "$mnt is still busy, wait one second" && sleep 1;
815     umount $force $mnt;
816 fi
817 fi"
818 }
819
820 shudown_node_hard () {
821     local host=$1
822     local attempts=3
823
824     for i in $(seq $attempts) ; do
825         $POWER_DOWN $host
826         sleep 1
827         ping -w 3 -c 1 $host > /dev/null 2>&1 || return 0
828         echo "waiting for $host to fail attempts=$attempts"
829         [ $i -lt $attempts ] || \
830             { echo "$host still pingable after power down! attempts=$attempts" && return 1; } 
831     done
832 }
833
834 shutdown_client() {
835     local client=$1
836     local mnt=${2:-$MOUNT}
837     local attempts=3
838
839     if [ "$FAILURE_MODE" = HARD ]; then
840         shudown_node_hard $client 
841     else
842        zconf_umount_clients $client $mnt -f
843     fi
844 }
845
846 shutdown_facet() {
847     local facet=$1
848     if [ "$FAILURE_MODE" = HARD ]; then
849         shudown_node_hard $(facet_active_host $facet)
850     elif [ "$FAILURE_MODE" = SOFT ]; then
851         stop $facet
852     fi
853 }
854
855 reboot_facet() {
856     facet=$1
857     if [ "$FAILURE_MODE" = HARD ]; then
858         $POWER_UP `facet_active_host $facet`
859     else
860         sleep 10
861     fi
862 }
863
864 boot_node() {
865     local node=$1
866     if [ "$FAILURE_MODE" = HARD ]; then
867        $POWER_UP $node
868        wait_for_host $node
869     fi
870 }
871
872 # recovery-scale functions
873 check_progs_installed () {
874     local clients=$1
875     shift
876     local progs=$@
877
878     do_nodes $clients "PATH=:$PATH; status=true;
879 for prog in $progs; do
880     if ! [ \\\"\\\$(which \\\$prog)\\\"  -o  \\\"\\\${!prog}\\\" ]; then
881        echo \\\$prog missing on \\\$(hostname);
882        status=false;
883     fi
884 done;
885 eval \\\$status"
886 }
887
888 client_var_name() {
889     echo __$(echo $1 | tr '-' 'X')
890 }
891
892 start_client_load() {
893     local client=$1
894     local load=$2
895     local var=$(client_var_name $client)_load
896     eval export ${var}=$load
897
898     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
899                               BREAK_ON_ERROR=$BREAK_ON_ERROR \
900                               END_RUN_FILE=$END_RUN_FILE \
901                               LOAD_PID_FILE=$LOAD_PID_FILE \
902                               TESTSUITELOG=$TESTSUITELOG \
903                               run_${load}.sh" &
904     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $!"
905     log "Started client load: ${load} on $client"
906
907     return 0
908 }
909
910 start_client_loads () {
911     local -a clients=(${1//,/ })
912     local numloads=${#CLIENT_LOADS[@]}
913     local testnum
914
915     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
916         testnum=$((nodenum % numloads))
917         start_client_load ${clients[nodenum]} ${CLIENT_LOADS[testnum]}
918     done
919 }
920
921 # only for remote client 
922 check_client_load () {
923     local client=$1
924     local var=$(client_var_name $client)_load
925     local TESTLOAD=run_${!var}.sh
926
927     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
928     
929     # bug 18914: try to connect several times not only when
930     # check ps, but  while check_catastrophe also
931     local tries=3
932     local RC=254
933     while [ $RC = 254 -a $tries -gt 0 ]; do
934         let tries=$tries-1
935         # assume success
936         RC=0
937         if ! check_catastrophe $client; then
938             RC=${PIPESTATUS[0]}
939             if [ $RC -eq 254 ]; then
940                 # FIXME: not sure how long we shuold sleep here
941                 sleep 10
942                 continue
943             fi
944             echo "check catastrophe failed: RC=$RC "
945             return $RC
946         fi
947     done
948     # We can continue try to connect if RC=254
949     # Just print the warning about this
950     if [ $RC = 254 ]; then
951         echo "got a return status of $RC from do_node while checking catastrophe on $client"
952     fi
953
954     # see if the load is still on the client
955     tries=3
956     RC=254
957     while [ $RC = 254 -a $tries -gt 0 ]; do
958         let tries=$tries-1
959         # assume success
960         RC=0
961         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
962             RC=${PIPESTATUS[0]}
963             sleep 30
964         fi
965     done
966     if [ $RC = 254 ]; then
967         echo "got a return status of $RC from do_node while checking (catastrophe and 'ps') the client load on $client"
968         # see if we can diagnose a bit why this is
969     fi
970
971     return $RC
972 }
973 check_client_loads () {
974    local clients=${1//,/ }
975    local client=
976    local rc=0
977
978    for client in $clients; do
979       check_client_load $client
980       rc=${PIPESTATUS[0]}
981       if [ "$rc" != 0 ]; then
982         log "Client load failed on node $client, rc=$rc"
983         return $rc
984       fi
985    done
986 }
987
988 restart_client_loads () {
989     local clients=${1//,/ }
990     local expectedfail=${2:-""}
991     local client=
992     local rc=0
993
994     for client in $clients; do
995         check_client_load $client
996         rc=${PIPESTATUS[0]}
997         if [ "$rc" != 0 -a "$expectedfail" ]; then
998             local var=$(client_var_name $client)_load
999             start_client_load $client ${!var}
1000             echo "Restarted client load ${!var}: on $client. Checking ..."
1001             check_client_load $client
1002             rc=${PIPESTATUS[0]}
1003             if [ "$rc" != 0 ]; then
1004                 log "Client load failed to restart on node $client, rc=$rc"
1005                 # failure one client load means test fail
1006                 # we do not need to check other 
1007                 return $rc
1008             fi
1009         else
1010             return $rc
1011         fi
1012     done
1013 }
1014 # End recovery-scale functions
1015
1016 # verify that lustre actually cleaned up properly
1017 cleanup_check() {
1018     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
1019         error "LBUG/LASSERT detected"
1020     BUSY=`dmesg | grep -i destruct || true`
1021     if [ "$BUSY" ]; then
1022         echo "$BUSY" 1>&2
1023         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
1024         exit 205
1025     fi
1026
1027     check_mem_leak || exit 204
1028
1029     [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl && \
1030         echo "$0: lustre didn't clean up..." 1>&2 && return 202 || true
1031
1032     if module_loaded lnet || module_loaded libcfs; then
1033         echo "$0: modules still loaded..." 1>&2
1034         /sbin/lsmod 1>&2
1035         return 203
1036     fi
1037     return 0
1038 }
1039
1040 wait_update () {
1041     local node=$1
1042     local TEST=$2
1043     local FINAL=$3
1044     local MAX=${4:-90}
1045
1046         local RESULT
1047         local WAIT=0
1048         local sleep=5
1049         while [ true ]; do
1050             RESULT=$(do_node $node "$TEST")
1051             if [ "$RESULT" == "$FINAL" ]; then
1052                 echo "Updated after $WAIT sec: wanted '$FINAL' got '$RESULT'"
1053                 return 0
1054             fi
1055             [ $WAIT -ge $MAX ] && break
1056             echo "Waiting $((MAX - WAIT)) secs for update"
1057             WAIT=$((WAIT + sleep))
1058             sleep $sleep
1059         done
1060         echo "Update not seen after $MAX sec: wanted '$FINAL' got '$RESULT'"
1061         return 3
1062 }
1063
1064 wait_update_facet () {
1065     local facet=$1
1066     wait_update  $(facet_active_host $facet) "$@"
1067 }
1068
1069 wait_delete_completed () {
1070     local TOTALPREV=`lctl get_param -n osc.*.kbytesavail | \
1071                      awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1072
1073     local WAIT=0
1074     local MAX_WAIT=20
1075     while [ "$WAIT" -ne "$MAX_WAIT" ]; do
1076         sleep 1
1077         TOTAL=`lctl get_param -n osc.*.kbytesavail | \
1078                awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1079         [ "$TOTAL" -eq "$TOTALPREV" ] && return 0
1080         echo "Waiting delete completed ... prev: $TOTALPREV current: $TOTAL "
1081         TOTALPREV=$TOTAL
1082         WAIT=$(( WAIT + 1))
1083     done
1084     echo "Delete is not completed in $MAX_WAIT sec"
1085     return 1
1086 }
1087
1088 wait_for_host() {
1089     local host=$1
1090     check_network "$host" 900
1091     while ! do_node $host hostname  > /dev/null; do sleep 5; done
1092 }
1093
1094 wait_for() {
1095     local facet=$1
1096     local host=`facet_active_host $facet`
1097     wait_for_host $host
1098 }
1099
1100 wait_recovery_complete () {
1101     local facet=$1
1102
1103     # Use default policy if $2 is not passed by caller.
1104     #define OBD_RECOVERY_TIMEOUT (obd_timeout * 5 / 2)
1105     # as we are in process of changing obd_timeout in different ways
1106     # let's set MAX longer than that
1107     local MAX=${2:-$(( TIMEOUT * 4 ))}
1108
1109     local var_svc=${facet}_svc
1110     local procfile="*.${!var_svc}.recovery_status"
1111     local WAIT=0
1112     local STATUS=
1113
1114     while [ $WAIT -lt $MAX ]; do
1115         STATUS=$(do_facet $facet lctl get_param -n $procfile | grep status)
1116         [[ $STATUS = "status: COMPLETE" ]] && return 0
1117         sleep 5
1118         WAIT=$((WAIT + 5))
1119         echo "Waiting $((MAX - WAIT)) secs for $facet recovery done. $STATUS"
1120     done
1121     echo "$facet recovery not done in $MAX sec. $STATUS"
1122     return 1
1123 }
1124
1125 wait_mds_ost_sync () {
1126     # just because recovery is done doesn't mean we've finished
1127     # orphan cleanup. Wait for llogs to get synchronized.
1128     echo "Waiting for orphan cleanup..."
1129     # MAX value includes time needed for MDS-OST reconnection
1130     local MAX=$(( TIMEOUT * 2 ))
1131     local WAIT=0
1132     while [ $WAIT -lt $MAX ]; do
1133         local -a sync=($(do_nodes $(comma_list $(osts_nodes)) \
1134             "$LCTL get_param -n obdfilter.*.mds_sync"))
1135         local con=1
1136         for ((i=0; i<${#sync[@]}; i++)); do
1137             [ ${sync[$i]} -eq 0 ] && continue
1138             # there is a not finished MDS-OST synchronization
1139             con=0
1140             break;
1141         done
1142         sleep 2 # increase waiting time and cover statfs cache
1143         [ ${con} -eq 1 ] && return 0
1144         echo "Waiting $WAIT secs for $facet mds-ost sync done."
1145         WAIT=$((WAIT + 2))
1146     done
1147     echo "$facet recovery not done in $MAX sec. $STATUS"
1148     return 1
1149 }
1150
1151 wait_destroy_complete () {
1152     echo "Waiting for destroy to be done..."
1153     # MAX value shouldn't be big as this mean server responsiveness
1154     # never increase this just to make test pass but investigate
1155     # why it takes so long time
1156     local MAX=5
1157     local WAIT=0
1158     while [ $WAIT -lt $MAX ]; do
1159         local -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))
1160         local con=1
1161         for ((i=0; i<${#RPCs[@]}; i++)); do
1162             [ ${RPCs[$i]} -eq 0 ] && continue
1163             # there are still some destroy RPCs in flight
1164             con=0
1165             break;
1166         done
1167         sleep 1
1168         [ ${con} -eq 1 ] && return 0 # done waiting
1169         echo "Waiting $WAIT secs for destroys to be done."
1170         WAIT=$((WAIT + 1))
1171     done
1172     echo "Destroys weren't done in $MAX sec."
1173     return 1
1174 }
1175
1176 wait_exit_ST () {
1177     local facet=$1
1178
1179     local WAIT=0
1180     local INTERVAL=1
1181     local running
1182     # conf-sanity 31 takes a long time cleanup
1183     while [ $WAIT -lt 300 ]; do
1184         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
1185         [ -z "${running}" ] && return 0
1186         echo "waited $WAIT for${running}"
1187         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
1188         sleep $INTERVAL
1189         WAIT=$((WAIT + INTERVAL))
1190     done
1191     echo "service didn't stop after $WAIT seconds.  Still running:"
1192     echo ${running}
1193     return 1
1194 }
1195
1196 wait_remote_prog () {
1197    local prog=$1
1198    local WAIT=0
1199    local INTERVAL=5
1200    local rc=0
1201
1202    [ "$PDSH" = "no_dsh" ] && return 0
1203
1204    while [ $WAIT -lt $2 ]; do
1205         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
1206         [ -z "${running}" ] && return 0 || true
1207         echo "waited $WAIT for: "
1208         echo "$running"
1209         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
1210         sleep $INTERVAL
1211         WAIT=$((WAIT + INTERVAL))
1212     done
1213     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
1214     [ -z "$pids" ] && return 0
1215     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
1216     # FIXME: not portable
1217     for pid in $pids; do
1218         cat /proc/${pid}/status || true
1219         cat /proc/${pid}/wchan || true
1220         echo "Killing $pid"
1221         kill -9 $pid || true
1222         sleep 1
1223         ps -P $pid && rc=1
1224     done
1225
1226     return $rc
1227 }
1228
1229 clients_up() {
1230     # not every config has many clients
1231     sleep 1
1232     if [ ! -z "$CLIENTS" ]; then
1233         $PDSH $CLIENTS "stat -f $MOUNT" > /dev/null
1234     else
1235         stat -f $MOUNT > /dev/null
1236     fi
1237 }
1238
1239 client_up() {
1240     local client=$1
1241     # usually checked on particular client or locally
1242     sleep 1
1243     if [ ! -z "$client" ]; then
1244         $PDSH $client "stat -f $MOUNT" > /dev/null
1245     else
1246         stat -f $MOUNT > /dev/null
1247     fi
1248 }
1249
1250 client_evicted() {
1251     ! client_up $1
1252 }
1253
1254 client_reconnect() {
1255     uname -n >> $MOUNT/recon
1256     if [ -z "$CLIENTS" ]; then
1257         df $MOUNT; uname -n >> $MOUNT/recon
1258     else
1259         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
1260     fi
1261     echo Connected clients:
1262     cat $MOUNT/recon
1263     ls -l $MOUNT/recon > /dev/null
1264     rm $MOUNT/recon
1265 }
1266
1267 facet_failover() {
1268     local facet=$1
1269     local sleep_time=$2
1270     echo "Failing $facet on node `facet_active_host $facet`"
1271     shutdown_facet $facet
1272     [ -n "$sleep_time" ] && sleep $sleep_time
1273     reboot_facet $facet
1274     change_active $facet
1275     local TO=`facet_active_host $facet`
1276     echo "Failover $facet to $TO"
1277     wait_for $facet
1278     mount_facet $facet || error "Restart of $facet failed"
1279 }
1280
1281 obd_name() {
1282     local facet=$1
1283 }
1284
1285 replay_barrier() {
1286     local facet=$1
1287     do_facet $facet sync
1288     df $MOUNT
1289     local svc=${facet}_svc
1290     do_facet $facet $LCTL --device %${!svc} notransno
1291     do_facet $facet $LCTL --device %${!svc} readonly
1292     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1293     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1294 }
1295
1296 replay_barrier_nodf() {
1297     local facet=$1    echo running=${running}
1298     do_facet $facet sync
1299     local svc=${facet}_svc
1300     echo Replay barrier on ${!svc}
1301     do_facet $facet $LCTL --device %${!svc} notransno
1302     do_facet $facet $LCTL --device %${!svc} readonly
1303     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1304     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1305 }
1306
1307 replay_barrier_nosync() {
1308     local facet=$1    echo running=${running}
1309     local svc=${facet}_svc
1310     echo Replay barrier on ${!svc}
1311     do_facet $facet $LCTL --device %${!svc} notransno
1312     do_facet $facet $LCTL --device %${!svc} readonly
1313     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1314     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1315 }
1316
1317 mds_evict_client() {
1318     UUID=`lctl get_param -n mdc.${mds1_svc}-mdc-*.uuid`
1319     do_facet mds1 "lctl set_param -n mdt.${mds1_svc}.evict_client $UUID"
1320 }
1321
1322 ost_evict_client() {
1323     UUID=`lctl get_param -n devices| grep ${ost1_svc}-osc- | egrep -v 'MDT' | awk '{print $5}'`
1324     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
1325 }
1326
1327 fail() {
1328     facet_failover $* || error "failover: $?"
1329     clients_up || error "post-failover df: $?"
1330 }
1331
1332 fail_nodf() {
1333         local facet=$1
1334         facet_failover $facet
1335 }
1336
1337 fail_abort() {
1338     local facet=$1
1339     stop $facet
1340     change_active $facet
1341     mount_facet $facet -o abort_recovery
1342     clients_up || echo "first df failed: $?"
1343     clients_up || error "post-failover df: $?"
1344 }
1345
1346 do_lmc() {
1347     echo There is no lmc.  This is mountconf, baby.
1348     exit 1
1349 }
1350
1351 h2gm () {
1352     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1353         ID=`$PDSH $1 $GMNALNID -l | cut -d\  -f2`
1354         echo $ID"@gm"
1355     fi
1356 }
1357
1358 h2name_or_ip() {
1359     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1360         echo $1"@$2"
1361     fi
1362 }
1363
1364 h2ptl() {
1365    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1366        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
1367        if [ -z "$ID" ]; then
1368            echo "Could not get a ptl id for $1..."
1369            exit 1
1370        fi
1371        echo $ID"@ptl"
1372    fi
1373 }
1374 declare -fx h2ptl
1375
1376 h2tcp() {
1377     h2name_or_ip "$1" "tcp"
1378 }
1379 declare -fx h2tcp
1380
1381 h2elan() {
1382     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1383         if type __h2elan >/dev/null 2>&1; then
1384             ID=$(__h2elan $1)
1385         else
1386             ID=`echo $1 | sed 's/[^0-9]*//g'`
1387         fi
1388         echo $ID"@elan"
1389     fi
1390 }
1391 declare -fx h2elan
1392
1393 h2openib() {
1394     h2name_or_ip "$1" "openib"
1395 }
1396 declare -fx h2openib
1397
1398 h2o2ib() {
1399     h2name_or_ip "$1" "o2ib"
1400 }
1401 declare -fx h2o2ib
1402
1403 facet_host() {
1404     local facet=$1
1405
1406     [ "$facet" == client ] && echo -n $HOSTNAME && return
1407     varname=${facet}_HOST
1408     if [ -z "${!varname}" ]; then
1409         if [ "${facet:0:3}" == "ost" ]; then
1410             eval ${facet}_HOST=${ost_HOST}
1411         fi
1412     fi
1413     echo -n ${!varname}
1414 }
1415
1416 facet_active() {
1417     local facet=$1
1418     local activevar=${facet}active
1419
1420     if [ -f $TMP/${facet}active ] ; then
1421         source $TMP/${facet}active
1422     fi
1423
1424     active=${!activevar}
1425     if [ -z "$active" ] ; then
1426         echo -n ${facet}
1427     else
1428         echo -n ${active}
1429     fi
1430 }
1431
1432 facet_active_host() {
1433     local facet=$1
1434     local active=`facet_active $facet`
1435     if [ "$facet" == client ]; then
1436         echo $HOSTNAME
1437     else
1438         echo `facet_host $active`
1439     fi
1440 }
1441
1442 change_active() {
1443     local facet=$1
1444     local failover=${facet}failover
1445     host=`facet_host $failover`
1446     [ -z "$host" ] && return
1447     local curactive=`facet_active $facet`
1448     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
1449         eval export ${facet}active=$facet
1450     else
1451         eval export ${facet}active=$failover
1452     fi
1453     # save the active host for this facet
1454     local activevar=${facet}active
1455     echo "$activevar=${!activevar}" > $TMP/$activevar
1456 }
1457
1458 do_node() {
1459     local verbose=false
1460     # do not stripe off hostname if verbose, bug 19215
1461     if [ x$1 = x--verbose ]; then
1462         shift
1463         verbose=true
1464     fi
1465
1466     local HOST=$1
1467     shift
1468     local myPDSH=$PDSH
1469     if [ "$HOST" = "$HOSTNAME" ]; then
1470         myPDSH="no_dsh"
1471     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
1472         echo "cannot run remote command on $HOST with $myPDSH"
1473         return 128
1474     fi
1475     if $VERBOSE; then
1476         echo "CMD: $HOST $@" >&2
1477         $myPDSH $HOST $LCTL mark "$@" > /dev/null 2>&1 || :
1478     fi
1479
1480     if [ "$myPDSH" = "rsh" ]; then
1481 # we need this because rsh does not return exit code of an executed command
1482         local command_status="$TMP/cs"
1483         rsh $HOST ":> $command_status"
1484         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
1485                     cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
1486                     echo command failed >$command_status"
1487         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
1488         return 0
1489     fi
1490
1491     if $verbose ; then
1492         # print HOSTNAME for myPDSH="no_dsh"
1493         if [[ $myPDSH = no_dsh ]]; then
1494             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
1495         else
1496             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
1497         fi
1498     else
1499         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
1500     fi
1501     return ${PIPESTATUS[0]}
1502 }
1503
1504 single_local_node () {
1505    [ "$1" = "$HOSTNAME" ]
1506 }
1507
1508 do_nodes() {
1509     local verbose=false
1510     # do not stripe off hostname if verbose, bug 19215
1511     if [ x$1 = x--verbose ]; then
1512         shift
1513         verbose=true
1514     fi
1515
1516     local rnodes=$1
1517     shift
1518
1519     if single_local_node $rnodes; then
1520         if $verbose; then
1521            do_node --verbose $rnodes $@
1522         else
1523            do_node $rnodes $@
1524         fi
1525         return $?
1526     fi
1527
1528     # This is part from do_node
1529     local myPDSH=$PDSH
1530
1531     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
1532         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
1533
1534     if $VERBOSE; then
1535         echo "CMD: $rnodes $@" >&2
1536         $myPDSH $rnodes $LCTL mark "$@" > /dev/null 2>&1 || :
1537     fi
1538
1539     if $verbose ; then
1540         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
1541     else
1542         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -re "s/\w+:\s//g"
1543     fi
1544     return ${PIPESTATUS[0]}
1545 }
1546
1547 do_facet() {
1548     local facet=$1
1549     shift
1550     local HOST=`facet_active_host $facet`
1551     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
1552     do_node $HOST "$@"
1553 }
1554
1555 add() {
1556     local facet=$1
1557     shift
1558     # make sure its not already running
1559     stop ${facet} -f
1560     rm -f $TMP/${facet}active
1561     do_facet ${facet} $MKFS $*
1562 }
1563
1564 ostdevname() {
1565     num=$1
1566     DEVNAME=OSTDEV$num
1567     #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
1568     eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}}
1569     echo -n $DEVPTR
1570 }
1571
1572 mdsdevname() {
1573     num=$1
1574     DEVNAME=MDSDEV$num
1575     #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
1576     eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}}
1577     echo -n $DEVPTR
1578 }
1579
1580 ########
1581 ## MountConf setup
1582
1583 stopall() {
1584     # make sure we are using the primary server, so test-framework will
1585     # be able to clean up properly.
1586     activemds=`facet_active mds1`
1587     if [ $activemds != "mds1" ]; then
1588         fail mds1
1589     fi
1590
1591     local clients=$CLIENTS
1592     [ -z $clients ] && clients=$(hostname)
1593
1594     zconf_umount_clients $clients $MOUNT "$*" || true
1595     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
1596
1597     [ "$CLIENTONLY" ] && return
1598     # The add fn does rm ${facet}active file, this would be enough
1599     # if we use do_facet <facet> only after the facet added, but
1600     # currently we use do_facet mds in local.sh
1601     for num in `seq $MDSCOUNT`; do
1602         stop mds$num -f
1603         rm -f ${TMP}/mds${num}active
1604     done
1605
1606     for num in `seq $OSTCOUNT`; do
1607         stop ost$num -f
1608         rm -f $TMP/ost${num}active
1609     done
1610
1611     return 0
1612 }
1613
1614 cleanupall() {
1615     nfs_client_mode && return
1616
1617     stopall $*
1618     unload_modules
1619     cleanup_gss
1620 }
1621
1622 mdsmkfsopts()
1623 {
1624     local nr=$1
1625     test $nr = 1 && echo -n $MDS_MKFS_OPTS || echo -n $MDSn_MKFS_OPTS
1626 }
1627
1628 formatall() {
1629     if [ "$IAMDIR" == "yes" ]; then
1630         MDS_MKFS_OPTS="$MDS_MKFS_OPTS --iam-dir"
1631         MDSn_MKFS_OPTS="$MDSn_MKFS_OPTS --iam-dir"
1632     fi
1633
1634     [ "$FSTYPE" ] && FSTYPE_OPT="--backfstype $FSTYPE"
1635
1636     stopall
1637     # We need ldiskfs here, may as well load them all
1638     load_modules
1639     [ "$CLIENTONLY" ] && return
1640     echo Formatting mgs, mds, osts
1641     if [[ $MDSDEV1 != $MGSDEV ]] || [[ $mds1_HOST != $mgs_HOST ]]; then
1642         add mgs $mgs_MKFS_OPTS $FSTYPE_OPT --reformat $MGSDEV || exit 10
1643     fi
1644
1645     for num in `seq $MDSCOUNT`; do
1646         echo "Format mds$num: $(mdsdevname $num)"
1647         if $VERBOSE; then
1648             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` || exit 9
1649         else
1650             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` > /dev/null || exit 9
1651         fi
1652     done
1653
1654     for num in `seq $OSTCOUNT`; do
1655         echo "Format ost$num: $(ostdevname $num)"
1656         if $VERBOSE; then
1657             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` || exit 10
1658         else
1659             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` > /dev/null || exit 10
1660         fi
1661     done
1662 }
1663
1664 mount_client() {
1665     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
1666 }
1667
1668 umount_client() {
1669     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
1670 }
1671
1672 # return value:
1673 # 0: success, the old identity set already.
1674 # 1: success, the old identity does not set.
1675 # 2: fail.
1676 switch_identity() {
1677     local num=$1
1678     local switch=$2
1679     local j=`expr $num - 1`
1680     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
1681
1682     if [ -z "$MDT" ]; then
1683         return 2
1684     fi
1685
1686     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
1687
1688     if $switch; then
1689         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
1690     else
1691         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
1692     fi
1693
1694     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush \"-1\""
1695
1696     if [ $old = "NONE" ]; then
1697         return 1
1698     else
1699         return 0
1700     fi
1701 }
1702
1703 remount_client()
1704 {
1705         zconf_umount `hostname` $1 || error "umount failed"
1706         zconf_mount `hostname` $1 || error "mount failed"
1707 }
1708
1709 writeconf_facet () {
1710     local facet=$1
1711     local dev=$2
1712
1713     do_facet $facet "$TUNEFS --writeconf $dev"
1714 }
1715
1716 writeconf_all () {
1717     for num in `seq $MDSCOUNT`; do
1718         DEVNAME=$(mdsdevname $num)
1719         writeconf_facet mds$num $DEVNAME
1720     done
1721
1722     for num in `seq $OSTCOUNT`; do
1723         DEVNAME=$(ostdevname $num)
1724         writeconf_facet ost$num $DEVNAME
1725     done
1726 }
1727
1728 setupall() {
1729     nfs_client_mode && return
1730
1731     sanity_mount_check ||
1732         error "environments are insane!"
1733
1734     load_modules
1735
1736     if [ -z "$CLIENTONLY" ]; then
1737         echo Setup mgs, mdt, osts
1738         echo $WRITECONF | grep -q "writeconf" && \
1739             writeconf_all
1740         if [[ $mds1_HOST != $mgs_HOST ]] || [[ $MDSDEV1 != $MGSDEV ]]; then
1741             start mgs $MGSDEV $mgs_MOUNT_OPTS
1742         fi
1743
1744         for num in `seq $MDSCOUNT`; do
1745             DEVNAME=$(mdsdevname $num)
1746             start mds$num $DEVNAME $MDS_MOUNT_OPTS
1747
1748             # We started mds, now we should set failover variables properly.
1749             # Set mds${num}failover_HOST if it is not set (the default failnode).
1750             local varname=mds${num}failover_HOST
1751             if [ -z "${!varname}" ]; then
1752                 eval mds${num}failover_HOST=$(facet_host mds$num)
1753             fi
1754
1755             if [ $IDENTITY_UPCALL != "default" ]; then
1756                 switch_identity $num $IDENTITY_UPCALL
1757             fi
1758         done
1759         for num in `seq $OSTCOUNT`; do
1760             DEVNAME=$(ostdevname $num)
1761             start ost$num $DEVNAME $OST_MOUNT_OPTS
1762
1763             # We started ost$num, now we should set ost${num}failover variable properly.
1764             # Set ost${num}failover_HOST if it is not set (the default failnode).
1765             varname=ost${num}failover_HOST
1766             if [ -z "${!varname}" ]; then
1767                 eval ost${num}failover_HOST=$(facet_host ost${num})
1768             fi
1769
1770         done
1771     fi
1772
1773     init_gss
1774
1775     # wait a while to allow sptlrpc configuration be propogated to targets,
1776     # only needed when mounting new target devices.
1777     if $GSS; then
1778         sleep 10
1779     fi
1780
1781     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
1782     mount_client $MOUNT
1783     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
1784
1785     if [ "$MOUNT_2" ]; then
1786         mount_client $MOUNT2
1787         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
1788     fi
1789
1790     init_param_vars
1791
1792     # by remounting mdt before ost, initial connect from mdt to ost might
1793     # timeout because ost is not ready yet. wait some time to its fully
1794     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
1795     # by a context negotiation rpc with $TIMEOUT.
1796     # FIXME better by monitoring import status.
1797     if $GSS; then
1798         set_flavor_all $SEC
1799         sleep $((TIMEOUT + 5))
1800     else
1801         sleep 5
1802     fi
1803 }
1804
1805 mounted_lustre_filesystems() {
1806         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
1807 }
1808
1809 init_facet_vars () {
1810     [ "$CLIENTONLY" ] && return 0
1811     local facet=$1
1812     shift
1813     local device=$1
1814
1815     shift
1816
1817     eval export ${facet}_dev=${device}
1818     eval export ${facet}_opt=\"$@\"
1819
1820     local dev=${facet}_dev
1821     local label=$(do_facet ${facet} "$E2LABEL ${!dev}")
1822     [ -z "$label" ] && echo no label for ${!dev} && exit 1
1823
1824     eval export ${facet}_svc=${label}
1825
1826     local varname=${facet}failover_HOST
1827     if [ -z "${!varname}" ]; then
1828        eval $varname=$(facet_host $facet) 
1829     fi
1830
1831     # ${facet}failover_dev is set in cfg file
1832     varname=${facet}failover_dev
1833     if [ -n "${!varname}" ] ; then
1834         eval export ${facet}failover_dev=${!varname}
1835     else
1836         eval export ${facet}failover_dev=$device
1837     fi
1838 }
1839
1840 init_facets_vars () {
1841     local DEVNAME
1842
1843     if ! remote_mds_nodsh; then 
1844         for num in `seq $MDSCOUNT`; do
1845             DEVNAME=`mdsdevname $num`
1846             init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
1847         done
1848     fi
1849
1850     remote_ost_nodsh && return
1851
1852     for num in `seq $OSTCOUNT`; do
1853         DEVNAME=`ostdevname $num`
1854         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
1855     done
1856 }
1857
1858 osc_ensure_active () {
1859     local facet=$1
1860     local type=$2
1861     local timeout=$3
1862     local period=0
1863
1864     while [ $period -lt $timeout ]; do
1865         count=$(do_facet $facet "lctl dl | grep '${FSNAME}-OST.*-osc-${type}' | grep ' IN ' 2>/dev/null | wc -l")
1866         if [ $count -eq 0 ]; then
1867             break
1868         fi
1869
1870         echo "There are $count OST are inactive, wait $period seconds, and try again"
1871         sleep 3
1872         period=$((period+3))
1873     done
1874
1875     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
1876 }
1877
1878 som_check() {
1879     SOM_ENABLED=$(do_facet $SINGLEMDS "$LCTL get_param mdt.*.som" | awk -F= ' {print $2}' | head -n 1)
1880     echo $SOM_ENABLED
1881 }
1882
1883 init_param_vars () {
1884     if ! remote_ost_nodsh && ! remote_mds_nodsh; then
1885         export MDSVER=$(do_facet $SINGLEMDS "lctl get_param version" | cut -d. -f1,2)
1886         export OSTVER=$(do_facet ost1 "lctl get_param version" | cut -d. -f1,2)
1887         export CLIVER=$(lctl get_param version | cut -d. -f 1,2)
1888     fi
1889
1890     remote_mds_nodsh ||
1891         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
1892
1893     log "Using TIMEOUT=$TIMEOUT"
1894
1895     osc_ensure_active $SINGLEMDS M $TIMEOUT
1896     osc_ensure_active client c $TIMEOUT
1897
1898     if [ x"$(som_check)" = x"enabled" ]; then
1899         ENABLE_QUOTA=""
1900         echo "disable quota temporary when SOM enabled"
1901     fi
1902     if [ $QUOTA_AUTO -ne 0 ]; then
1903         if [ "$ENABLE_QUOTA" ]; then
1904             echo "enable quota as required"
1905             setup_quota $MOUNT || return 2
1906         else
1907             echo "disable quota as required"
1908             $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
1909         fi
1910     fi
1911
1912     return 0
1913 }
1914
1915 nfs_client_mode () {
1916     if [ "$NFSCLIENT" ]; then
1917         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
1918         local clients=$CLIENTS
1919         [ -z $clients ] && clients=$(hostname)
1920
1921         # FIXME: remove hostname when 19215 fixed
1922         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
1923         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
1924         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
1925         return
1926     fi
1927     return 1
1928 }
1929
1930 check_config_client () {
1931     local mntpt=$1
1932
1933     local mounted=$(mount | grep " $mntpt ")
1934     if [ "$CLIENTONLY" ]; then
1935         # bug 18021
1936         # CLIENTONLY should not depend on *_HOST settings
1937         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
1938         # in theory someone could create a new,
1939         # client-only config file that assumed lustre was already
1940         # configured and didn't set the MGSNID. If MGSNID is not set,
1941         # then we should use the mgs nid currently being used 
1942         # as the default value. bug 18021
1943         [[ x$MGSNID = x ]] &&
1944             MGSNID=${mgc//MGC/}
1945
1946         if [[ x$mgc != xMGC$MGSNID ]]; then
1947             if [ "$mgs_HOST" ]; then
1948                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
1949 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
1950 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
1951             fi
1952         fi
1953         return 0
1954     fi
1955
1956     local myMGS_host=$mgs_HOST   
1957     if [ "$NETTYPE" = "ptl" ]; then
1958         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
1959     fi
1960
1961     echo Checking config lustre mounted on $mntpt
1962     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
1963     mgshost=$(echo $mgshost | awk -F: '{print $1}')
1964
1965 #    if [ "$mgshost" != "$myMGS_host" ]; then
1966 #            log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
1967 #                   Please use correct config or set mds_HOST correctly!"
1968 #    fi
1969
1970 }
1971
1972 check_config_clients () {
1973     local clients=${CLIENTS:-$HOSTNAME}
1974     local mntpt=$1
1975
1976     nfs_client_mode && return
1977
1978     do_rpc_nodes $clients check_config_client $mntpt
1979
1980     sanity_mount_check ||
1981         error "environments are insane!"
1982 }
1983
1984 check_timeout () {
1985     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
1986     local cltimeout=$(lctl get_param -n timeout)
1987     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
1988         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
1989         return 1
1990     fi
1991 }
1992
1993 is_mounted () {
1994     local mntpt=$1
1995     local mounted=$(mounted_lustre_filesystems)
1996
1997     echo $mounted' ' | grep -w -q $mntpt' '
1998 }
1999
2000 check_and_setup_lustre() {
2001     nfs_client_mode && return
2002
2003     local MOUNTED=$(mounted_lustre_filesystems)
2004
2005     local do_check=true
2006     # 1.
2007     # both MOUNT and MOUNT2 are not mounted
2008     if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
2009         [ "$REFORMAT" ] && formatall
2010         # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
2011         setupall
2012         is_mounted $MOUNT || error "NAME=$NAME not mounted"
2013         export I_MOUNTED=yes
2014         do_check=false
2015     # 2.
2016     # MOUNT2 is mounted
2017     elif is_mounted $MOUNT2; then
2018             # 3.
2019             # MOUNT2 is mounted, while MOUNT_2 is not set
2020             if ! [ "$MOUNT_2" ]; then
2021                 cleanup_mount $MOUNT2
2022                 export I_UMOUNTED2=yes
2023
2024             # 4.
2025             # MOUNT2 is mounted, MOUNT_2 is set
2026             else
2027                 # FIXME: what to do if check_config failed?
2028                 # i.e. if:
2029                 # 1) remote client has mounted other Lustre fs ?
2030                 # 2) it has insane env ?
2031                 # let's try umount MOUNT2 on all clients and mount it again:
2032                 if ! check_config_clients $MOUNT2; then
2033                     cleanup_mount $MOUNT2
2034                     restore_mount $MOUNT2
2035                     export I_MOUNTED2=yes
2036                 fi
2037             fi 
2038
2039     # 5.
2040     # MOUNT is mounted MOUNT2 is not mounted
2041     elif [ "$MOUNT_2" ]; then
2042         restore_mount $MOUNT2
2043         export I_MOUNTED2=yes
2044     fi
2045
2046     if $do_check; then
2047         # FIXME: what to do if check_config failed?
2048         # i.e. if:
2049         # 1) remote client has mounted other Lustre fs?
2050         # 2) lustre is mounted on remote_clients atall ?
2051         check_config_clients $MOUNT
2052         init_facets_vars
2053         init_param_vars
2054
2055         do_nodes $(comma_list $(nodes_list)) "lctl set_param debug=\\\"$PTLDEBUG\\\";
2056             lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
2057             lctl set_param debug_mb=${DEBUG_SIZE};
2058             sync"
2059     fi
2060
2061     init_gss
2062     set_flavor_all $SEC
2063
2064     if [ "$ONLY" == "setup" ]; then
2065         exit 0
2066     fi
2067 }
2068
2069 restore_mount () {
2070    local clients=${CLIENTS:-$HOSTNAME}
2071    local mntpt=$1
2072
2073    zconf_mount_clients $clients $mntpt
2074 }
2075
2076 cleanup_mount () {
2077     local clients=${CLIENTS:-$HOSTNAME}
2078     local mntpt=$1
2079
2080     zconf_umount_clients $clients $mntpt    
2081 }
2082
2083 cleanup_and_setup_lustre() {
2084     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
2085         lctl set_param debug=0 || true
2086         cleanupall
2087         if [ "$ONLY" == "cleanup" ]; then
2088             exit 0
2089         fi
2090     fi
2091     check_and_setup_lustre
2092 }
2093
2094 check_and_cleanup_lustre() {
2095     if is_mounted $MOUNT; then
2096         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
2097         [ "$ENABLE_QUOTA" ] && restore_quota_type || true
2098     fi
2099
2100     if [ "$I_UMOUNTED2" = "yes" ]; then
2101         restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
2102     fi
2103
2104     if [ "$I_MOUNTED2" = "yes" ]; then
2105         cleanup_mount $MOUNT2
2106     fi
2107
2108     if [ "$I_MOUNTED" = "yes" ]; then
2109         cleanupall -f || error "cleanup failed"
2110         unset I_MOUNTED
2111     fi
2112 }
2113
2114 #######
2115 # General functions
2116
2117 check_network() {
2118     local NETWORK=0
2119     local WAIT=0
2120     local MAX=$2
2121     while [ $NETWORK -eq 0 ]; do
2122         if ping -c 1 -w 3 $1 > /dev/null; then
2123             NETWORK=1
2124         else
2125             WAIT=$((WAIT + 5))
2126             echo "waiting for $1, $((MAX - WAIT)) secs left"
2127             sleep 5
2128         fi
2129         if [ $WAIT -gt $MAX ]; then
2130             echo "Network not available"
2131             exit 1
2132         fi
2133     done
2134 }
2135 check_port() {
2136     while( !($DSH2 $1 "netstat -tna | grep -q $2") ) ; do
2137         sleep 9
2138     done
2139 }
2140
2141 no_dsh() {
2142     shift
2143     eval $@
2144 }
2145
2146 comma_list() {
2147     # the sed converts spaces to commas, but leaves the last space
2148     # alone, so the line doesn't end with a comma.
2149     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
2150 }
2151
2152 # list, excluded are the comma separated lists
2153 exclude_items_from_list () {
2154     local list=$1
2155     local excluded=$2
2156     local item
2157
2158     list=${list//,/ }
2159     for item in ${excluded//,/ }; do
2160         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
2161     done
2162     echo $(comma_list $list) 
2163 }
2164
2165 # list, expand  are the comma separated lists
2166 expand_list () {
2167     local list=${1//,/ }
2168     local expand=${2//,/ }
2169     local expanded=
2170
2171     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
2172     echo $(comma_list $expanded)
2173 }
2174
2175 testslist_filter () {
2176     local script=$LUSTRE/tests/${TESTSUITE}.sh
2177
2178     [ -f $script ] || return 0
2179
2180     local start_at=$START_AT
2181     local stop_at=$STOP_AT
2182
2183     local var=${TESTSUITE//-/_}_START_AT
2184     [ x"${!var}" != x ] && start_at=${!var}
2185     var=${TESTSUITE//-/_}_STOP_AT
2186     [ x"${!var}" != x ] && stop_at=${!var}
2187
2188     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
2189         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
2190             /^'${start_at}'$/ {flag = 0}
2191             {if (flag == 1) print $0}
2192             /^'${stop_at}'$/ { flag = 1 }'
2193 }
2194
2195 absolute_path() {
2196     (cd `dirname $1`; echo $PWD/`basename $1`)
2197 }
2198
2199 get_facets () {
2200     local name=$(echo $1 | tr "[:upper:]" "[:lower:]")
2201     local type=$(echo $1 | tr "[:lower:]" "[:upper:]")
2202
2203     local list=""
2204     local count=${type}COUNT
2205     for ((i=1; i<=${!count}; i++)) do
2206         list="$list ${name}$i"
2207     done
2208     echo $(comma_list $list)
2209 }
2210
2211 ##################################
2212 # Adaptive Timeouts funcs
2213
2214 at_is_enabled() {
2215     # only check mds, we assume at_max is the same on all nodes
2216     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
2217     if [ $at_max -eq 0 ]; then
2218         return 1
2219     else
2220         return 0
2221     fi
2222 }
2223
2224 at_max_get() {
2225     local facet=$1
2226
2227     # suppose that all ost-s has the same at_max set
2228     if [ $facet == "ost" ]; then
2229         do_facet ost1 "lctl get_param -n at_max"
2230     else
2231         do_facet $facet "lctl get_param -n at_max"
2232     fi
2233 }
2234
2235 at_max_set() {
2236     local at_max=$1
2237     shift
2238
2239     local facet
2240     for facet in $@; do
2241         if [ $facet == "ost" ]; then
2242             for i in `seq $OSTCOUNT`; do
2243                 do_facet ost$i "lctl set_param at_max=$at_max"
2244
2245             done
2246         elif [ $facet == "mds" ]; then
2247             for i in `seq $MDSCOUNT`; do
2248                 do_facet mds$i "lctl set_param at_max=$at_max"
2249             done
2250         else
2251             do_facet $facet "lctl set_param at_max=$at_max"
2252         fi
2253     done
2254 }
2255
2256 ##################################
2257 # OBD_FAIL funcs
2258
2259 drop_request() {
2260 # OBD_FAIL_MDS_ALL_REQUEST_NET
2261     RC=0
2262     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
2263     do_facet client "$1" || RC=$?
2264     do_facet $SINGLEMDS lctl set_param fail_loc=0
2265     return $RC
2266 }
2267
2268 drop_reply() {
2269 # OBD_FAIL_MDS_ALL_REPLY_NET
2270     RC=0
2271     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
2272     do_facet client "$@" || RC=$?
2273     do_facet $SINGLEMDS lctl set_param fail_loc=0
2274     return $RC
2275 }
2276
2277 drop_reint_reply() {
2278 # OBD_FAIL_MDS_REINT_NET_REP
2279     RC=0
2280     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
2281     do_facet client "$@" || RC=$?
2282     do_facet $SINGLEMDS lctl set_param fail_loc=0
2283     return $RC
2284 }
2285
2286 pause_bulk() {
2287 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
2288     RC=0
2289     do_facet ost1 lctl set_param fail_loc=0x214
2290     do_facet client "$1" || RC=$?
2291     do_facet client "sync"
2292     do_facet ost1 lctl set_param fail_loc=0
2293     return $RC
2294 }
2295
2296 drop_ldlm_cancel() {
2297 #define OBD_FAIL_LDLM_CANCEL             0x304
2298     RC=0
2299     do_facet client lctl set_param fail_loc=0x304
2300     do_facet client "$@" || RC=$?
2301     do_facet client lctl set_param fail_loc=0
2302     return $RC
2303 }
2304
2305 drop_bl_callback() {
2306 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
2307     RC=0
2308     do_facet client lctl set_param fail_loc=0x305
2309     do_facet client "$@" || RC=$?
2310     do_facet client lctl set_param fail_loc=0
2311     return $RC
2312 }
2313
2314 drop_ldlm_reply() {
2315 #define OBD_FAIL_LDLM_REPLY              0x30c
2316     RC=0
2317     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
2318     do_facet client "$@" || RC=$?
2319     do_facet $SINGLEMDS lctl set_param fail_loc=0
2320     return $RC
2321 }
2322
2323 clear_failloc() {
2324     facet=$1
2325     pause=$2
2326     sleep $pause
2327     echo "clearing fail_loc on $facet"
2328     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
2329 }
2330
2331 set_nodes_failloc () {
2332     do_nodes $(comma_list $1)  lctl set_param fail_loc=$2
2333 }
2334
2335 cancel_lru_locks() {
2336     $LCTL mark "cancel_lru_locks $1 start"
2337     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
2338         $LCTL set_param -n $d=clear
2339     done
2340     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
2341     $LCTL mark "cancel_lru_locks $1 stop"
2342 }
2343
2344 default_lru_size()
2345 {
2346         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
2347         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
2348         echo "$DEFAULT_LRU_SIZE"
2349 }
2350
2351 lru_resize_enable()
2352 {
2353     lctl set_param ldlm.namespaces.*$1*.lru_size=0
2354 }
2355
2356 lru_resize_disable()
2357 {
2358     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
2359 }
2360
2361 pgcache_empty() {
2362     local FILE
2363     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
2364         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
2365             echo there is still data in page cache $FILE ?
2366             lctl get_param -n $FILE
2367             return 1
2368         fi
2369     done
2370     if [[ $MDSDEV1 != $MGSDEV ]]; then
2371         stop mgs 
2372     fi
2373
2374     return 0
2375 }
2376
2377 debugsave() {
2378     DEBUGSAVE="$(lctl get_param -n debug)"
2379 }
2380
2381 debugrestore() {
2382     [ -n "$DEBUGSAVE" ] && \
2383         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
2384     DEBUGSAVE=""
2385 }
2386
2387 debug_size_save() {
2388     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
2389 }
2390
2391 debug_size_restore() {
2392     [ -n "$DEBUG_SIZE_SAVED" ] && \
2393         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
2394     DEBUG_SIZE_SAVED=""
2395 }
2396
2397 start_full_debug_logging() {
2398     debugsave
2399     debug_size_save
2400
2401     local FULLDEBUG=-1
2402     local DEBUG_SIZE=150
2403
2404     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
2405     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
2406 }
2407
2408 stop_full_debug_logging() {
2409     debug_size_restore
2410     debugrestore
2411 }
2412
2413 ##################################
2414 # Test interface
2415 ##################################
2416
2417 error_noexit() {
2418     local TYPE=${TYPE:-"FAIL"}
2419
2420     local dump=true
2421     # do not dump logs if $1=false
2422     if [ "x$1" = "xfalse" ]; then
2423         shift
2424         dump=false
2425     fi
2426
2427     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
2428
2429     # We need to dump the logs on all nodes
2430     if $dump; then
2431         gather_logs $(comma_list $(nodes_list))
2432     fi
2433
2434     debugrestore
2435     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
2436     echo "$@" > $LOGDIR/err
2437 }
2438
2439 error() {
2440     error_noexit "$@"
2441     if $FAIL_ON_ERROR; then
2442         reset_fail_loc
2443         exit 1
2444     fi
2445 }
2446
2447 error_exit() {
2448     error_noexit "$@"
2449     exit 1
2450 }
2451
2452 # use only if we are ignoring failures for this test, bugno required.
2453 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
2454 # e.g. error_ignore 5494 "your message"
2455 error_ignore() {
2456     local TYPE="IGNORE (bz$1)"
2457     shift
2458     error_noexit "$@"
2459 }
2460
2461 skip_env () {
2462     $FAIL_ON_SKIP_ENV && error false $@ || skip $@
2463 }
2464
2465 skip () {
2466     echo
2467     log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
2468     [ "$TESTSUITELOG" ] && \
2469         echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
2470 }
2471
2472 build_test_filter() {
2473     EXCEPT="$EXCEPT $(testslist_filter)"
2474
2475     [ "$ONLY" ] && log "only running test `echo $ONLY`"
2476     for O in $ONLY; do
2477         eval ONLY_${O}=true
2478     done
2479     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
2480         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
2481     [ "$EXCEPT_SLOW" ] && \
2482         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
2483     for E in $EXCEPT $ALWAYS_EXCEPT; do
2484         eval EXCEPT_${E}=true
2485     done
2486     for E in $EXCEPT_SLOW; do
2487         eval EXCEPT_SLOW_${E}=true
2488     done
2489     for G in $GRANT_CHECK_LIST; do
2490         eval GCHECK_ONLY_${G}=true
2491         done
2492 }
2493
2494 basetest() {
2495     if [[ $1 = [a-z]* ]]; then
2496         echo $1
2497     else
2498         echo ${1%%[a-z]*}
2499     fi
2500 }
2501
2502 # print a newline if the last test was skipped
2503 export LAST_SKIPPED=
2504 run_test() {
2505     assert_DIR
2506
2507     export base=`basetest $1`
2508     if [ ! -z "$ONLY" ]; then
2509         testname=ONLY_$1
2510         if [ ${!testname}x != x ]; then
2511             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2512             run_one_logged $1 "$2"
2513             return $?
2514         fi
2515         testname=ONLY_$base
2516         if [ ${!testname}x != x ]; then
2517             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2518             run_one_logged $1 "$2"
2519             return $?
2520         fi
2521         LAST_SKIPPED="y"
2522         echo -n "."
2523         return 0
2524     fi
2525     testname=EXCEPT_$1
2526     if [ ${!testname}x != x ]; then
2527         LAST_SKIPPED="y"
2528         TESTNAME=test_$1 skip "skipping excluded test $1"
2529         return 0
2530     fi
2531     testname=EXCEPT_$base
2532     if [ ${!testname}x != x ]; then
2533         LAST_SKIPPED="y"
2534         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
2535         return 0
2536     fi
2537     testname=EXCEPT_SLOW_$1
2538     if [ ${!testname}x != x ]; then
2539         LAST_SKIPPED="y"
2540         TESTNAME=test_$1 skip "skipping SLOW test $1"
2541         return 0
2542     fi
2543     testname=EXCEPT_SLOW_$base
2544     if [ ${!testname}x != x ]; then
2545         LAST_SKIPPED="y"
2546         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
2547         return 0
2548     fi
2549
2550     LAST_SKIPPED=
2551     run_one_logged $1 "$2"
2552
2553     return $?
2554 }
2555
2556 EQUALS="======================================================================"
2557 equals_msg() {
2558     msg="$@"
2559
2560     local suffixlen=$((${#EQUALS} - ${#msg}))
2561     [ $suffixlen -lt 5 ] && suffixlen=5
2562     log `echo $(printf '===== %s %.*s\n' "$msg" $suffixlen $EQUALS)`
2563 }
2564
2565 log() {
2566     echo "$*"
2567     module_loaded lnet || load_modules
2568
2569     local MSG="$*"
2570     # Get rid of '
2571     MSG=${MSG//\'/\\\'}
2572     MSG=${MSG//\(/\\\(}
2573     MSG=${MSG//\)/\\\)}
2574     MSG=${MSG//\;/\\\;}
2575     MSG=${MSG//\|/\\\|}
2576     MSG=${MSG//\>/\\\>}
2577     MSG=${MSG//\</\\\<}
2578     MSG=${MSG//\//\\\/}
2579     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
2580 }
2581
2582 trace() {
2583         log "STARTING: $*"
2584         strace -o $TMP/$1.strace -ttt $*
2585         RC=$?
2586         log "FINISHED: $*: rc $RC"
2587         return 1
2588 }
2589
2590 pass() {
2591     # Set TEST_STATUS here; will be used for logging the result
2592     if [ -f $LOGDIR/err ]; then
2593         TEST_STATUS="FAIL"
2594     else
2595         TEST_STATUS="PASS"
2596     fi
2597     echo $TEST_STATUS " " $@
2598 }
2599
2600 check_mds() {
2601     FFREE=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filesfree | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2602     FTOTAL=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filestotal | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2603     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
2604 }
2605
2606 reset_fail_loc () {
2607     echo -n "Resetting fail_loc on all nodes..."
2608     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
2609     echo done.
2610 }
2611
2612 run_one() {
2613     local testnum=$1
2614     local message=$2
2615     local start_tm=$3
2616     tfile=f${testnum}
2617     export tdir=d0.${TESTSUITE}/d${base}
2618     export TESTNAME=test_$testnum
2619     local SAVE_UMASK=`umask`
2620     umask 0022
2621
2622     log "== test $testnum: $message == `date +%H:%M:%S` ($start_tm)"
2623     test_${testnum} || error "test_$testnum failed with $?"
2624     cd $SAVE_PWD
2625     reset_fail_loc
2626     check_grant ${testnum} || error "check_grant $testnum failed with $?"
2627     check_catastrophe || error "LBUG/LASSERT detected"
2628     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
2629     unset TESTNAME
2630     unset tdir
2631     umask $SAVE_UMASK
2632     return 0
2633 }
2634
2635 run_one_logged() {
2636     local BEFORE=`date +%s`
2637     local TEST_ERROR
2638     local name=${TESTSUITE}.test_${1}.test_log.$(hostname).log
2639     local test_log=$LOGDIR/$name
2640     rm -rf $LOGDIR/err
2641
2642     echo
2643     run_one $1 "$2" $BEFORE 2>&1 | tee $test_log
2644     local RC=${PIPESTATUS[0]}
2645
2646     [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] && \
2647         echo "test_$1 returned $RC" | tee $LOGDIR/err
2648
2649     duration=$((`date +%s` - $BEFORE))
2650     pass "(${duration}s)"
2651     [ -f $LOGDIR/err ] && TEST_ERROR=$(cat $LOGDIR/err)
2652     log_sub_test test_${1} $TEST_STATUS $duration "$RC" "$TEST_ERROR"
2653
2654     if [ -f $LOGDIR/err ]; then
2655         $FAIL_ON_ERROR && exit $RC
2656     fi
2657
2658     return 0
2659 }
2660
2661 canonical_path() {
2662     (cd `dirname $1`; echo $PWD/`basename $1`)
2663 }
2664
2665 sync_clients() {
2666     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
2667     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
2668         cd $SAVE_PWD
2669 }
2670
2671 check_grant() {
2672     export base=`basetest $1`
2673     [ "$CHECK_GRANT" == "no" ] && return 0
2674
2675         testname=GCHECK_ONLY_${base}
2676         [ ${!testname}x == x ] && return 0
2677
2678     echo -n "checking grant......"
2679         cd $SAVE_PWD
2680         # write some data to sync client lost_grant
2681         rm -f $DIR1/${tfile}_check_grant_* 2>&1
2682         for i in `seq $OSTCOUNT`; do
2683                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
2684                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
2685                                               count=1 > /dev/null 2>&1
2686         done
2687         # sync all the data and make sure no pending data on server
2688         sync_clients
2689         
2690         #get client grant and server grant
2691         client_grant=0
2692     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
2693                 client_grant=$((client_grant + $d))
2694         done
2695         server_grant=0
2696         for d in `lctl get_param -n obdfilter.*.tot_granted`; do
2697                 server_grant=$((server_grant + $d))
2698         done
2699
2700         # cleanup the check_grant file
2701         for i in `seq $OSTCOUNT`; do
2702                 rm $DIR1/${tfile}_check_grant_$i
2703         done
2704
2705         #check whether client grant == server grant
2706         if [ $client_grant != $server_grant ]; then
2707                 echo "failed: client:${client_grant} server: ${server_grant}"
2708                 return 1
2709         else
2710                 echo "pass"
2711         fi
2712 }
2713
2714 ########################
2715 # helper functions
2716
2717 osc_to_ost()
2718 {
2719     osc=$1
2720     ost=`echo $1 | awk -F_ '{print $3}'`
2721     if [ -z $ost ]; then
2722         ost=`echo $1 | sed 's/-osc.*//'`
2723     fi
2724     echo $ost
2725 }
2726
2727 remote_node () {
2728     local node=$1
2729     [ "$node" != "$(hostname)" ]
2730 }
2731
2732 remote_mds ()
2733 {
2734     local node
2735     for node in $(mdts_nodes); do
2736         remote_node $node && return 0
2737     done
2738     return 1
2739 }
2740
2741 remote_mds_nodsh()
2742 {
2743     [ "$CLIENTONLY" ] && return 0 || true
2744     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
2745 }
2746
2747 require_dsh_mds()
2748 {
2749         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
2750             MSKIPPED=1 && return 1
2751         return 0
2752 }
2753
2754 remote_ost ()
2755 {
2756     local node
2757     for node in $(osts_nodes) ; do
2758         remote_node $node && return 0
2759     done
2760     return 1
2761 }
2762
2763 remote_ost_nodsh()
2764 {
2765     [ "$CLIENTONLY" ] && return 0 || true 
2766     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2767 }
2768
2769 require_dsh_ost()
2770 {
2771         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
2772             OSKIPPED=1 && return 1
2773         return 0
2774 }
2775
2776 remote_mgs_nodsh()
2777 {
2778     local MGS 
2779     MGS=$(facet_host mgs)
2780     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2781 }
2782
2783 local_mode ()
2784 {
2785     remote_mds_nodsh || remote_ost_nodsh || \
2786         $(single_local_node $(comma_list $(nodes_list)))
2787 }
2788
2789 mdts_nodes () {
2790     local MDSNODES
2791     local NODES_sort
2792     for num in `seq $MDSCOUNT`; do
2793         MDSNODES="$MDSNODES $(facet_host mds$num)"
2794     done
2795     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
2796
2797     echo $NODES_sort
2798 }
2799
2800 remote_servers () {
2801     remote_ost && remote_mds
2802 }
2803
2804 osts_nodes () {
2805     local OSTNODES=$(facet_host ost1)
2806     local NODES_sort
2807
2808     for num in `seq $OSTCOUNT`; do
2809         local myOST=$(facet_host ost$num)
2810         OSTNODES="$OSTNODES $myOST"
2811     done
2812     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
2813
2814     echo $NODES_sort
2815 }
2816
2817 nodes_list () {
2818     # FIXME. We need a list of clients
2819     local myNODES=$HOSTNAME
2820     local myNODES_sort
2821
2822     # CLIENTS (if specified) contains the local client
2823     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
2824
2825     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
2826         myNODES="$myNODES $(osts_nodes) $(mdts_nodes)"
2827     fi
2828
2829     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
2830
2831     echo $myNODES_sort
2832 }
2833
2834 remote_nodes_list () {
2835     local rnodes=$(nodes_list)
2836     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2837     echo $rnodes
2838 }
2839
2840 init_clients_lists () {
2841     # Sanity check: exclude the local client from RCLIENTS
2842     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2843
2844     # Sanity check: exclude the dup entries
2845     rclients=$(for i in $rclients; do echo $i; done | sort -u)
2846
2847     local clients="$SINGLECLIENT $HOSTNAME $rclients"
2848
2849     # Sanity check: exclude the dup entries from CLIENTS
2850     # for those configs which has SINGLCLIENT set to local client
2851     clients=$(for i in $clients; do echo $i; done | sort -u)
2852
2853     CLIENTS=`comma_list $clients`
2854     local -a remoteclients=($rclients)
2855     for ((i=0; $i<${#remoteclients[@]}; i++)); do
2856             varname=CLIENT$((i + 2))
2857             eval $varname=${remoteclients[i]}
2858     done
2859
2860     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
2861 }
2862
2863 get_random_entry () {
2864     local rnodes=$1
2865
2866     rnodes=${rnodes//,/ }
2867
2868     local -a nodes=($rnodes)
2869     local num=${#nodes[@]} 
2870     local i=$((RANDOM * num * 2 / 65536))
2871
2872     echo ${nodes[i]}
2873 }
2874
2875 client_only () {
2876     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
2877 }
2878
2879 is_patchless ()
2880 {
2881     lctl get_param version | grep -q patchless
2882 }
2883
2884 check_versions () {
2885     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
2886 }
2887
2888 get_node_count() {
2889     local nodes="$@"
2890     echo $nodes | wc -w || true
2891 }
2892
2893 mixed_ost_devs () {
2894     local nodes=$(osts_nodes)
2895     local osscount=$(get_node_count "$nodes")
2896     [ ! "$OSTCOUNT" = "$osscount" ]
2897 }
2898
2899 mixed_mdt_devs () {
2900     local nodes=$(mdts_nodes)
2901     local mdtcount=$(get_node_count "$nodes")
2902     [ ! "$MDSCOUNT" = "$mdtcount" ]
2903 }
2904
2905 generate_machine_file() {
2906     local nodes=${1//,/ }
2907     local machinefile=$2
2908     rm -f $machinefile || error "can't rm $machinefile"
2909     for node in $nodes; do
2910         echo $node >>$machinefile
2911     done
2912 }
2913
2914 get_stripe () {
2915     local file=$1/stripe
2916     touch $file
2917     $LFS getstripe -v $file || error
2918     rm -f $file
2919 }
2920
2921 check_runas_id_ret() {
2922     local myRC=0
2923     local myRUNAS_UID=$1
2924     local myRUNAS_GID=$2
2925     shift 2
2926     local myRUNAS=$@
2927     if [ -z "$myRUNAS" ]; then
2928         error_exit "myRUNAS command must be specified for check_runas_id"
2929     fi
2930     if $GSS_KRB5; then
2931         $myRUNAS krb5_login.sh || \
2932             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
2933     fi
2934     mkdir $DIR/d0_runas_test
2935     chmod 0755 $DIR
2936     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
2937     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
2938     rm -rf $DIR/d0_runas_test
2939     return $myRC
2940 }
2941
2942 check_runas_id() {
2943     local myRUNAS_UID=$1
2944     local myRUNAS_GID=$2
2945     shift 2
2946     local myRUNAS=$@
2947     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
2948         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
2949         Please set RUNAS_ID to some UID which exists on MDS and client or
2950         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
2951 }
2952
2953 # obtain the UID/GID for MPI_USER
2954 get_mpiuser_id() {
2955     local mpi_user=$1
2956
2957     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
2958 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
2959
2960     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
2961 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
2962 }
2963
2964 # obtain and cache Kerberos ticket-granting ticket
2965 refresh_krb5_tgt() {
2966     local myRUNAS_UID=$1
2967     local myRUNAS_GID=$2
2968     shift 2
2969     local myRUNAS=$@
2970     if [ -z "$myRUNAS" ]; then
2971         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
2972     fi
2973
2974     CLIENTS=${CLIENTS:-$HOSTNAME}
2975     do_nodes $CLIENTS "set -x
2976 if ! $myRUNAS krb5_login.sh; then
2977     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
2978     exit 1
2979 fi"
2980 }
2981
2982 # Run multiop in the background, but wait for it to print
2983 # "PAUSING" to its stdout before returning from this function.
2984 multiop_bg_pause() {
2985     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
2986     FILE=$1
2987     ARGS=$2
2988
2989     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
2990     mkfifo $TMPPIPE
2991
2992     echo "$MULTIOP_PROG $FILE v$ARGS"
2993     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
2994
2995     echo "TMPPIPE=${TMPPIPE}"
2996     read -t 60 multiop_output < $TMPPIPE
2997     if [ $? -ne 0 ]; then
2998         rm -f $TMPPIPE
2999         return 1
3000     fi
3001     rm -f $TMPPIPE
3002     if [ "$multiop_output" != "PAUSING" ]; then
3003         echo "Incorrect multiop output: $multiop_output"
3004         kill -9 $PID
3005         return 1
3006     fi
3007
3008     return 0
3009 }
3010
3011 do_and_time () {
3012     local cmd=$1
3013     local rc
3014
3015     SECONDS=0
3016     eval '$cmd'
3017     
3018     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
3019
3020     echo $SECONDS
3021     return $rc
3022 }
3023
3024 inodes_available () {
3025     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
3026     echo $IFree
3027 }
3028
3029 # reset llite stat counters
3030 clear_llite_stats(){
3031         lctl set_param -n llite.*.stats 0
3032 }
3033
3034 # sum llite stat items
3035 calc_llite_stats() {
3036         local res=$(lctl get_param -n llite.*.stats |
3037                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
3038         echo $res
3039 }
3040
3041 # reset osc stat counters
3042 clear_osc_stats(){
3043         lctl set_param -n osc.*.osc_stats 0
3044 }
3045
3046 # sum osc stat items
3047 calc_osc_stats() {
3048         local res=$(lctl get_param -n osc.*.osc_stats |
3049                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
3050         echo $res
3051 }
3052
3053 calc_sum () {
3054         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
3055 }
3056
3057 calc_osc_kbytes () {
3058         df $MOUNT > /dev/null
3059         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
3060 }
3061
3062 # save_lustre_params(node, parameter_mask)
3063 # generate a stream of formatted strings (<node> <param name>=<param value>)
3064 save_lustre_params() {
3065         local s
3066         do_nodes --verbose $1 "lctl get_param $2 | while read s; do echo \\\$s; done"
3067 }
3068
3069 # restore lustre parameters from input stream, produces by save_lustre_params
3070 restore_lustre_params() {
3071         local node
3072         local name
3073         local val
3074         while IFS=" =" read node name val; do
3075                 do_node ${node//:/} "lctl set_param -n $name $val"
3076         done
3077 }
3078
3079 check_catastrophe() {
3080     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
3081     local C=$CATASTROPHE
3082     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
3083
3084     if [ $rnodes ]; then
3085         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
3086 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
3087 exit \\\$rc;"
3088     fi 
3089 }
3090
3091 # $1 node
3092 # $2 file
3093 # $3 $RUNAS
3094 get_stripe_info() {
3095         local tmp_file
3096
3097         stripe_size=0
3098         stripe_count=0
3099         stripe_index=0
3100         tmp_file=$(mktemp)
3101
3102         do_facet $1 $3 lfs getstripe -v $2 > $tmp_file
3103
3104         stripe_size=`awk '$1 ~ /size/ {print $2}' $tmp_file`
3105         stripe_count=`awk '$1 ~ /count/ {print $2}' $tmp_file`
3106         stripe_index=`awk '$1 ~ /stripe_offset/ {print $2}' $tmp_file`
3107         rm -f $tmp_file
3108 }
3109
3110 # CMD: determine mds index where directory inode presents
3111 get_mds_dir () {
3112     local dir=$1
3113     local file=$dir/f0.get_mds_dir_tmpfile
3114
3115     mkdir -p $dir
3116     rm -f $file
3117     sleep 1
3118     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
3119     local -a oldused=($iused)
3120
3121     openfile -f O_CREAT:O_LOV_DELAY_CREATE -m 0644 $file > /dev/null
3122     sleep 1
3123     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
3124     local -a newused=($iused)
3125
3126     local num=0
3127     for ((i=0; i<${#newused[@]}; i++)); do
3128          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
3129              echo $(( i + 1 ))
3130              rm -f $file
3131              return 0
3132          fi
3133     done
3134     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
3135 }
3136
3137 mdsrate_cleanup () {
3138     if [ -d $4 ]; then
3139         mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
3140         rmdir $4
3141     fi
3142 }
3143
3144 delayed_recovery_enabled () {
3145     local var=${SINGLEMDS}_svc
3146     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
3147 }
3148
3149 ########################
3150
3151 convert_facet2label() { 
3152     local facet=$1
3153
3154     if [ x$facet = xost ]; then
3155        facet=ost1
3156     fi
3157
3158     local varsvc=${facet}_svc
3159
3160     if [ -n ${!varsvc} ]; then
3161         echo ${!varsvc}
3162     else  
3163         error "No lablel for $facet!"
3164     fi
3165 }
3166
3167 get_clientosc_proc_path() {
3168     local ost=$1
3169
3170     echo "{$1}-osc-*"
3171 }
3172
3173 get_lustre_version () {
3174     local node=${1:-"mds"}    
3175     do_facet $node $LCTL get_param -n version |  awk '/^lustre:/ {print $2}'
3176 }
3177
3178 get_mds_version_major () {
3179     local version=$(get_lustre_version mds)
3180     echo $version | awk -F. '{print $1}'
3181 }
3182
3183 get_mds_version_minor () {
3184     local version=$(get_lustre_version mds)
3185     echo $version | awk -F. '{print $2}'
3186 }
3187
3188 get_mdtosc_proc_path() {
3189     local ost=$1
3190     local major=$(get_mds_version_major)
3191     local minor=$(get_mds_version_minor)
3192     if [ $major -le 1 -a $minor -le 8 ] ; then
3193         echo "${ost}-osc"
3194     else
3195         echo "${ost}-osc-MDT0000"
3196     fi
3197 }
3198
3199 get_osc_import_name() {
3200     local facet=$1
3201     local ost=$2
3202     local label=$(convert_facet2label $ost)
3203
3204     if [ "$facet" == "mds" ]; then
3205         get_mdtosc_proc_path $label
3206         return 0
3207     fi
3208
3209     get_clientosc_proc_path $label
3210     return 0
3211 }
3212
3213 wait_import_state () {
3214     local expected=$1
3215     local CONN_PROC=$2
3216     local CONN_STATE
3217     local i=0
3218
3219     CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3220     while [ "${CONN_STATE}" != "${expected}" ]; do
3221         if [ "${expected}" == "DISCONN" ]; then
3222             # for disconn we can check after proc entry is removed
3223             [ "x${CONN_STATE}" == "x" ] && return 0
3224             #  with AT we can have connect request timeout ~ reconnect timeout
3225             # and test can't see real disconnect
3226             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
3227         fi
3228         # disconnect rpc should be wait not more obd_timeout
3229         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
3230             error "can't put import for $CONN_PROC into ${expected} state" && return 1
3231         sleep 1
3232         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3233         i=$(($i + 1))
3234     done
3235
3236     log "$CONN_PROC now in ${CONN_STATE} state"
3237     return 0
3238 }
3239
3240 wait_osc_import_state() {
3241     local facet=$1
3242     local ost_facet=$2
3243     local expected=$3
3244     local ost=$(get_osc_import_name $facet $ost_facet)
3245     local CONN_PROC
3246     local CONN_STATE
3247     local i=0
3248
3249     CONN_PROC="osc.${ost}.ost_server_uuid"
3250     CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3251     while [ "${CONN_STATE}" != "${expected}" ]; do
3252         if [ "${expected}" == "DISCONN" ]; then 
3253             # for disconn we can check after proc entry is removed
3254             [ "x${CONN_STATE}" == "x" ] && return 0
3255             #  with AT we can have connect request timeout ~ reconnect timeout
3256             # and test can't see real disconnect
3257             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
3258         fi
3259         # disconnect rpc should be wait not more obd_timeout
3260         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
3261             error "can't put import for ${ost}(${ost_facet}) into ${expected} state" && return 1
3262         sleep 1
3263         CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3264         i=$(($i + 1))
3265     done
3266
3267     log "${ost_facet} now in ${CONN_STATE} state"
3268     return 0
3269 }
3270 get_clientmdc_proc_path() {
3271     echo "${1}-mdc-*"
3272 }
3273
3274 do_rpc_nodes () {
3275     local list=$1
3276     shift
3277
3278     # Add paths to lustre tests for 32 and 64 bit systems.
3279     local RPATH="$RLUSTRE/tests:/usr/lib/lustre/tests:/usr/lib64/lustre/tests:$PATH"
3280     do_nodes --verbose $list "PATH=$RPATH sh rpc.sh $@ "
3281 }
3282
3283 wait_clients_import_state () {
3284     local list=$1
3285     local facet=$2
3286     local expected=$3
3287     shift
3288
3289     local label=$(convert_facet2label $facet)
3290     local proc_path
3291     case $facet in
3292         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
3293         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
3294         *) error "unknown facet!" ;;
3295     esac
3296
3297     if ! do_rpc_nodes $list wait_import_state $expected $proc_path; then
3298         error "import is not in ${expected} state"
3299         return 1
3300     fi
3301 }
3302
3303 oos_full() {
3304         local -a AVAILA
3305         local -a GRANTA
3306         local OSCFULL=1
3307         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
3308                   $LCTL get_param obdfilter.*.kbytesavail))
3309         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
3310                   $LCTL get_param -n obdfilter.*.tot_granted))
3311         for ((i=0; i<${#AVAILA[@]}; i++)); do
3312                 local -a AVAIL1=(${AVAILA[$i]//=/ })
3313                 GRANT=$((${GRANTA[$i]}/1024))
3314                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} grnt=$GRANT diff=$((AVAIL1[1] - GRANT))
3315                 [ $((AVAIL1[1] - GRANT)) -lt 400 ] && OSCFULL=0 && echo " FULL" || echo
3316         done
3317         return $OSCFULL
3318 }
3319
3320 pool_list () {
3321    do_facet mgs lctl pool_list $1
3322 }
3323
3324 create_pool() {
3325     local fsname=${1%%.*}
3326     local poolname=${1##$fsname.}
3327
3328     do_facet mgs lctl pool_new $1
3329     local RC=$?
3330     # get param should return err unless pool is created
3331     [[ $RC -ne 0 ]] && return $RC
3332
3333     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
3334         2>/dev/null || echo foo" "" || RC=1
3335     if [[ $RC -eq 0 ]]; then
3336         add_pool_to_list $1
3337     else
3338         error "pool_new failed $1"
3339     fi
3340     return $RC
3341 }
3342
3343 add_pool_to_list () {
3344     local fsname=${1%%.*}
3345     local poolname=${1##$fsname.}
3346
3347     local listvar=${fsname}_CREATED_POOLS
3348     eval export ${listvar}=$(expand_list ${!listvar} $poolname)
3349 }
3350
3351 remove_pool_from_list () {
3352     local fsname=${1%%.*}
3353     local poolname=${1##$fsname.}
3354
3355     local listvar=${fsname}_CREATED_POOLS
3356     eval export ${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
3357 }
3358
3359 destroy_pool_int() {
3360     local ost
3361     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
3362         awk '$1 !~ /^Pool:/ {print $1}')
3363     for ost in $OSTS; do
3364         do_facet mgs lctl pool_remove $1 $ost
3365     done
3366     do_facet mgs lctl pool_destroy $1
3367 }
3368
3369 # <fsname>.<poolname> or <poolname>
3370 destroy_pool() {
3371     local fsname=${1%%.*}
3372     local poolname=${1##$fsname.}
3373
3374     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
3375
3376     local RC
3377
3378     pool_list $fsname.$poolname || return $?
3379
3380     destroy_pool_int $fsname.$poolname
3381     RC=$?
3382     [[ $RC -ne 0 ]] && return $RC
3383
3384     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
3385       2>/dev/null || echo foo" "foo" || RC=1
3386
3387     if [[ $RC -eq 0 ]]; then
3388         remove_pool_from_list $fsname.$poolname
3389     else
3390         error "destroy pool failed $1"
3391     fi
3392     return $RC
3393 }
3394
3395 destroy_pools () {
3396     local fsname=${1:-$FSNAME}
3397     local poolname
3398     local listvar=${fsname}_CREATED_POOLS
3399
3400     pool_list $fsname
3401
3402     [ x${!listvar} = x ] && return 0
3403
3404     echo destroy the created pools: ${!listvar}
3405     for poolname in ${!listvar//,/ }; do
3406         destroy_pool $fsname.$poolname 
3407     done
3408 }
3409
3410 cleanup_pools () {
3411     local fsname=${1:-$FSNAME}
3412     trap 0
3413     destroy_pools $fsname
3414 }
3415
3416 gather_logs () {
3417     local list=$1
3418
3419     local ts=$(date +%s)
3420
3421     # bug 20237, comment 11
3422     # It would also be useful to provide the option
3423     # of writing the file to an NFS directory so it doesn't need to be copied.
3424     local tmp=$TMP
3425     local docp=true
3426     [ -f $LOGDIR/shared ] && docp=false
3427  
3428     # dump lustre logs, dmesg
3429
3430     prefix="$LOGDIR/${TESTSUITE}.${TESTNAME}"
3431     suffix="$ts.log"
3432     echo "Dumping lctl log to ${prefix}.*.${suffix}"
3433
3434     if [ "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
3435         echo "Dumping logs only on local client."
3436         $LCTL dk > ${prefix}.debug_log.$(hostname).${suffix}
3437         dmesg > ${prefix}.dmesg.$(hostname).${suffix}
3438         return
3439     fi
3440
3441     do_nodes --verbose $list \
3442         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname).${suffix};
3443          dmesg > ${prefix}.dmesg.\\\$(hostname).${suffix}"
3444     if [ ! -f $LOGDIR/shared ]; then
3445         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
3446       fi
3447
3448     local archive=$LOGDIR/${TESTSUITE}-$ts.tar.bz2
3449     tar -jcf $archive $LOGDIR/*$ts* $LOGDIR/*${TESTSUITE}*
3450
3451     echo $archive
3452 }
3453
3454 cleanup_logs () {
3455     local list=${1:-$(comma_list $(nodes_list))}
3456
3457     [ -n ${TESTSUITE} ] && do_nodes $list "rm -f $TMP/*${TESTSUITE}*" || true
3458 }
3459
3460 do_ls () {
3461     local mntpt_root=$1
3462     local num_mntpts=$2
3463     local dir=$3
3464     local i
3465     local cmd
3466     local pids
3467     local rc=0
3468
3469     for i in $(seq 0 $num_mntpts); do
3470         cmd="ls -laf ${mntpt_root}$i/$dir"
3471         echo + $cmd;
3472         $cmd > /dev/null &
3473         pids="$pids $!"
3474     done
3475     echo pids=$pids
3476     for pid in $pids; do
3477         wait $pid || rc=$?
3478     done
3479
3480     return $rc
3481 }
3482
3483 get_clients_mount_count () {
3484     local clients=${CLIENTS:-`hostname`}
3485
3486     # we need to take into account the clients mounts and
3487     # exclude mds/ost mounts if any;
3488     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
3489 }
3490
3491 # gss functions
3492 PROC_CLI="srpc_info"
3493
3494 combination()
3495 {
3496     local M=$1
3497     local N=$2
3498     local R=1
3499
3500     if [ $M -lt $N ]; then
3501         R=0
3502     else
3503         N=$((N + 1))
3504         while [ $N -le $M ]; do
3505             R=$((R * N))
3506             N=$((N + 1))
3507         done
3508     fi
3509
3510     echo $R
3511     return 0
3512 }
3513
3514 calc_connection_cnt() {
3515     local dir=$1
3516
3517     # MDT->MDT = 2 * C(M, 2)
3518     # MDT->OST = M * O
3519     # CLI->OST = C * O
3520     # CLI->MDT = C * M
3521     comb_m2=$(combination $MDSCOUNT 2)
3522
3523     local num_clients=$(get_clients_mount_count)
3524
3525     local cnt_mdt2mdt=$((comb_m2 * 2))
3526     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
3527     local cnt_cli2ost=$((num_clients * OSTCOUNT))
3528     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
3529     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
3530     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
3531     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
3532
3533     local var=cnt_$dir
3534     local res=${!var}
3535
3536     echo $res
3537 }
3538
3539 set_rule()
3540 {
3541     local tgt=$1
3542     local net=$2
3543     local dir=$3
3544     local flavor=$4
3545     local cmd="$tgt.srpc.flavor"
3546
3547     if [ $net == "any" ]; then
3548         net="default"
3549     fi
3550     cmd="$cmd.$net"
3551
3552     if [ $dir != "any" ]; then
3553         cmd="$cmd.$dir"
3554     fi
3555
3556     cmd="$cmd=$flavor"
3557     log "Setting sptlrpc rule: $cmd"
3558     do_facet mgs "$LCTL conf_param $cmd"
3559 }
3560
3561 count_flvr()
3562 {
3563     local output=$1
3564     local flavor=$2
3565     local count=0
3566
3567     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
3568     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
3569
3570     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
3571
3572     if [ "x$bulkspec" != "x" ]; then
3573         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
3574
3575         if [ "x$algs" != "x" ]; then
3576             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
3577         else
3578             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
3579             if [ $bulk == "bulkn" ]; then
3580                 bulk_count=`echo "$output" | grep "bulk flavor" \
3581                             | grep "null/null" | wc -l`
3582             elif [ $bulk == "bulki" ]; then
3583                 bulk_count=`echo "$output" | grep "bulk flavor" \
3584                             | grep "/null" | grep -v "null/" | wc -l`
3585             else
3586                 bulk_count=`echo "$output" | grep "bulk flavor" \
3587                             | grep -v "/null" | grep -v "null/" | wc -l`
3588             fi
3589         fi
3590
3591         [ $bulk_count -lt $count ] && count=$bulk_count
3592     fi
3593
3594     echo $count
3595 }
3596
3597 flvr_cnt_cli2mdt()
3598 {
3599     local flavor=$1
3600     local cnt
3601
3602     local clients=${CLIENTS:-`hostname`}
3603
3604     for c in ${clients//,/ }; do
3605         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
3606         tmpcnt=`count_flvr "$output" $flavor`
3607         cnt=$((cnt + tmpcnt))
3608     done
3609     echo $cnt
3610 }
3611
3612 flvr_cnt_cli2ost()
3613 {
3614     local flavor=$1
3615     local cnt
3616
3617     local clients=${CLIENTS:-`hostname`}
3618
3619     for c in ${clients//,/ }; do
3620         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
3621         tmpcnt=`count_flvr "$output" $flavor`
3622         cnt=$((cnt + tmpcnt))
3623     done
3624     echo $cnt
3625 }
3626
3627 flvr_cnt_mdt2mdt()
3628 {
3629     local flavor=$1
3630     local cnt=0
3631
3632     if [ $MDSCOUNT -le 1 ]; then
3633         echo 0
3634         return
3635     fi
3636
3637     for num in `seq $MDSCOUNT`; do
3638         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
3639         tmpcnt=`count_flvr "$output" $flavor`
3640         cnt=$((cnt + tmpcnt))
3641     done
3642     echo $cnt;
3643 }
3644
3645 flvr_cnt_mdt2ost()
3646 {
3647     local flavor=$1
3648     local cnt=0
3649
3650     for num in `seq $MDSCOUNT`; do
3651         output=`do_facet mds$num lctl get_param -n osc.*OST*-osc-MDT*.$PROC_CLI 2>/dev/null`
3652         tmpcnt=`count_flvr "$output" $flavor`
3653         cnt=$((cnt + tmpcnt))
3654     done
3655     echo $cnt;
3656 }
3657
3658 flvr_cnt_mgc2mgs()
3659 {
3660     local flavor=$1
3661
3662     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
3663     count_flvr "$output" $flavor
3664 }
3665
3666 do_check_flavor()
3667 {
3668     local dir=$1        # from to
3669     local flavor=$2     # flavor expected
3670     local res=0
3671
3672     if [ $dir == "cli2mdt" ]; then
3673         res=`flvr_cnt_cli2mdt $flavor`
3674     elif [ $dir == "cli2ost" ]; then
3675         res=`flvr_cnt_cli2ost $flavor`
3676     elif [ $dir == "mdt2mdt" ]; then
3677         res=`flvr_cnt_mdt2mdt $flavor`
3678     elif [ $dir == "mdt2ost" ]; then
3679         res=`flvr_cnt_mdt2ost $flavor`
3680     elif [ $dir == "all2ost" ]; then
3681         res1=`flvr_cnt_mdt2ost $flavor`
3682         res2=`flvr_cnt_cli2ost $flavor`
3683         res=$((res1 + res2))
3684     elif [ $dir == "all2mdt" ]; then
3685         res1=`flvr_cnt_mdt2mdt $flavor`
3686         res2=`flvr_cnt_cli2mdt $flavor`
3687         res=$((res1 + res2))
3688     elif [ $dir == "all2all" ]; then
3689         res1=`flvr_cnt_mdt2ost $flavor`
3690         res2=`flvr_cnt_cli2ost $flavor`
3691         res3=`flvr_cnt_mdt2mdt $flavor`
3692         res4=`flvr_cnt_cli2mdt $flavor`
3693         res=$((res1 + res2 + res3 + res4))
3694     fi
3695
3696     echo $res
3697 }
3698
3699 wait_flavor()
3700 {
3701     local dir=$1        # from to
3702     local flavor=$2     # flavor expected
3703     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
3704
3705     local res=0
3706
3707     for ((i=0;i<20;i++)); do
3708         echo -n "checking..."
3709         res=$(do_check_flavor $dir $flavor)
3710         if [ $res -eq $expect ]; then
3711             echo "found $res $flavor connections of $dir, OK"
3712             return 0
3713         else
3714             echo "found $res $flavor connections of $dir, not ready ($expect)"
3715             sleep 4
3716         fi
3717     done
3718
3719     echo "Error checking $flavor of $dir: expect $expect, actual $res"
3720     return 1
3721 }
3722
3723 restore_to_default_flavor()
3724 {
3725     local proc="mgs.MGS.live.$FSNAME"
3726
3727     echo "restoring to default flavor..."
3728
3729     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
3730
3731     # remove all existing rules if any
3732     if [ $nrule -ne 0 ]; then
3733         echo "$nrule existing rules"
3734         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
3735             echo "remove rule: $rule"
3736             spec=`echo $rule | awk -F = '{print $1}'`
3737             do_facet mgs "$LCTL conf_param $spec="
3738         done
3739     fi
3740
3741     # verify no rules left
3742     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
3743     [ $nrule -ne 0 ] && error "still $nrule rules left"
3744
3745     # wait for default flavor to be applied
3746     # currently default flavor for all connections are 'null'
3747     wait_flavor all2all null
3748     echo "now at default flavor settings"
3749 }
3750
3751 set_flavor_all()
3752 {
3753     local flavor=${1:-null}
3754
3755     echo "setting all flavor to $flavor"
3756
3757     # FIXME need parameter to this fn
3758     # and remove global vars
3759     local cnt_all2all=$(calc_connection_cnt all2all)
3760
3761     local res=$(do_check_flavor all2all $flavor)
3762     if [ $res -eq $cnt_all2all ]; then
3763         echo "already have total $res $flavor connections"
3764         return
3765     fi
3766
3767     echo "found $res $flavor out of total $cnt_all2all connections"
3768     restore_to_default_flavor
3769
3770     [[ $flavor = null ]] && return 0
3771
3772     set_rule $FSNAME any any $flavor
3773     wait_flavor all2all $flavor
3774 }
3775
3776
3777 check_logdir() {
3778     local dir=$1
3779     # Checking for shared logdir
3780     if [ ! -d $dir ]; then
3781         # Not found. Create local logdir
3782         mkdir -p $dir
3783     else
3784         touch $dir/node.$(hostname).yml
3785     fi
3786     return 0
3787 }
3788
3789 check_write_access() {
3790     local dir=$1
3791     for node in $(nodes_list); do
3792         if [ ! -f "$dir/node.${node}.yml" ]; then
3793             # Logdir not accessible/writable from this node.
3794             return 1
3795         fi
3796     done
3797     return 0
3798 }
3799
3800 init_logging() {
3801     if [[ -n $YAML_LOG ]]; then
3802         return
3803     fi
3804     export YAML_LOG=${LOGDIR}/results.yml
3805     mkdir -p $LOGDIR
3806     init_clients_lists
3807
3808     do_rpc_nodes $(comma_list $(nodes_list)) check_logdir $LOGDIR
3809     if check_write_access $LOGDIR; then
3810         touch $LOGDIR/shared
3811         echo "Logging to shared log directory: $LOGDIR"
3812     else
3813         echo "Logging to local directory: $LOGDIR"
3814     fi
3815
3816     yml_nodes_file $LOGDIR
3817     yml_results_file >> $YAML_LOG
3818 }
3819
3820 log_test() {
3821     yml_log_test $1 >> $YAML_LOG
3822 }
3823
3824 log_sub_test() {
3825     yml_log_sub_test $@ >> $YAML_LOG
3826 }
3827