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