Whamcloud - gitweb
b=22225 Pad all test descriptions with "=" characters.
[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 #
2541 # Main entry into test-framework. This is called with the name and
2542 # description of a test. The name is used to find the function to run
2543 # the test using "test_$name".
2544 #
2545 # This supports a variety of methods of specifying specific test to
2546 # run or not run.  These need to be documented...
2547 #
2548 run_test() {
2549     assert_DIR
2550
2551     export base=`basetest $1`
2552     if [ ! -z "$ONLY" ]; then
2553         testname=ONLY_$1
2554         if [ ${!testname}x != x ]; then
2555             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2556             run_one_logged $1 "$2"
2557             return $?
2558         fi
2559         testname=ONLY_$base
2560         if [ ${!testname}x != x ]; then
2561             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2562             run_one_logged $1 "$2"
2563             return $?
2564         fi
2565         LAST_SKIPPED="y"
2566         echo -n "."
2567         return 0
2568     fi
2569     testname=EXCEPT_$1
2570     if [ ${!testname}x != x ]; then
2571         LAST_SKIPPED="y"
2572         TESTNAME=test_$1 skip "skipping excluded test $1"
2573         return 0
2574     fi
2575     testname=EXCEPT_$base
2576     if [ ${!testname}x != x ]; then
2577         LAST_SKIPPED="y"
2578         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
2579         return 0
2580     fi
2581     testname=EXCEPT_SLOW_$1
2582     if [ ${!testname}x != x ]; then
2583         LAST_SKIPPED="y"
2584         TESTNAME=test_$1 skip "skipping SLOW test $1"
2585         return 0
2586     fi
2587     testname=EXCEPT_SLOW_$base
2588     if [ ${!testname}x != x ]; then
2589         LAST_SKIPPED="y"
2590         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
2591         return 0
2592     fi
2593
2594     LAST_SKIPPED=
2595     run_one_logged $1 "$2"
2596
2597     return $?
2598 }
2599
2600 EQUALS="======================================================================"
2601 equals_msg() {
2602     msg="$@"
2603
2604     local suffixlen=$((${#EQUALS} - ${#msg}))
2605     [ $suffixlen -lt 5 ] && suffixlen=5
2606     log `echo $(printf '===== %s %.*s\n' "$msg" $suffixlen $EQUALS)`
2607 }
2608
2609 log() {
2610     echo "$*"
2611     module_loaded lnet || load_modules
2612
2613     local MSG="$*"
2614     # Get rid of '
2615     MSG=${MSG//\'/\\\'}
2616     MSG=${MSG//\(/\\\(}
2617     MSG=${MSG//\)/\\\)}
2618     MSG=${MSG//\;/\\\;}
2619     MSG=${MSG//\|/\\\|}
2620     MSG=${MSG//\>/\\\>}
2621     MSG=${MSG//\</\\\<}
2622     MSG=${MSG//\//\\\/}
2623     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
2624 }
2625
2626 trace() {
2627         log "STARTING: $*"
2628         strace -o $TMP/$1.strace -ttt $*
2629         RC=$?
2630         log "FINISHED: $*: rc $RC"
2631         return 1
2632 }
2633
2634 pass() {
2635     # Set TEST_STATUS here; will be used for logging the result
2636     if [ -f $LOGDIR/err ]; then
2637         TEST_STATUS="FAIL"
2638     else
2639         TEST_STATUS="PASS"
2640     fi
2641     echo $TEST_STATUS " " $@
2642 }
2643
2644 check_mds() {
2645     FFREE=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filesfree | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2646     FTOTAL=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filestotal | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2647     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
2648 }
2649
2650 reset_fail_loc () {
2651     echo -n "Resetting fail_loc on all nodes..."
2652     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
2653     echo done.
2654 }
2655
2656
2657 #
2658 # Log a message (on all nodes) padded with "=" before and after. 
2659 # Also appends a timestamp and prepends the testsuite name.
2660
2661 banner() {
2662     msg="== ${TESTSUITE} $*"
2663     # pad the message out to 70 with "="
2664     last=${msg: -1:1}
2665     [[ $last != "=" && $last != " " ]] && msg+=" "
2666     for i in $(seq $((68 - ${#msg})) ); do
2667         msg+="="
2668     done
2669     # always include at least == after the message
2670     msg+="=="
2671
2672     log "$msg $(date +"%H:%M:%S (%s)")"
2673 }
2674
2675 #
2676 # Run a single test function and cleanup after it.  
2677 #
2678 # This function should be run in a subshell so the test func can
2679 # exit() without stopping the whole script.
2680 #
2681 run_one() {
2682     local testnum=$1
2683     local message=$2
2684     tfile=f${testnum}
2685     export tdir=d0.${TESTSUITE}/d${base}
2686     export TESTNAME=test_$testnum
2687     local SAVE_UMASK=`umask`
2688     umask 0022
2689
2690     banner "test $testnum: $message"
2691     test_${testnum} || error "test_$testnum failed with $?"
2692     cd $SAVE_PWD
2693     reset_fail_loc
2694     check_grant ${testnum} || error "check_grant $testnum failed with $?"
2695     check_catastrophe || error "LBUG/LASSERT detected"
2696     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
2697     unset TESTNAME
2698     unset tdir
2699     umask $SAVE_UMASK
2700     return 0
2701 }
2702
2703 #
2704 # Wrapper around run_one to ensure:
2705 #  - test runs in subshell
2706 #  - output of test is saved to separate log file for error reporting
2707 #  - test result is saved to data file
2708 #
2709 run_one_logged() {
2710     local BEFORE=`date +%s`
2711     local TEST_ERROR
2712     local name=${TESTSUITE}.test_${1}.test_log.$(hostname).log
2713     local test_log=$LOGDIR/$name
2714     rm -rf $LOGDIR/err
2715
2716     echo
2717     run_one $1 "$2" 2>&1 | tee $test_log
2718     local RC=${PIPESTATUS[0]}
2719
2720     [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] && \
2721         echo "test_$1 returned $RC" | tee $LOGDIR/err
2722
2723     duration=$((`date +%s` - $BEFORE))
2724     pass "(${duration}s)"
2725     [ -f $LOGDIR/err ] && TEST_ERROR=$(cat $LOGDIR/err)
2726     log_sub_test test_${1} $TEST_STATUS $duration "$RC" "$TEST_ERROR"
2727
2728     if [ -f $LOGDIR/err ]; then
2729         $FAIL_ON_ERROR && exit $RC
2730     fi
2731
2732     return 0
2733 }
2734
2735 canonical_path() {
2736     (cd `dirname $1`; echo $PWD/`basename $1`)
2737 }
2738
2739 sync_clients() {
2740     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
2741     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
2742         cd $SAVE_PWD
2743 }
2744
2745 check_grant() {
2746     export base=`basetest $1`
2747     [ "$CHECK_GRANT" == "no" ] && return 0
2748
2749         testname=GCHECK_ONLY_${base}
2750         [ ${!testname}x == x ] && return 0
2751
2752     echo -n "checking grant......"
2753         cd $SAVE_PWD
2754         # write some data to sync client lost_grant
2755         rm -f $DIR1/${tfile}_check_grant_* 2>&1
2756         for i in `seq $OSTCOUNT`; do
2757                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
2758                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
2759                                               count=1 > /dev/null 2>&1
2760         done
2761         # sync all the data and make sure no pending data on server
2762         sync_clients
2763         
2764         #get client grant and server grant
2765         client_grant=0
2766     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
2767                 client_grant=$((client_grant + $d))
2768         done
2769         server_grant=0
2770         for d in `lctl get_param -n obdfilter.*.tot_granted`; do
2771                 server_grant=$((server_grant + $d))
2772         done
2773
2774         # cleanup the check_grant file
2775         for i in `seq $OSTCOUNT`; do
2776                 rm $DIR1/${tfile}_check_grant_$i
2777         done
2778
2779         #check whether client grant == server grant
2780         if [ $client_grant != $server_grant ]; then
2781                 echo "failed: client:${client_grant} server: ${server_grant}"
2782                 return 1
2783         else
2784                 echo "pass"
2785         fi
2786 }
2787
2788 ########################
2789 # helper functions
2790
2791 osc_to_ost()
2792 {
2793     osc=$1
2794     ost=`echo $1 | awk -F_ '{print $3}'`
2795     if [ -z $ost ]; then
2796         ost=`echo $1 | sed 's/-osc.*//'`
2797     fi
2798     echo $ost
2799 }
2800
2801 remote_node () {
2802     local node=$1
2803     [ "$node" != "$(hostname)" ]
2804 }
2805
2806 remote_mds ()
2807 {
2808     local node
2809     for node in $(mdts_nodes); do
2810         remote_node $node && return 0
2811     done
2812     return 1
2813 }
2814
2815 remote_mds_nodsh()
2816 {
2817     [ "$CLIENTONLY" ] && return 0 || true
2818     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
2819 }
2820
2821 require_dsh_mds()
2822 {
2823         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
2824             MSKIPPED=1 && return 1
2825         return 0
2826 }
2827
2828 remote_ost ()
2829 {
2830     local node
2831     for node in $(osts_nodes) ; do
2832         remote_node $node && return 0
2833     done
2834     return 1
2835 }
2836
2837 remote_ost_nodsh()
2838 {
2839     [ "$CLIENTONLY" ] && return 0 || true 
2840     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2841 }
2842
2843 require_dsh_ost()
2844 {
2845         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
2846             OSKIPPED=1 && return 1
2847         return 0
2848 }
2849
2850 remote_mgs_nodsh()
2851 {
2852     local MGS 
2853     MGS=$(facet_host mgs)
2854     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2855 }
2856
2857 local_mode ()
2858 {
2859     remote_mds_nodsh || remote_ost_nodsh || \
2860         $(single_local_node $(comma_list $(nodes_list)))
2861 }
2862
2863 mdts_nodes () {
2864     local MDSNODES
2865     local NODES_sort
2866     for num in `seq $MDSCOUNT`; do
2867         MDSNODES="$MDSNODES $(facet_host mds$num)"
2868     done
2869     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
2870
2871     echo $NODES_sort
2872 }
2873
2874 remote_servers () {
2875     remote_ost && remote_mds
2876 }
2877
2878 osts_nodes () {
2879     local OSTNODES=$(facet_host ost1)
2880     local NODES_sort
2881
2882     for num in `seq $OSTCOUNT`; do
2883         local myOST=$(facet_host ost$num)
2884         OSTNODES="$OSTNODES $myOST"
2885     done
2886     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
2887
2888     echo $NODES_sort
2889 }
2890
2891 nodes_list () {
2892     # FIXME. We need a list of clients
2893     local myNODES=$HOSTNAME
2894     local myNODES_sort
2895
2896     # CLIENTS (if specified) contains the local client
2897     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
2898
2899     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
2900         myNODES="$myNODES $(osts_nodes) $(mdts_nodes)"
2901     fi
2902
2903     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
2904
2905     echo $myNODES_sort
2906 }
2907
2908 remote_nodes_list () {
2909     local rnodes=$(nodes_list)
2910     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2911     echo $rnodes
2912 }
2913
2914 init_clients_lists () {
2915     # Sanity check: exclude the local client from RCLIENTS
2916     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2917
2918     # Sanity check: exclude the dup entries
2919     rclients=$(for i in $rclients; do echo $i; done | sort -u)
2920
2921     local clients="$SINGLECLIENT $HOSTNAME $rclients"
2922
2923     # Sanity check: exclude the dup entries from CLIENTS
2924     # for those configs which has SINGLCLIENT set to local client
2925     clients=$(for i in $clients; do echo $i; done | sort -u)
2926
2927     CLIENTS=`comma_list $clients`
2928     local -a remoteclients=($rclients)
2929     for ((i=0; $i<${#remoteclients[@]}; i++)); do
2930             varname=CLIENT$((i + 2))
2931             eval $varname=${remoteclients[i]}
2932     done
2933
2934     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
2935 }
2936
2937 get_random_entry () {
2938     local rnodes=$1
2939
2940     rnodes=${rnodes//,/ }
2941
2942     local -a nodes=($rnodes)
2943     local num=${#nodes[@]} 
2944     local i=$((RANDOM * num * 2 / 65536))
2945
2946     echo ${nodes[i]}
2947 }
2948
2949 client_only () {
2950     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
2951 }
2952
2953 is_patchless ()
2954 {
2955     lctl get_param version | grep -q patchless
2956 }
2957
2958 check_versions () {
2959     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
2960 }
2961
2962 get_node_count() {
2963     local nodes="$@"
2964     echo $nodes | wc -w || true
2965 }
2966
2967 mixed_ost_devs () {
2968     local nodes=$(osts_nodes)
2969     local osscount=$(get_node_count "$nodes")
2970     [ ! "$OSTCOUNT" = "$osscount" ]
2971 }
2972
2973 mixed_mdt_devs () {
2974     local nodes=$(mdts_nodes)
2975     local mdtcount=$(get_node_count "$nodes")
2976     [ ! "$MDSCOUNT" = "$mdtcount" ]
2977 }
2978
2979 generate_machine_file() {
2980     local nodes=${1//,/ }
2981     local machinefile=$2
2982     rm -f $machinefile || error "can't rm $machinefile"
2983     for node in $nodes; do
2984         echo $node >>$machinefile
2985     done
2986 }
2987
2988 get_stripe () {
2989     local file=$1/stripe
2990     touch $file
2991     $LFS getstripe -v $file || error
2992     rm -f $file
2993 }
2994
2995 setstripe_nfsserver () {
2996     local dir=$1
2997
2998     local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
2999                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -1)
3000
3001     [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
3002
3003     do_node --verbose $nfsserver lfs setstripe "$@"
3004 }
3005
3006 check_runas_id_ret() {
3007     local myRC=0
3008     local myRUNAS_UID=$1
3009     local myRUNAS_GID=$2
3010     shift 2
3011     local myRUNAS=$@
3012     if [ -z "$myRUNAS" ]; then
3013         error_exit "myRUNAS command must be specified for check_runas_id"
3014     fi
3015     if $GSS_KRB5; then
3016         $myRUNAS krb5_login.sh || \
3017             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
3018     fi
3019     mkdir $DIR/d0_runas_test
3020     chmod 0755 $DIR
3021     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
3022     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
3023     rm -rf $DIR/d0_runas_test
3024     return $myRC
3025 }
3026
3027 check_runas_id() {
3028     local myRUNAS_UID=$1
3029     local myRUNAS_GID=$2
3030     shift 2
3031     local myRUNAS=$@
3032     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
3033         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
3034         Please set RUNAS_ID to some UID which exists on MDS and client or
3035         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
3036 }
3037
3038 # obtain the UID/GID for MPI_USER
3039 get_mpiuser_id() {
3040     local mpi_user=$1
3041
3042     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
3043 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
3044
3045     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
3046 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
3047 }
3048
3049 # obtain and cache Kerberos ticket-granting ticket
3050 refresh_krb5_tgt() {
3051     local myRUNAS_UID=$1
3052     local myRUNAS_GID=$2
3053     shift 2
3054     local myRUNAS=$@
3055     if [ -z "$myRUNAS" ]; then
3056         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
3057     fi
3058
3059     CLIENTS=${CLIENTS:-$HOSTNAME}
3060     do_nodes $CLIENTS "set -x
3061 if ! $myRUNAS krb5_login.sh; then
3062     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
3063     exit 1
3064 fi"
3065 }
3066
3067 # Run multiop in the background, but wait for it to print
3068 # "PAUSING" to its stdout before returning from this function.
3069 multiop_bg_pause() {
3070     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
3071     FILE=$1
3072     ARGS=$2
3073
3074     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
3075     mkfifo $TMPPIPE
3076
3077     echo "$MULTIOP_PROG $FILE v$ARGS"
3078     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
3079
3080     echo "TMPPIPE=${TMPPIPE}"
3081     read -t 60 multiop_output < $TMPPIPE
3082     if [ $? -ne 0 ]; then
3083         rm -f $TMPPIPE
3084         return 1
3085     fi
3086     rm -f $TMPPIPE
3087     if [ "$multiop_output" != "PAUSING" ]; then
3088         echo "Incorrect multiop output: $multiop_output"
3089         kill -9 $PID
3090         return 1
3091     fi
3092
3093     return 0
3094 }
3095
3096 do_and_time () {
3097     local cmd=$1
3098     local rc
3099
3100     SECONDS=0
3101     eval '$cmd'
3102     
3103     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
3104
3105     echo $SECONDS
3106     return $rc
3107 }
3108
3109 inodes_available () {
3110     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
3111     echo $IFree
3112 }
3113
3114 mdsrate_inodes_available () {
3115     echo $(($(inodes_available) - 1))
3116 }
3117
3118 # reset llite stat counters
3119 clear_llite_stats(){
3120         lctl set_param -n llite.*.stats 0
3121 }
3122
3123 # sum llite stat items
3124 calc_llite_stats() {
3125         local res=$(lctl get_param -n llite.*.stats |
3126                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
3127         echo $res
3128 }
3129
3130 # reset osc stat counters
3131 clear_osc_stats(){
3132         lctl set_param -n osc.*.osc_stats 0
3133 }
3134
3135 # sum osc stat items
3136 calc_osc_stats() {
3137         local res=$(lctl get_param -n osc.*.osc_stats |
3138                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
3139         echo $res
3140 }
3141
3142 calc_sum () {
3143         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
3144 }
3145
3146 calc_osc_kbytes () {
3147         df $MOUNT > /dev/null
3148         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
3149 }
3150
3151 # save_lustre_params(node, parameter_mask)
3152 # generate a stream of formatted strings (<node> <param name>=<param value>)
3153 save_lustre_params() {
3154         local s
3155         do_nodes --verbose $1 "lctl get_param $2 | while read s; do echo \\\$s; done"
3156 }
3157
3158 # restore lustre parameters from input stream, produces by save_lustre_params
3159 restore_lustre_params() {
3160         local node
3161         local name
3162         local val
3163         while IFS=" =" read node name val; do
3164                 do_node ${node//:/} "lctl set_param -n $name $val"
3165         done
3166 }
3167
3168 check_catastrophe() {
3169     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
3170     local C=$CATASTROPHE
3171     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
3172
3173     if [ $rnodes ]; then
3174         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
3175 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
3176 exit \\\$rc;"
3177     fi 
3178 }
3179
3180 # $1 node
3181 # $2 file
3182 # $3 $RUNAS
3183 get_stripe_info() {
3184         local tmp_file
3185
3186         stripe_size=0
3187         stripe_count=0
3188         stripe_index=0
3189         tmp_file=$(mktemp)
3190
3191         do_facet $1 $3 lfs getstripe -v $2 > $tmp_file
3192
3193         stripe_size=`awk '$1 ~ /size/ {print $2}' $tmp_file`
3194         stripe_count=`awk '$1 ~ /count/ {print $2}' $tmp_file`
3195         stripe_index=`awk '$1 ~ /stripe_offset/ {print $2}' $tmp_file`
3196         rm -f $tmp_file
3197 }
3198
3199 # CMD: determine mds index where directory inode presents
3200 get_mds_dir () {
3201     local dir=$1
3202     local file=$dir/f0.get_mds_dir_tmpfile
3203
3204     mkdir -p $dir
3205     rm -f $file
3206     sleep 1
3207     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
3208     local -a oldused=($iused)
3209
3210     openfile -f O_CREAT:O_LOV_DELAY_CREATE -m 0644 $file > /dev/null
3211     sleep 1
3212     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
3213     local -a newused=($iused)
3214
3215     local num=0
3216     for ((i=0; i<${#newused[@]}; i++)); do
3217          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
3218              echo $(( i + 1 ))
3219              rm -f $file
3220              return 0
3221          fi
3222     done
3223     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
3224 }
3225
3226 mdsrate_cleanup () {
3227     if [ -d $4 ]; then
3228         mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
3229         rmdir $4
3230     fi
3231 }
3232
3233 delayed_recovery_enabled () {
3234     local var=${SINGLEMDS}_svc
3235     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
3236 }
3237
3238 ########################
3239
3240 convert_facet2label() { 
3241     local facet=$1
3242
3243     if [ x$facet = xost ]; then
3244        facet=ost1
3245     fi
3246
3247     local varsvc=${facet}_svc
3248
3249     if [ -n ${!varsvc} ]; then
3250         echo ${!varsvc}
3251     else  
3252         error "No lablel for $facet!"
3253     fi
3254 }
3255
3256 get_clientosc_proc_path() {
3257     local ost=$1
3258
3259     echo "{$1}-osc-*"
3260 }
3261
3262 get_lustre_version () {
3263     local node=${1:-"mds"}    
3264     do_facet $node $LCTL get_param -n version |  awk '/^lustre:/ {print $2}'
3265 }
3266
3267 get_mds_version_major () {
3268     local version=$(get_lustre_version mds)
3269     echo $version | awk -F. '{print $1}'
3270 }
3271
3272 get_mds_version_minor () {
3273     local version=$(get_lustre_version mds)
3274     echo $version | awk -F. '{print $2}'
3275 }
3276
3277 get_mdtosc_proc_path() {
3278     local ost=$1
3279     local major=$(get_mds_version_major)
3280     local minor=$(get_mds_version_minor)
3281     if [ $major -le 1 -a $minor -le 8 ] ; then
3282         echo "${ost}-osc"
3283     else
3284         echo "${ost}-osc-MDT0000"
3285     fi
3286 }
3287
3288 get_osc_import_name() {
3289     local facet=$1
3290     local ost=$2
3291     local label=$(convert_facet2label $ost)
3292
3293     if [ "$facet" == "mds" ]; then
3294         get_mdtosc_proc_path $label
3295         return 0
3296     fi
3297
3298     get_clientosc_proc_path $label
3299     return 0
3300 }
3301
3302 wait_import_state () {
3303     local expected=$1
3304     local CONN_PROC=$2
3305     local CONN_STATE
3306     local i=0
3307
3308     CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3309     while [ "${CONN_STATE}" != "${expected}" ]; do
3310         if [ "${expected}" == "DISCONN" ]; then
3311             # for disconn we can check after proc entry is removed
3312             [ "x${CONN_STATE}" == "x" ] && return 0
3313             #  with AT we can have connect request timeout ~ reconnect timeout
3314             # and test can't see real disconnect
3315             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
3316         fi
3317         # disconnect rpc should be wait not more obd_timeout
3318         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
3319             error "can't put import for $CONN_PROC into ${expected} state" && return 1
3320         sleep 1
3321         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3322         i=$(($i + 1))
3323     done
3324
3325     log "$CONN_PROC now in ${CONN_STATE} state"
3326     return 0
3327 }
3328
3329 wait_osc_import_state() {
3330     local facet=$1
3331     local ost_facet=$2
3332     local expected=$3
3333     local ost=$(get_osc_import_name $facet $ost_facet)
3334     local CONN_PROC
3335     local CONN_STATE
3336     local i=0
3337
3338     CONN_PROC="osc.${ost}.ost_server_uuid"
3339     CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3340     while [ "${CONN_STATE}" != "${expected}" ]; do
3341         if [ "${expected}" == "DISCONN" ]; then 
3342             # for disconn we can check after proc entry is removed
3343             [ "x${CONN_STATE}" == "x" ] && return 0
3344             #  with AT we can have connect request timeout ~ reconnect timeout
3345             # and test can't see real disconnect
3346             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
3347         fi
3348         # disconnect rpc should be wait not more obd_timeout
3349         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
3350             error "can't put import for ${ost}(${ost_facet}) into ${expected} state" && return 1
3351         sleep 1
3352         CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3353         i=$(($i + 1))
3354     done
3355
3356     log "${ost_facet} now in ${CONN_STATE} state"
3357     return 0
3358 }
3359 get_clientmdc_proc_path() {
3360     echo "${1}-mdc-*"
3361 }
3362
3363 do_rpc_nodes () {
3364     local list=$1
3365     shift
3366
3367     # Add paths to lustre tests for 32 and 64 bit systems.
3368     local RPATH="$RLUSTRE/tests:/usr/lib/lustre/tests:/usr/lib64/lustre/tests:$PATH"
3369     do_nodes --verbose $list "PATH=$RPATH sh rpc.sh $@ "
3370 }
3371
3372 wait_clients_import_state () {
3373     local list=$1
3374     local facet=$2
3375     local expected=$3
3376     shift
3377
3378     local label=$(convert_facet2label $facet)
3379     local proc_path
3380     case $facet in
3381         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
3382         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
3383         *) error "unknown facet!" ;;
3384     esac
3385
3386     if ! do_rpc_nodes $list wait_import_state $expected $proc_path; then
3387         error "import is not in ${expected} state"
3388         return 1
3389     fi
3390 }
3391
3392 oos_full() {
3393         local -a AVAILA
3394         local -a GRANTA
3395         local OSCFULL=1
3396         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
3397                   $LCTL get_param obdfilter.*.kbytesavail))
3398         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
3399                   $LCTL get_param -n obdfilter.*.tot_granted))
3400         for ((i=0; i<${#AVAILA[@]}; i++)); do
3401                 local -a AVAIL1=(${AVAILA[$i]//=/ })
3402                 GRANT=$((${GRANTA[$i]}/1024))
3403                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} grnt=$GRANT diff=$((AVAIL1[1] - GRANT))
3404                 [ $((AVAIL1[1] - GRANT)) -lt 400 ] && OSCFULL=0 && echo " FULL" || echo
3405         done
3406         return $OSCFULL
3407 }
3408
3409 pool_list () {
3410    do_facet mgs lctl pool_list $1
3411 }
3412
3413 create_pool() {
3414     local fsname=${1%%.*}
3415     local poolname=${1##$fsname.}
3416
3417     do_facet mgs lctl pool_new $1
3418     local RC=$?
3419     # get param should return err unless pool is created
3420     [[ $RC -ne 0 ]] && return $RC
3421
3422     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
3423         2>/dev/null || echo foo" "" || RC=1
3424     if [[ $RC -eq 0 ]]; then
3425         add_pool_to_list $1
3426     else
3427         error "pool_new failed $1"
3428     fi
3429     return $RC
3430 }
3431
3432 add_pool_to_list () {
3433     local fsname=${1%%.*}
3434     local poolname=${1##$fsname.}
3435
3436     local listvar=${fsname}_CREATED_POOLS
3437     eval export ${listvar}=$(expand_list ${!listvar} $poolname)
3438 }
3439
3440 remove_pool_from_list () {
3441     local fsname=${1%%.*}
3442     local poolname=${1##$fsname.}
3443
3444     local listvar=${fsname}_CREATED_POOLS
3445     eval export ${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
3446 }
3447
3448 destroy_pool_int() {
3449     local ost
3450     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
3451         awk '$1 !~ /^Pool:/ {print $1}')
3452     for ost in $OSTS; do
3453         do_facet mgs lctl pool_remove $1 $ost
3454     done
3455     do_facet mgs lctl pool_destroy $1
3456 }
3457
3458 # <fsname>.<poolname> or <poolname>
3459 destroy_pool() {
3460     local fsname=${1%%.*}
3461     local poolname=${1##$fsname.}
3462
3463     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
3464
3465     local RC
3466
3467     pool_list $fsname.$poolname || return $?
3468
3469     destroy_pool_int $fsname.$poolname
3470     RC=$?
3471     [[ $RC -ne 0 ]] && return $RC
3472
3473     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
3474       2>/dev/null || echo foo" "foo" || RC=1
3475
3476     if [[ $RC -eq 0 ]]; then
3477         remove_pool_from_list $fsname.$poolname
3478     else
3479         error "destroy pool failed $1"
3480     fi
3481     return $RC
3482 }
3483
3484 destroy_pools () {
3485     local fsname=${1:-$FSNAME}
3486     local poolname
3487     local listvar=${fsname}_CREATED_POOLS
3488
3489     pool_list $fsname
3490
3491     [ x${!listvar} = x ] && return 0
3492
3493     echo destroy the created pools: ${!listvar}
3494     for poolname in ${!listvar//,/ }; do
3495         destroy_pool $fsname.$poolname 
3496     done
3497 }
3498
3499 cleanup_pools () {
3500     local fsname=${1:-$FSNAME}
3501     trap 0
3502     destroy_pools $fsname
3503 }
3504
3505 gather_logs () {
3506     local list=$1
3507
3508     local ts=$(date +%s)
3509
3510     # bug 20237, comment 11
3511     # It would also be useful to provide the option
3512     # of writing the file to an NFS directory so it doesn't need to be copied.
3513     local tmp=$TMP
3514     local docp=true
3515     [ -f $LOGDIR/shared ] && docp=false
3516  
3517     # dump lustre logs, dmesg
3518
3519     prefix="$LOGDIR/${TESTSUITE}.${TESTNAME}"
3520     suffix="$ts.log"
3521     echo "Dumping lctl log to ${prefix}.*.${suffix}"
3522
3523     if [ "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
3524         echo "Dumping logs only on local client."
3525         $LCTL dk > ${prefix}.debug_log.$(hostname).${suffix}
3526         dmesg > ${prefix}.dmesg.$(hostname).${suffix}
3527         return
3528     fi
3529
3530     do_nodes --verbose $list \
3531         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname).${suffix};
3532          dmesg > ${prefix}.dmesg.\\\$(hostname).${suffix}"
3533     if [ ! -f $LOGDIR/shared ]; then
3534         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
3535       fi
3536
3537     local archive=$LOGDIR/${TESTSUITE}-$ts.tar.bz2
3538     tar -jcf $archive $LOGDIR/*$ts* $LOGDIR/*${TESTSUITE}*
3539
3540     echo $archive
3541 }
3542
3543 cleanup_logs () {
3544     local list=${1:-$(comma_list $(nodes_list))}
3545
3546     [ -n ${TESTSUITE} ] && do_nodes $list "rm -f $TMP/*${TESTSUITE}*" || true
3547 }
3548
3549 do_ls () {
3550     local mntpt_root=$1
3551     local num_mntpts=$2
3552     local dir=$3
3553     local i
3554     local cmd
3555     local pids
3556     local rc=0
3557
3558     for i in $(seq 0 $num_mntpts); do
3559         cmd="ls -laf ${mntpt_root}$i/$dir"
3560         echo + $cmd;
3561         $cmd > /dev/null &
3562         pids="$pids $!"
3563     done
3564     echo pids=$pids
3565     for pid in $pids; do
3566         wait $pid || rc=$?
3567     done
3568
3569     return $rc
3570 }
3571
3572 get_clients_mount_count () {
3573     local clients=${CLIENTS:-`hostname`}
3574
3575     # we need to take into account the clients mounts and
3576     # exclude mds/ost mounts if any;
3577     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
3578 }
3579
3580 # gss functions
3581 PROC_CLI="srpc_info"
3582
3583 combination()
3584 {
3585     local M=$1
3586     local N=$2
3587     local R=1
3588
3589     if [ $M -lt $N ]; then
3590         R=0
3591     else
3592         N=$((N + 1))
3593         while [ $N -le $M ]; do
3594             R=$((R * N))
3595             N=$((N + 1))
3596         done
3597     fi
3598
3599     echo $R
3600     return 0
3601 }
3602
3603 calc_connection_cnt() {
3604     local dir=$1
3605
3606     # MDT->MDT = 2 * C(M, 2)
3607     # MDT->OST = M * O
3608     # CLI->OST = C * O
3609     # CLI->MDT = C * M
3610     comb_m2=$(combination $MDSCOUNT 2)
3611
3612     local num_clients=$(get_clients_mount_count)
3613
3614     local cnt_mdt2mdt=$((comb_m2 * 2))
3615     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
3616     local cnt_cli2ost=$((num_clients * OSTCOUNT))
3617     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
3618     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
3619     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
3620     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
3621
3622     local var=cnt_$dir
3623     local res=${!var}
3624
3625     echo $res
3626 }
3627
3628 set_rule()
3629 {
3630     local tgt=$1
3631     local net=$2
3632     local dir=$3
3633     local flavor=$4
3634     local cmd="$tgt.srpc.flavor"
3635
3636     if [ $net == "any" ]; then
3637         net="default"
3638     fi
3639     cmd="$cmd.$net"
3640
3641     if [ $dir != "any" ]; then
3642         cmd="$cmd.$dir"
3643     fi
3644
3645     cmd="$cmd=$flavor"
3646     log "Setting sptlrpc rule: $cmd"
3647     do_facet mgs "$LCTL conf_param $cmd"
3648 }
3649
3650 count_flvr()
3651 {
3652     local output=$1
3653     local flavor=$2
3654     local count=0
3655
3656     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
3657     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
3658
3659     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
3660
3661     if [ "x$bulkspec" != "x" ]; then
3662         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
3663
3664         if [ "x$algs" != "x" ]; then
3665             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
3666         else
3667             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
3668             if [ $bulk == "bulkn" ]; then
3669                 bulk_count=`echo "$output" | grep "bulk flavor" \
3670                             | grep "null/null" | wc -l`
3671             elif [ $bulk == "bulki" ]; then
3672                 bulk_count=`echo "$output" | grep "bulk flavor" \
3673                             | grep "/null" | grep -v "null/" | wc -l`
3674             else
3675                 bulk_count=`echo "$output" | grep "bulk flavor" \
3676                             | grep -v "/null" | grep -v "null/" | wc -l`
3677             fi
3678         fi
3679
3680         [ $bulk_count -lt $count ] && count=$bulk_count
3681     fi
3682
3683     echo $count
3684 }
3685
3686 flvr_cnt_cli2mdt()
3687 {
3688     local flavor=$1
3689     local cnt
3690
3691     local clients=${CLIENTS:-`hostname`}
3692
3693     for c in ${clients//,/ }; do
3694         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
3695         tmpcnt=`count_flvr "$output" $flavor`
3696         cnt=$((cnt + tmpcnt))
3697     done
3698     echo $cnt
3699 }
3700
3701 flvr_cnt_cli2ost()
3702 {
3703     local flavor=$1
3704     local cnt
3705
3706     local clients=${CLIENTS:-`hostname`}
3707
3708     for c in ${clients//,/ }; do
3709         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
3710         tmpcnt=`count_flvr "$output" $flavor`
3711         cnt=$((cnt + tmpcnt))
3712     done
3713     echo $cnt
3714 }
3715
3716 flvr_cnt_mdt2mdt()
3717 {
3718     local flavor=$1
3719     local cnt=0
3720
3721     if [ $MDSCOUNT -le 1 ]; then
3722         echo 0
3723         return
3724     fi
3725
3726     for num in `seq $MDSCOUNT`; do
3727         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
3728         tmpcnt=`count_flvr "$output" $flavor`
3729         cnt=$((cnt + tmpcnt))
3730     done
3731     echo $cnt;
3732 }
3733
3734 flvr_cnt_mdt2ost()
3735 {
3736     local flavor=$1
3737     local cnt=0
3738
3739     for num in `seq $MDSCOUNT`; do
3740         output=`do_facet mds$num lctl get_param -n osc.*OST*-osc-MDT*.$PROC_CLI 2>/dev/null`
3741         tmpcnt=`count_flvr "$output" $flavor`
3742         cnt=$((cnt + tmpcnt))
3743     done
3744     echo $cnt;
3745 }
3746
3747 flvr_cnt_mgc2mgs()
3748 {
3749     local flavor=$1
3750
3751     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
3752     count_flvr "$output" $flavor
3753 }
3754
3755 do_check_flavor()
3756 {
3757     local dir=$1        # from to
3758     local flavor=$2     # flavor expected
3759     local res=0
3760
3761     if [ $dir == "cli2mdt" ]; then
3762         res=`flvr_cnt_cli2mdt $flavor`
3763     elif [ $dir == "cli2ost" ]; then
3764         res=`flvr_cnt_cli2ost $flavor`
3765     elif [ $dir == "mdt2mdt" ]; then
3766         res=`flvr_cnt_mdt2mdt $flavor`
3767     elif [ $dir == "mdt2ost" ]; then
3768         res=`flvr_cnt_mdt2ost $flavor`
3769     elif [ $dir == "all2ost" ]; then
3770         res1=`flvr_cnt_mdt2ost $flavor`
3771         res2=`flvr_cnt_cli2ost $flavor`
3772         res=$((res1 + res2))
3773     elif [ $dir == "all2mdt" ]; then
3774         res1=`flvr_cnt_mdt2mdt $flavor`
3775         res2=`flvr_cnt_cli2mdt $flavor`
3776         res=$((res1 + res2))
3777     elif [ $dir == "all2all" ]; then
3778         res1=`flvr_cnt_mdt2ost $flavor`
3779         res2=`flvr_cnt_cli2ost $flavor`
3780         res3=`flvr_cnt_mdt2mdt $flavor`
3781         res4=`flvr_cnt_cli2mdt $flavor`
3782         res=$((res1 + res2 + res3 + res4))
3783     fi
3784
3785     echo $res
3786 }
3787
3788 wait_flavor()
3789 {
3790     local dir=$1        # from to
3791     local flavor=$2     # flavor expected
3792     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
3793
3794     local res=0
3795
3796     for ((i=0;i<20;i++)); do
3797         echo -n "checking..."
3798         res=$(do_check_flavor $dir $flavor)
3799         if [ $res -eq $expect ]; then
3800             echo "found $res $flavor connections of $dir, OK"
3801             return 0
3802         else
3803             echo "found $res $flavor connections of $dir, not ready ($expect)"
3804             sleep 4
3805         fi
3806     done
3807
3808     echo "Error checking $flavor of $dir: expect $expect, actual $res"
3809     return 1
3810 }
3811
3812 restore_to_default_flavor()
3813 {
3814     local proc="mgs.MGS.live.$FSNAME"
3815
3816     echo "restoring to default flavor..."
3817
3818     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
3819
3820     # remove all existing rules if any
3821     if [ $nrule -ne 0 ]; then
3822         echo "$nrule existing rules"
3823         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
3824             echo "remove rule: $rule"
3825             spec=`echo $rule | awk -F = '{print $1}'`
3826             do_facet mgs "$LCTL conf_param $spec="
3827         done
3828     fi
3829
3830     # verify no rules left
3831     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
3832     [ $nrule -ne 0 ] && error "still $nrule rules left"
3833
3834     # wait for default flavor to be applied
3835     # currently default flavor for all connections are 'null'
3836     wait_flavor all2all null
3837     echo "now at default flavor settings"
3838 }
3839
3840 set_flavor_all()
3841 {
3842     local flavor=${1:-null}
3843
3844     echo "setting all flavor to $flavor"
3845
3846     # FIXME need parameter to this fn
3847     # and remove global vars
3848     local cnt_all2all=$(calc_connection_cnt all2all)
3849
3850     local res=$(do_check_flavor all2all $flavor)
3851     if [ $res -eq $cnt_all2all ]; then
3852         echo "already have total $res $flavor connections"
3853         return
3854     fi
3855
3856     echo "found $res $flavor out of total $cnt_all2all connections"
3857     restore_to_default_flavor
3858
3859     [[ $flavor = null ]] && return 0
3860
3861     set_rule $FSNAME any any $flavor
3862     wait_flavor all2all $flavor
3863 }
3864
3865
3866 check_logdir() {
3867     local dir=$1
3868     # Checking for shared logdir
3869     if [ ! -d $dir ]; then
3870         # Not found. Create local logdir
3871         mkdir -p $dir
3872     else
3873         touch $dir/node.$(hostname).yml
3874     fi
3875     return 0
3876 }
3877
3878 check_write_access() {
3879     local dir=$1
3880     for node in $(nodes_list); do
3881         if [ ! -f "$dir/node.${node}.yml" ]; then
3882             # Logdir not accessible/writable from this node.
3883             return 1
3884         fi
3885     done
3886     return 0
3887 }
3888
3889 init_logging() {
3890     if [[ -n $YAML_LOG ]]; then
3891         return
3892     fi
3893     export YAML_LOG=${LOGDIR}/results.yml
3894     mkdir -p $LOGDIR
3895     init_clients_lists
3896
3897     do_rpc_nodes $(comma_list $(nodes_list)) check_logdir $LOGDIR
3898     if check_write_access $LOGDIR; then
3899         touch $LOGDIR/shared
3900         echo "Logging to shared log directory: $LOGDIR"
3901     else
3902         echo "Logging to local directory: $LOGDIR"
3903     fi
3904
3905     yml_nodes_file $LOGDIR
3906     yml_results_file >> $YAML_LOG
3907 }
3908
3909 log_test() {
3910     yml_log_test $1 >> $YAML_LOG
3911 }
3912
3913 log_sub_test() {
3914     yml_log_sub_test $@ >> $YAML_LOG
3915 }
3916