Whamcloud - gitweb
b=18649 set wait_recovery_complete() MAX value to max recovery time estimated
[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 [ $(basename $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_nodesv $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     # bug 22169: wait the background threads to start
954     sleep 2
955 }
956
957 # only for remote client 
958 check_client_load () {
959     local client=$1
960     local var=$(client_var_name $client)_load
961     local TESTLOAD=run_${!var}.sh
962
963     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
964     
965     # bug 18914: try to connect several times not only when
966     # check ps, but  while check_catastrophe also
967     local tries=3
968     local RC=254
969     while [ $RC = 254 -a $tries -gt 0 ]; do
970         let tries=$tries-1
971         # assume success
972         RC=0
973         if ! check_catastrophe $client; then
974             RC=${PIPESTATUS[0]}
975             if [ $RC -eq 254 ]; then
976                 # FIXME: not sure how long we shuold sleep here
977                 sleep 10
978                 continue
979             fi
980             echo "check catastrophe failed: RC=$RC "
981             return $RC
982         fi
983     done
984     # We can continue try to connect if RC=254
985     # Just print the warning about this
986     if [ $RC = 254 ]; then
987         echo "got a return status of $RC from do_node while checking catastrophe on $client"
988     fi
989
990     # see if the load is still on the client
991     tries=3
992     RC=254
993     while [ $RC = 254 -a $tries -gt 0 ]; do
994         let tries=$tries-1
995         # assume success
996         RC=0
997         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
998             RC=${PIPESTATUS[0]}
999             sleep 30
1000         fi
1001     done
1002     if [ $RC = 254 ]; then
1003         echo "got a return status of $RC from do_node while checking (catastrophe and 'ps') the client load on $client"
1004         # see if we can diagnose a bit why this is
1005     fi
1006
1007     return $RC
1008 }
1009 check_client_loads () {
1010    local clients=${1//,/ }
1011    local client=
1012    local rc=0
1013
1014    for client in $clients; do
1015       check_client_load $client
1016       rc=${PIPESTATUS[0]}
1017       if [ "$rc" != 0 ]; then
1018         log "Client load failed on node $client, rc=$rc"
1019         return $rc
1020       fi
1021    done
1022 }
1023
1024 restart_client_loads () {
1025     local clients=${1//,/ }
1026     local expectedfail=${2:-""}
1027     local client=
1028     local rc=0
1029
1030     for client in $clients; do
1031         check_client_load $client
1032         rc=${PIPESTATUS[0]}
1033         if [ "$rc" != 0 -a "$expectedfail" ]; then
1034             local var=$(client_var_name $client)_load
1035             start_client_load $client ${!var}
1036             echo "Restarted client load ${!var}: on $client. Checking ..."
1037             check_client_load $client
1038             rc=${PIPESTATUS[0]}
1039             if [ "$rc" != 0 ]; then
1040                 log "Client load failed to restart on node $client, rc=$rc"
1041                 # failure one client load means test fail
1042                 # we do not need to check other 
1043                 return $rc
1044             fi
1045         else
1046             return $rc
1047         fi
1048     done
1049 }
1050 # End recovery-scale functions
1051
1052 # verify that lustre actually cleaned up properly
1053 cleanup_check() {
1054     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
1055         error "LBUG/LASSERT detected"
1056     BUSY=`dmesg | grep -i destruct || true`
1057     if [ "$BUSY" ]; then
1058         echo "$BUSY" 1>&2
1059         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
1060         exit 205
1061     fi
1062
1063     check_mem_leak || exit 204
1064
1065     [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl && \
1066         echo "$0: lustre didn't clean up..." 1>&2 && return 202 || true
1067
1068     if module_loaded lnet || module_loaded libcfs; then
1069         echo "$0: modules still loaded..." 1>&2
1070         /sbin/lsmod 1>&2
1071         return 203
1072     fi
1073     return 0
1074 }
1075
1076 wait_update () {
1077     local node=$1
1078     local TEST=$2
1079     local FINAL=$3
1080     local MAX=${4:-90}
1081
1082         local RESULT
1083         local WAIT=0
1084         local sleep=5
1085         while [ true ]; do
1086             RESULT=$(do_node $node "$TEST")
1087             if [ "$RESULT" == "$FINAL" ]; then
1088                 echo "Updated after $WAIT sec: wanted '$FINAL' got '$RESULT'"
1089                 return 0
1090             fi
1091             [ $WAIT -ge $MAX ] && break
1092             echo "Waiting $((MAX - WAIT)) secs for update"
1093             WAIT=$((WAIT + sleep))
1094             sleep $sleep
1095         done
1096         echo "Update not seen after $MAX sec: wanted '$FINAL' got '$RESULT'"
1097         return 3
1098 }
1099
1100 wait_update_facet () {
1101     local facet=$1
1102     wait_update  $(facet_active_host $facet) "$@"
1103 }
1104
1105 wait_delete_completed () {
1106     local TOTALPREV=`lctl get_param -n osc.*.kbytesavail | \
1107                      awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1108
1109     local WAIT=0
1110     local MAX_WAIT=20
1111     while [ "$WAIT" -ne "$MAX_WAIT" ]; do
1112         sleep 1
1113         TOTAL=`lctl get_param -n osc.*.kbytesavail | \
1114                awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1115         [ "$TOTAL" -eq "$TOTALPREV" ] && return 0
1116         echo "Waiting delete completed ... prev: $TOTALPREV current: $TOTAL "
1117         TOTALPREV=$TOTAL
1118         WAIT=$(( WAIT + 1))
1119     done
1120     echo "Delete is not completed in $MAX_WAIT sec"
1121     return 1
1122 }
1123
1124 wait_for_host() {
1125     local host=$1
1126     check_network "$host" 900
1127     while ! do_node $host hostname  > /dev/null; do sleep 5; done
1128 }
1129
1130 wait_for() {
1131     local facet=$1
1132     local host=`facet_active_host $facet`
1133     wait_for_host $host
1134 }
1135
1136 wait_recovery_complete () {
1137     local facet=$1
1138
1139     # Use default policy if $2 is not passed by caller.
1140     local MAX=${2:-$(max_recovery_time)}
1141
1142     local var_svc=${facet}_svc
1143     local procfile="*.${!var_svc}.recovery_status"
1144     local WAIT=0
1145     local STATUS=
1146
1147     while [ $WAIT -lt $MAX ]; do
1148         STATUS=$(do_facet $facet lctl get_param -n $procfile | grep status)
1149         [[ $STATUS = "status: COMPLETE" ]] && return 0
1150         sleep 5
1151         WAIT=$((WAIT + 5))
1152         echo "Waiting $((MAX - WAIT)) secs for $facet recovery done. $STATUS"
1153     done
1154     echo "$facet recovery not done in $MAX sec. $STATUS"
1155     return 1
1156 }
1157
1158 wait_mds_ost_sync () {
1159     # just because recovery is done doesn't mean we've finished
1160     # orphan cleanup. Wait for llogs to get synchronized.
1161     echo "Waiting for orphan cleanup..."
1162     # MAX value includes time needed for MDS-OST reconnection
1163     local MAX=$(( TIMEOUT * 2 ))
1164     local WAIT=0
1165     while [ $WAIT -lt $MAX ]; do
1166         local -a sync=($(do_nodes $(comma_list $(osts_nodes)) \
1167             "$LCTL get_param -n obdfilter.*.mds_sync"))
1168         local con=1
1169         for ((i=0; i<${#sync[@]}; i++)); do
1170             [ ${sync[$i]} -eq 0 ] && continue
1171             # there is a not finished MDS-OST synchronization
1172             con=0
1173             break;
1174         done
1175         sleep 2 # increase waiting time and cover statfs cache
1176         [ ${con} -eq 1 ] && return 0
1177         echo "Waiting $WAIT secs for $facet mds-ost sync done."
1178         WAIT=$((WAIT + 2))
1179     done
1180     echo "$facet recovery not done in $MAX sec. $STATUS"
1181     return 1
1182 }
1183
1184 wait_destroy_complete () {
1185     echo "Waiting for destroy to be done..."
1186     # MAX value shouldn't be big as this mean server responsiveness
1187     # never increase this just to make test pass but investigate
1188     # why it takes so long time
1189     local MAX=5
1190     local WAIT=0
1191     while [ $WAIT -lt $MAX ]; do
1192         local -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))
1193         local con=1
1194         for ((i=0; i<${#RPCs[@]}; i++)); do
1195             [ ${RPCs[$i]} -eq 0 ] && continue
1196             # there are still some destroy RPCs in flight
1197             con=0
1198             break;
1199         done
1200         sleep 1
1201         [ ${con} -eq 1 ] && return 0 # done waiting
1202         echo "Waiting $WAIT secs for destroys to be done."
1203         WAIT=$((WAIT + 1))
1204     done
1205     echo "Destroys weren't done in $MAX sec."
1206     return 1
1207 }
1208
1209 wait_exit_ST () {
1210     local facet=$1
1211
1212     local WAIT=0
1213     local INTERVAL=1
1214     local running
1215     # conf-sanity 31 takes a long time cleanup
1216     while [ $WAIT -lt 300 ]; do
1217         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
1218         [ -z "${running}" ] && return 0
1219         echo "waited $WAIT for${running}"
1220         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
1221         sleep $INTERVAL
1222         WAIT=$((WAIT + INTERVAL))
1223     done
1224     echo "service didn't stop after $WAIT seconds.  Still running:"
1225     echo ${running}
1226     return 1
1227 }
1228
1229 wait_remote_prog () {
1230    local prog=$1
1231    local WAIT=0
1232    local INTERVAL=5
1233    local rc=0
1234
1235    [ "$PDSH" = "no_dsh" ] && return 0
1236
1237    while [ $WAIT -lt $2 ]; do
1238         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
1239         [ -z "${running}" ] && return 0 || true
1240         echo "waited $WAIT for: "
1241         echo "$running"
1242         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
1243         sleep $INTERVAL
1244         WAIT=$((WAIT + INTERVAL))
1245     done
1246     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
1247     [ -z "$pids" ] && return 0
1248     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
1249     # FIXME: not portable
1250     for pid in $pids; do
1251         cat /proc/${pid}/status || true
1252         cat /proc/${pid}/wchan || true
1253         echo "Killing $pid"
1254         kill -9 $pid || true
1255         sleep 1
1256         ps -P $pid && rc=1
1257     done
1258
1259     return $rc
1260 }
1261
1262 clients_up() {
1263     # not every config has many clients
1264     sleep 1
1265     if [ ! -z "$CLIENTS" ]; then
1266         $PDSH $CLIENTS "stat -f $MOUNT" > /dev/null
1267     else
1268         stat -f $MOUNT > /dev/null
1269     fi
1270 }
1271
1272 client_up() {
1273     local client=$1
1274     # usually checked on particular client or locally
1275     sleep 1
1276     if [ ! -z "$client" ]; then
1277         $PDSH $client "stat -f $MOUNT" > /dev/null
1278     else
1279         stat -f $MOUNT > /dev/null
1280     fi
1281 }
1282
1283 client_evicted() {
1284     ! client_up $1
1285 }
1286
1287 client_reconnect() {
1288     uname -n >> $MOUNT/recon
1289     if [ -z "$CLIENTS" ]; then
1290         df $MOUNT; uname -n >> $MOUNT/recon
1291     else
1292         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
1293     fi
1294     echo Connected clients:
1295     cat $MOUNT/recon
1296     ls -l $MOUNT/recon > /dev/null
1297     rm $MOUNT/recon
1298 }
1299
1300 facet_failover() {
1301     local facet=$1
1302     local sleep_time=$2
1303     echo "Failing $facet on node `facet_active_host $facet`"
1304     shutdown_facet $facet
1305     [ -n "$sleep_time" ] && sleep $sleep_time
1306     reboot_facet $facet
1307     change_active $facet
1308     local TO=`facet_active_host $facet`
1309     echo "Failover $facet to $TO"
1310     wait_for $facet
1311     mount_facet $facet || error "Restart of $facet failed"
1312 }
1313
1314 obd_name() {
1315     local facet=$1
1316 }
1317
1318 replay_barrier() {
1319     local facet=$1
1320     do_facet $facet sync
1321     df $MOUNT
1322     local svc=${facet}_svc
1323     do_facet $facet $LCTL --device %${!svc} notransno
1324     do_facet $facet $LCTL --device %${!svc} readonly
1325     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1326     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1327 }
1328
1329 replay_barrier_nodf() {
1330     local facet=$1    echo running=${running}
1331     do_facet $facet sync
1332     local svc=${facet}_svc
1333     echo Replay barrier on ${!svc}
1334     do_facet $facet $LCTL --device %${!svc} notransno
1335     do_facet $facet $LCTL --device %${!svc} readonly
1336     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1337     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1338 }
1339
1340 replay_barrier_nosync() {
1341     local facet=$1    echo running=${running}
1342     local svc=${facet}_svc
1343     echo Replay barrier on ${!svc}
1344     do_facet $facet $LCTL --device %${!svc} notransno
1345     do_facet $facet $LCTL --device %${!svc} readonly
1346     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1347     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1348 }
1349
1350 mds_evict_client() {
1351     UUID=`lctl get_param -n mdc.${mds1_svc}-mdc-*.uuid`
1352     do_facet mds1 "lctl set_param -n mdt.${mds1_svc}.evict_client $UUID"
1353 }
1354
1355 ost_evict_client() {
1356     UUID=`lctl get_param -n devices| grep ${ost1_svc}-osc- | egrep -v 'MDT' | awk '{print $5}'`
1357     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
1358 }
1359
1360 fail() {
1361     facet_failover $* || error "failover: $?"
1362     clients_up || error "post-failover df: $?"
1363 }
1364
1365 fail_nodf() {
1366         local facet=$1
1367         facet_failover $facet
1368 }
1369
1370 fail_abort() {
1371     local facet=$1
1372     stop $facet
1373     change_active $facet
1374     mount_facet $facet -o abort_recovery
1375     clients_up || echo "first df failed: $?"
1376     clients_up || error "post-failover df: $?"
1377 }
1378
1379 do_lmc() {
1380     echo There is no lmc.  This is mountconf, baby.
1381     exit 1
1382 }
1383
1384 h2gm () {
1385     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1386         ID=`$PDSH $1 $GMNALNID -l | cut -d\  -f2`
1387         echo $ID"@gm"
1388     fi
1389 }
1390
1391 h2name_or_ip() {
1392     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1393         echo $1"@$2"
1394     fi
1395 }
1396
1397 h2ptl() {
1398    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1399        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
1400        if [ -z "$ID" ]; then
1401            echo "Could not get a ptl id for $1..."
1402            exit 1
1403        fi
1404        echo $ID"@ptl"
1405    fi
1406 }
1407 declare -fx h2ptl
1408
1409 h2tcp() {
1410     h2name_or_ip "$1" "tcp"
1411 }
1412 declare -fx h2tcp
1413
1414 h2elan() {
1415     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1416         if type __h2elan >/dev/null 2>&1; then
1417             ID=$(__h2elan $1)
1418         else
1419             ID=`echo $1 | sed 's/[^0-9]*//g'`
1420         fi
1421         echo $ID"@elan"
1422     fi
1423 }
1424 declare -fx h2elan
1425
1426 h2openib() {
1427     h2name_or_ip "$1" "openib"
1428 }
1429 declare -fx h2openib
1430
1431 h2o2ib() {
1432     h2name_or_ip "$1" "o2ib"
1433 }
1434 declare -fx h2o2ib
1435
1436 facet_host() {
1437     local facet=$1
1438
1439     [ "$facet" == client ] && echo -n $HOSTNAME && return
1440     varname=${facet}_HOST
1441     if [ -z "${!varname}" ]; then
1442         if [ "${facet:0:3}" == "ost" ]; then
1443             eval ${facet}_HOST=${ost_HOST}
1444         fi
1445     fi
1446     echo -n ${!varname}
1447 }
1448
1449 facet_active() {
1450     local facet=$1
1451     local activevar=${facet}active
1452
1453     if [ -f $TMP/${facet}active ] ; then
1454         source $TMP/${facet}active
1455     fi
1456
1457     active=${!activevar}
1458     if [ -z "$active" ] ; then
1459         echo -n ${facet}
1460     else
1461         echo -n ${active}
1462     fi
1463 }
1464
1465 facet_active_host() {
1466     local facet=$1
1467     local active=`facet_active $facet`
1468     if [ "$facet" == client ]; then
1469         echo $HOSTNAME
1470     else
1471         echo `facet_host $active`
1472     fi
1473 }
1474
1475 change_active() {
1476     local facet=$1
1477     local failover=${facet}failover
1478     host=`facet_host $failover`
1479     [ -z "$host" ] && return
1480     local curactive=`facet_active $facet`
1481     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
1482         eval export ${facet}active=$facet
1483     else
1484         eval export ${facet}active=$failover
1485     fi
1486     # save the active host for this facet
1487     local activevar=${facet}active
1488     echo "$activevar=${!activevar}" > $TMP/$activevar
1489 }
1490
1491 do_node() {
1492     local verbose=false
1493     # do not stripe off hostname if verbose, bug 19215
1494     if [ x$1 = x--verbose ]; then
1495         shift
1496         verbose=true
1497     fi
1498
1499     local HOST=$1
1500     shift
1501     local myPDSH=$PDSH
1502     if [ "$HOST" = "$HOSTNAME" ]; then
1503         myPDSH="no_dsh"
1504     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
1505         echo "cannot run remote command on $HOST with $myPDSH"
1506         return 128
1507     fi
1508     if $VERBOSE; then
1509         echo "CMD: $HOST $@" >&2
1510         $myPDSH $HOST $LCTL mark "$@" > /dev/null 2>&1 || :
1511     fi
1512
1513     if [ "$myPDSH" = "rsh" ]; then
1514 # we need this because rsh does not return exit code of an executed command
1515         local command_status="$TMP/cs"
1516         rsh $HOST ":> $command_status"
1517         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
1518                     cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
1519                     echo command failed >$command_status"
1520         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
1521         return 0
1522     fi
1523
1524     if $verbose ; then
1525         # print HOSTNAME for myPDSH="no_dsh"
1526         if [[ $myPDSH = no_dsh ]]; then
1527             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
1528         else
1529             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
1530         fi
1531     else
1532         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
1533     fi
1534     return ${PIPESTATUS[0]}
1535 }
1536
1537 do_nodev() {
1538     do_node --verbose "$@"
1539 }
1540
1541 single_local_node () {
1542    [ "$1" = "$HOSTNAME" ]
1543 }
1544
1545 # Outputs environment variable assignments that should be passed to remote nodes
1546 get_env_vars() {
1547     local var
1548     local value
1549
1550     for var in ${!MODOPTS_*}; do
1551         value=${!var}
1552         echo "${var}=\"$value\""
1553     done
1554 }
1555
1556 do_nodes() {
1557     local verbose=false
1558     # do not stripe off hostname if verbose, bug 19215
1559     if [ x$1 = x--verbose ]; then
1560         shift
1561         verbose=true
1562     fi
1563
1564     local rnodes=$1
1565     shift
1566
1567     if single_local_node $rnodes; then
1568         if $verbose; then
1569            do_nodev $rnodes "$@"
1570         else
1571            do_node $rnodes "$@"
1572         fi
1573         return $?
1574     fi
1575
1576     # This is part from do_node
1577     local myPDSH=$PDSH
1578
1579     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
1580         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
1581
1582     if $VERBOSE; then
1583         echo "CMD: $rnodes $@" >&2
1584         $myPDSH $rnodes $LCTL mark "$@" > /dev/null 2>&1 || :
1585     fi
1586
1587     if $verbose ; then
1588         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")"
1589     else
1590         $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"
1591     fi
1592     return ${PIPESTATUS[0]}
1593 }
1594
1595 do_facet() {
1596     local facet=$1
1597     shift
1598     local HOST=`facet_active_host $facet`
1599     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
1600     do_node $HOST "$@"
1601 }
1602
1603 do_nodesv() {
1604     do_nodes --verbose "$@"
1605 }
1606
1607 add() {
1608     local facet=$1
1609     shift
1610     # make sure its not already running
1611     stop ${facet} -f
1612     rm -f $TMP/${facet}active
1613     do_facet ${facet} $MKFS $*
1614 }
1615
1616 ostdevname() {
1617     num=$1
1618     DEVNAME=OSTDEV$num
1619     #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
1620     eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}}
1621     echo -n $DEVPTR
1622 }
1623
1624 mdsdevname() {
1625     num=$1
1626     DEVNAME=MDSDEV$num
1627     #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
1628     eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}}
1629     echo -n $DEVPTR
1630 }
1631
1632 ########
1633 ## MountConf setup
1634
1635 stopall() {
1636     # make sure we are using the primary server, so test-framework will
1637     # be able to clean up properly.
1638     activemds=`facet_active mds1`
1639     if [ $activemds != "mds1" ]; then
1640         fail mds1
1641     fi
1642
1643     local clients=$CLIENTS
1644     [ -z $clients ] && clients=$(hostname)
1645
1646     zconf_umount_clients $clients $MOUNT "$*" || true
1647     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
1648
1649     [ "$CLIENTONLY" ] && return
1650     # The add fn does rm ${facet}active file, this would be enough
1651     # if we use do_facet <facet> only after the facet added, but
1652     # currently we use do_facet mds in local.sh
1653     for num in `seq $MDSCOUNT`; do
1654         stop mds$num -f
1655         rm -f ${TMP}/mds${num}active
1656     done
1657
1658     for num in `seq $OSTCOUNT`; do
1659         stop ost$num -f
1660         rm -f $TMP/ost${num}active
1661     done
1662
1663     if ! combined_mgs_mds ; then
1664         stop mgs
1665     fi
1666
1667     return 0
1668 }
1669
1670 cleanupall() {
1671     nfs_client_mode && return
1672
1673     stopall $*
1674     unload_modules
1675     cleanup_gss
1676 }
1677
1678 mdsmkfsopts()
1679 {
1680     local nr=$1
1681     test $nr = 1 && echo -n $MDS_MKFS_OPTS || echo -n $MDSn_MKFS_OPTS
1682 }
1683
1684 combined_mgs_mds () {
1685     [[ $MDSDEV1 = $MGSDEV ]] && [[ $mds1_HOST = $mgs_HOST ]]
1686 }
1687
1688 formatall() {
1689     if [ "$IAMDIR" == "yes" ]; then
1690         MDS_MKFS_OPTS="$MDS_MKFS_OPTS --iam-dir"
1691         MDSn_MKFS_OPTS="$MDSn_MKFS_OPTS --iam-dir"
1692     fi
1693
1694     [ "$FSTYPE" ] && FSTYPE_OPT="--backfstype $FSTYPE"
1695
1696     stopall
1697     # We need ldiskfs here, may as well load them all
1698     load_modules
1699     [ "$CLIENTONLY" ] && return
1700     echo Formatting mgs, mds, osts
1701     if ! combined_mgs_mds ; then
1702         add mgs $mgs_MKFS_OPTS $FSTYPE_OPT --reformat $MGSDEV || exit 10
1703     fi
1704
1705     for num in `seq $MDSCOUNT`; do
1706         echo "Format mds$num: $(mdsdevname $num)"
1707         if $VERBOSE; then
1708             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` || exit 9
1709         else
1710             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` > /dev/null || exit 9
1711         fi
1712     done
1713
1714     for num in `seq $OSTCOUNT`; do
1715         echo "Format ost$num: $(ostdevname $num)"
1716         if $VERBOSE; then
1717             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` || exit 10
1718         else
1719             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` > /dev/null || exit 10
1720         fi
1721     done
1722 }
1723
1724 mount_client() {
1725     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
1726 }
1727
1728 umount_client() {
1729     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
1730 }
1731
1732 # return value:
1733 # 0: success, the old identity set already.
1734 # 1: success, the old identity does not set.
1735 # 2: fail.
1736 switch_identity() {
1737     local num=$1
1738     local switch=$2
1739     local j=`expr $num - 1`
1740     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
1741
1742     if [ -z "$MDT" ]; then
1743         return 2
1744     fi
1745
1746     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
1747
1748     if $switch; then
1749         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
1750     else
1751         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
1752     fi
1753
1754     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush \"-1\""
1755
1756     if [ $old = "NONE" ]; then
1757         return 1
1758     else
1759         return 0
1760     fi
1761 }
1762
1763 remount_client()
1764 {
1765         zconf_umount `hostname` $1 || error "umount failed"
1766         zconf_mount `hostname` $1 || error "mount failed"
1767 }
1768
1769 writeconf_facet () {
1770     local facet=$1
1771     local dev=$2
1772
1773     do_facet $facet "$TUNEFS --writeconf $dev"
1774 }
1775
1776 writeconf_all () {
1777     for num in `seq $MDSCOUNT`; do
1778         DEVNAME=$(mdsdevname $num)
1779         writeconf_facet mds$num $DEVNAME
1780     done
1781
1782     for num in `seq $OSTCOUNT`; do
1783         DEVNAME=$(ostdevname $num)
1784         writeconf_facet ost$num $DEVNAME
1785     done
1786 }
1787
1788 setupall() {
1789     nfs_client_mode && return
1790
1791     sanity_mount_check ||
1792         error "environments are insane!"
1793
1794     load_modules
1795
1796     if [ -z "$CLIENTONLY" ]; then
1797         echo Setup mgs, mdt, osts
1798         echo $WRITECONF | grep -q "writeconf" && \
1799             writeconf_all
1800         if ! combined_mgs_mds ; then
1801             start mgs $MGSDEV $mgs_MOUNT_OPTS
1802         fi
1803
1804         for num in `seq $MDSCOUNT`; do
1805             DEVNAME=$(mdsdevname $num)
1806             start mds$num $DEVNAME $MDS_MOUNT_OPTS
1807
1808             # We started mds, now we should set failover variables properly.
1809             # Set mds${num}failover_HOST if it is not set (the default failnode).
1810             local varname=mds${num}failover_HOST
1811             if [ -z "${!varname}" ]; then
1812                 eval mds${num}failover_HOST=$(facet_host mds$num)
1813             fi
1814
1815             if [ $IDENTITY_UPCALL != "default" ]; then
1816                 switch_identity $num $IDENTITY_UPCALL
1817             fi
1818         done
1819         for num in `seq $OSTCOUNT`; do
1820             DEVNAME=$(ostdevname $num)
1821             start ost$num $DEVNAME $OST_MOUNT_OPTS
1822
1823             # We started ost$num, now we should set ost${num}failover variable properly.
1824             # Set ost${num}failover_HOST if it is not set (the default failnode).
1825             varname=ost${num}failover_HOST
1826             if [ -z "${!varname}" ]; then
1827                 eval ost${num}failover_HOST=$(facet_host ost${num})
1828             fi
1829
1830         done
1831     fi
1832
1833     init_gss
1834
1835     # wait a while to allow sptlrpc configuration be propogated to targets,
1836     # only needed when mounting new target devices.
1837     if $GSS; then
1838         sleep 10
1839     fi
1840
1841     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
1842     mount_client $MOUNT
1843     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
1844
1845     if [ "$MOUNT_2" ]; then
1846         mount_client $MOUNT2
1847         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
1848     fi
1849
1850     init_param_vars
1851
1852     # by remounting mdt before ost, initial connect from mdt to ost might
1853     # timeout because ost is not ready yet. wait some time to its fully
1854     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
1855     # by a context negotiation rpc with $TIMEOUT.
1856     # FIXME better by monitoring import status.
1857     if $GSS; then
1858         set_flavor_all $SEC
1859         sleep $((TIMEOUT + 5))
1860     else
1861         sleep 5
1862     fi
1863 }
1864
1865 mounted_lustre_filesystems() {
1866         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
1867 }
1868
1869 init_facet_vars () {
1870     [ "$CLIENTONLY" ] && return 0
1871     local facet=$1
1872     shift
1873     local device=$1
1874
1875     shift
1876
1877     eval export ${facet}_dev=${device}
1878     eval export ${facet}_opt=\"$@\"
1879
1880     local dev=${facet}_dev
1881     local label=$(do_facet ${facet} "$E2LABEL ${!dev}")
1882     [ -z "$label" ] && echo no label for ${!dev} && exit 1
1883
1884     eval export ${facet}_svc=${label}
1885
1886     local varname=${facet}failover_HOST
1887     if [ -z "${!varname}" ]; then
1888        eval $varname=$(facet_host $facet) 
1889     fi
1890
1891     # ${facet}failover_dev is set in cfg file
1892     varname=${facet}failover_dev
1893     if [ -n "${!varname}" ] ; then
1894         eval export ${facet}failover_dev=${!varname}
1895     else
1896         eval export ${facet}failover_dev=$device
1897     fi
1898 }
1899
1900 init_facets_vars () {
1901     local DEVNAME
1902
1903     if ! remote_mds_nodsh; then 
1904         for num in `seq $MDSCOUNT`; do
1905             DEVNAME=`mdsdevname $num`
1906             init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
1907         done
1908     fi
1909
1910     remote_ost_nodsh && return
1911
1912     for num in `seq $OSTCOUNT`; do
1913         DEVNAME=`ostdevname $num`
1914         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
1915     done
1916 }
1917
1918 osc_ensure_active () {
1919     local facet=$1
1920     local type=$2
1921     local timeout=$3
1922     local period=0
1923
1924     while [ $period -lt $timeout ]; do
1925         count=$(do_facet $facet "lctl dl | grep '${FSNAME}-OST.*-osc-${type}' | grep ' IN ' 2>/dev/null | wc -l")
1926         if [ $count -eq 0 ]; then
1927             break
1928         fi
1929
1930         echo "There are $count OST are inactive, wait $period seconds, and try again"
1931         sleep 3
1932         period=$((period+3))
1933     done
1934
1935     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
1936 }
1937
1938 init_param_vars () {
1939     if ! remote_ost_nodsh && ! remote_mds_nodsh; then
1940         export MDSVER=$(do_facet $SINGLEMDS "lctl get_param version" | cut -d. -f1,2)
1941         export OSTVER=$(do_facet ost1 "lctl get_param version" | cut -d. -f1,2)
1942         export CLIVER=$(lctl get_param version | cut -d. -f 1,2)
1943     fi
1944
1945     remote_mds_nodsh ||
1946         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
1947
1948     log "Using TIMEOUT=$TIMEOUT"
1949
1950     osc_ensure_active $SINGLEMDS M $TIMEOUT
1951     osc_ensure_active client c $TIMEOUT
1952
1953     if [ $QUOTA_AUTO -ne 0 ]; then
1954         if [ "$ENABLE_QUOTA" ]; then
1955             echo "enable quota as required"
1956             setup_quota $MOUNT || return 2
1957         else
1958             echo "disable quota as required"
1959             $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
1960         fi
1961     fi
1962
1963     return 0
1964 }
1965
1966 nfs_client_mode () {
1967     if [ "$NFSCLIENT" ]; then
1968         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
1969         local clients=$CLIENTS
1970         [ -z $clients ] && clients=$(hostname)
1971
1972         # FIXME: remove hostname when 19215 fixed
1973         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
1974         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
1975         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
1976         return
1977     fi
1978     return 1
1979 }
1980
1981 check_config_client () {
1982     local mntpt=$1
1983
1984     local mounted=$(mount | grep " $mntpt ")
1985     if [ "$CLIENTONLY" ]; then
1986         # bug 18021
1987         # CLIENTONLY should not depend on *_HOST settings
1988         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
1989         # in theory someone could create a new,
1990         # client-only config file that assumed lustre was already
1991         # configured and didn't set the MGSNID. If MGSNID is not set,
1992         # then we should use the mgs nid currently being used 
1993         # as the default value. bug 18021
1994         [[ x$MGSNID = x ]] &&
1995             MGSNID=${mgc//MGC/}
1996
1997         if [[ x$mgc != xMGC$MGSNID ]]; then
1998             if [ "$mgs_HOST" ]; then
1999                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
2000 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
2001 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
2002             fi
2003         fi
2004         return 0
2005     fi
2006
2007     local myMGS_host=$mgs_HOST   
2008     if [ "$NETTYPE" = "ptl" ]; then
2009         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
2010     fi
2011
2012     echo Checking config lustre mounted on $mntpt
2013     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
2014     mgshost=$(echo $mgshost | awk -F: '{print $1}')
2015
2016 #    if [ "$mgshost" != "$myMGS_host" ]; then
2017 #            log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
2018 #                   Please use correct config or set mds_HOST correctly!"
2019 #    fi
2020
2021 }
2022
2023 check_config_clients () {
2024     local clients=${CLIENTS:-$HOSTNAME}
2025     local mntpt=$1
2026
2027     nfs_client_mode && return
2028
2029     do_rpc_nodes $clients check_config_client $mntpt
2030
2031     sanity_mount_check ||
2032         error "environments are insane!"
2033 }
2034
2035 check_timeout () {
2036     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
2037     local cltimeout=$(lctl get_param -n timeout)
2038     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
2039         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
2040         return 1
2041     fi
2042 }
2043
2044 is_mounted () {
2045     local mntpt=$1
2046     local mounted=$(mounted_lustre_filesystems)
2047
2048     echo $mounted' ' | grep -w -q $mntpt' '
2049 }
2050
2051 check_and_setup_lustre() {
2052     nfs_client_mode && return
2053
2054     local MOUNTED=$(mounted_lustre_filesystems)
2055
2056     local do_check=true
2057     # 1.
2058     # both MOUNT and MOUNT2 are not mounted
2059     if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
2060         [ "$REFORMAT" ] && formatall
2061         # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
2062         setupall
2063         is_mounted $MOUNT || error "NAME=$NAME not mounted"
2064         export I_MOUNTED=yes
2065         do_check=false
2066     # 2.
2067     # MOUNT2 is mounted
2068     elif is_mounted $MOUNT2; then
2069             # 3.
2070             # MOUNT2 is mounted, while MOUNT_2 is not set
2071             if ! [ "$MOUNT_2" ]; then
2072                 cleanup_mount $MOUNT2
2073                 export I_UMOUNTED2=yes
2074
2075             # 4.
2076             # MOUNT2 is mounted, MOUNT_2 is set
2077             else
2078                 # FIXME: what to do if check_config failed?
2079                 # i.e. if:
2080                 # 1) remote client has mounted other Lustre fs ?
2081                 # 2) it has insane env ?
2082                 # let's try umount MOUNT2 on all clients and mount it again:
2083                 if ! check_config_clients $MOUNT2; then
2084                     cleanup_mount $MOUNT2
2085                     restore_mount $MOUNT2
2086                     export I_MOUNTED2=yes
2087                 fi
2088             fi 
2089
2090     # 5.
2091     # MOUNT is mounted MOUNT2 is not mounted
2092     elif [ "$MOUNT_2" ]; then
2093         restore_mount $MOUNT2
2094         export I_MOUNTED2=yes
2095     fi
2096
2097     if $do_check; then
2098         # FIXME: what to do if check_config failed?
2099         # i.e. if:
2100         # 1) remote client has mounted other Lustre fs?
2101         # 2) lustre is mounted on remote_clients atall ?
2102         check_config_clients $MOUNT
2103         init_facets_vars
2104         init_param_vars
2105
2106         do_nodes $(comma_list $(nodes_list)) "lctl set_param debug=\\\"$PTLDEBUG\\\";
2107             lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
2108             lctl set_param debug_mb=${DEBUG_SIZE};
2109             sync"
2110     fi
2111
2112     init_gss
2113     set_flavor_all $SEC
2114
2115     if [ "$ONLY" == "setup" ]; then
2116         exit 0
2117     fi
2118 }
2119
2120 restore_mount () {
2121    local clients=${CLIENTS:-$HOSTNAME}
2122    local mntpt=$1
2123
2124    zconf_mount_clients $clients $mntpt
2125 }
2126
2127 cleanup_mount () {
2128     local clients=${CLIENTS:-$HOSTNAME}
2129     local mntpt=$1
2130
2131     zconf_umount_clients $clients $mntpt    
2132 }
2133
2134 cleanup_and_setup_lustre() {
2135     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
2136         lctl set_param debug=0 || true
2137         cleanupall
2138         if [ "$ONLY" == "cleanup" ]; then
2139             exit 0
2140         fi
2141     fi
2142     check_and_setup_lustre
2143 }
2144
2145 check_and_cleanup_lustre() {
2146     if is_mounted $MOUNT; then
2147         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
2148         [ "$ENABLE_QUOTA" ] && restore_quota_type || true
2149     fi
2150
2151     if [ "$I_UMOUNTED2" = "yes" ]; then
2152         restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
2153     fi
2154
2155     if [ "$I_MOUNTED2" = "yes" ]; then
2156         cleanup_mount $MOUNT2
2157     fi
2158
2159     if [ "$I_MOUNTED" = "yes" ]; then
2160         cleanupall -f || error "cleanup failed"
2161         unset I_MOUNTED
2162     fi
2163 }
2164
2165 #######
2166 # General functions
2167
2168 check_network() {
2169     local NETWORK=0
2170     local WAIT=0
2171     local MAX=$2
2172     while [ $NETWORK -eq 0 ]; do
2173         if ping -c 1 -w 3 $1 > /dev/null; then
2174             NETWORK=1
2175         else
2176             WAIT=$((WAIT + 5))
2177             echo "waiting for $1, $((MAX - WAIT)) secs left"
2178             sleep 5
2179         fi
2180         if [ $WAIT -gt $MAX ]; then
2181             echo "Network not available"
2182             exit 1
2183         fi
2184     done
2185 }
2186 check_port() {
2187     while( !($DSH2 $1 "netstat -tna | grep -q $2") ) ; do
2188         sleep 9
2189     done
2190 }
2191
2192 no_dsh() {
2193     shift
2194     eval $@
2195 }
2196
2197 comma_list() {
2198     # the sed converts spaces to commas, but leaves the last space
2199     # alone, so the line doesn't end with a comma.
2200     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
2201 }
2202
2203 # list, excluded are the comma separated lists
2204 exclude_items_from_list () {
2205     local list=$1
2206     local excluded=$2
2207     local item
2208
2209     list=${list//,/ }
2210     for item in ${excluded//,/ }; do
2211         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
2212     done
2213     echo $(comma_list $list) 
2214 }
2215
2216 # list, expand  are the comma separated lists
2217 expand_list () {
2218     local list=${1//,/ }
2219     local expand=${2//,/ }
2220     local expanded=
2221
2222     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
2223     echo $(comma_list $expanded)
2224 }
2225
2226 testslist_filter () {
2227     local script=$LUSTRE/tests/${TESTSUITE}.sh
2228
2229     [ -f $script ] || return 0
2230
2231     local start_at=$START_AT
2232     local stop_at=$STOP_AT
2233
2234     local var=${TESTSUITE//-/_}_START_AT
2235     [ x"${!var}" != x ] && start_at=${!var}
2236     var=${TESTSUITE//-/_}_STOP_AT
2237     [ x"${!var}" != x ] && stop_at=${!var}
2238
2239     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
2240         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
2241             /^'${start_at}'$/ {flag = 0}
2242             {if (flag == 1) print $0}
2243             /^'${stop_at}'$/ { flag = 1 }'
2244 }
2245
2246 absolute_path() {
2247     (cd `dirname $1`; echo $PWD/`basename $1`)
2248 }
2249
2250 get_facets () {
2251     local name=$(echo $1 | tr "[:upper:]" "[:lower:]")
2252     local type=$(echo $1 | tr "[:lower:]" "[:upper:]")
2253
2254     local list=""
2255     local count=${type}COUNT
2256     for ((i=1; i<=${!count}; i++)) do
2257         list="$list ${name}$i"
2258     done
2259     echo $(comma_list $list)
2260 }
2261
2262 ##################################
2263 # Adaptive Timeouts funcs
2264
2265 at_is_enabled() {
2266     # only check mds, we assume at_max is the same on all nodes
2267     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
2268     if [ $at_max -eq 0 ]; then
2269         return 1
2270     else
2271         return 0
2272     fi
2273 }
2274
2275 at_max_get() {
2276     local facet=$1
2277
2278     # suppose that all ost-s has the same at_max set
2279     if [ $facet == "ost" ]; then
2280         do_facet ost1 "lctl get_param -n at_max"
2281     else
2282         do_facet $facet "lctl get_param -n at_max"
2283     fi
2284 }
2285
2286 at_max_set() {
2287     local at_max=$1
2288     shift
2289
2290     local facet
2291     for facet in $@; do
2292         if [ $facet == "ost" ]; then
2293             for i in `seq $OSTCOUNT`; do
2294                 do_facet ost$i "lctl set_param at_max=$at_max"
2295
2296             done
2297         elif [ $facet == "mds" ]; then
2298             for i in `seq $MDSCOUNT`; do
2299                 do_facet mds$i "lctl set_param at_max=$at_max"
2300             done
2301         else
2302             do_facet $facet "lctl set_param at_max=$at_max"
2303         fi
2304     done
2305 }
2306
2307 ##################################
2308 # OBD_FAIL funcs
2309
2310 drop_request() {
2311 # OBD_FAIL_MDS_ALL_REQUEST_NET
2312     RC=0
2313     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
2314     do_facet client "$1" || RC=$?
2315     do_facet $SINGLEMDS lctl set_param fail_loc=0
2316     return $RC
2317 }
2318
2319 drop_reply() {
2320 # OBD_FAIL_MDS_ALL_REPLY_NET
2321     RC=0
2322     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
2323     do_facet client "$@" || RC=$?
2324     do_facet $SINGLEMDS lctl set_param fail_loc=0
2325     return $RC
2326 }
2327
2328 drop_reint_reply() {
2329 # OBD_FAIL_MDS_REINT_NET_REP
2330     RC=0
2331     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
2332     do_facet client "$@" || RC=$?
2333     do_facet $SINGLEMDS lctl set_param fail_loc=0
2334     return $RC
2335 }
2336
2337 pause_bulk() {
2338 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
2339     RC=0
2340     do_facet ost1 lctl set_param fail_loc=0x214
2341     do_facet client "$1" || RC=$?
2342     do_facet client "sync"
2343     do_facet ost1 lctl set_param fail_loc=0
2344     return $RC
2345 }
2346
2347 drop_ldlm_cancel() {
2348 #define OBD_FAIL_LDLM_CANCEL             0x304
2349     RC=0
2350     do_facet client lctl set_param fail_loc=0x304
2351     do_facet client "$@" || RC=$?
2352     do_facet client lctl set_param fail_loc=0
2353     return $RC
2354 }
2355
2356 drop_bl_callback() {
2357 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
2358     RC=0
2359     do_facet client lctl set_param fail_loc=0x305
2360     do_facet client "$@" || RC=$?
2361     do_facet client lctl set_param fail_loc=0
2362     return $RC
2363 }
2364
2365 drop_ldlm_reply() {
2366 #define OBD_FAIL_LDLM_REPLY              0x30c
2367     RC=0
2368     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
2369     do_facet client "$@" || RC=$?
2370     do_facet $SINGLEMDS lctl set_param fail_loc=0
2371     return $RC
2372 }
2373
2374 clear_failloc() {
2375     facet=$1
2376     pause=$2
2377     sleep $pause
2378     echo "clearing fail_loc on $facet"
2379     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
2380 }
2381
2382 set_nodes_failloc () {
2383     do_nodes $(comma_list $1)  lctl set_param fail_loc=$2
2384 }
2385
2386 cancel_lru_locks() {
2387     $LCTL mark "cancel_lru_locks $1 start"
2388     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
2389         $LCTL set_param -n $d=clear
2390     done
2391     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
2392     $LCTL mark "cancel_lru_locks $1 stop"
2393 }
2394
2395 default_lru_size()
2396 {
2397         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
2398         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
2399         echo "$DEFAULT_LRU_SIZE"
2400 }
2401
2402 lru_resize_enable()
2403 {
2404     lctl set_param ldlm.namespaces.*$1*.lru_size=0
2405 }
2406
2407 lru_resize_disable()
2408 {
2409     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
2410 }
2411
2412 pgcache_empty() {
2413     local FILE
2414     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
2415         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
2416             echo there is still data in page cache $FILE ?
2417             lctl get_param -n $FILE
2418             return 1
2419         fi
2420     done
2421     return 0
2422 }
2423
2424 debugsave() {
2425     DEBUGSAVE="$(lctl get_param -n debug)"
2426 }
2427
2428 debugrestore() {
2429     [ -n "$DEBUGSAVE" ] && \
2430         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
2431     DEBUGSAVE=""
2432 }
2433
2434 debug_size_save() {
2435     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
2436 }
2437
2438 debug_size_restore() {
2439     [ -n "$DEBUG_SIZE_SAVED" ] && \
2440         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
2441     DEBUG_SIZE_SAVED=""
2442 }
2443
2444 start_full_debug_logging() {
2445     debugsave
2446     debug_size_save
2447
2448     local FULLDEBUG=-1
2449     local DEBUG_SIZE=150
2450
2451     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
2452     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
2453 }
2454
2455 stop_full_debug_logging() {
2456     debug_size_restore
2457     debugrestore
2458 }
2459
2460 ##################################
2461 # Test interface
2462 ##################################
2463
2464 error_noexit() {
2465     local TYPE=${TYPE:-"FAIL"}
2466
2467     local dump=true
2468     # do not dump logs if $1=false
2469     if [ "x$1" = "xfalse" ]; then
2470         shift
2471         dump=false
2472     fi
2473
2474     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
2475
2476     # We need to dump the logs on all nodes
2477     if $dump; then
2478         gather_logs $(comma_list $(nodes_list))
2479     fi
2480
2481     debugrestore
2482     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
2483     echo "$@" > $LOGDIR/err
2484 }
2485
2486 error() {
2487     error_noexit "$@"
2488     exit 1
2489 }
2490
2491 error_exit() {
2492     error "$@"
2493 }
2494
2495 # use only if we are ignoring failures for this test, bugno required.
2496 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
2497 # e.g. error_ignore 5494 "your message"
2498 error_ignore() {
2499     local TYPE="IGNORE (bz$1)"
2500     shift
2501     error_noexit "$@"
2502 }
2503
2504 skip_env () {
2505     $FAIL_ON_SKIP_ENV && error false $@ || skip $@
2506 }
2507
2508 skip () {
2509     echo
2510     log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
2511     [ "$TESTSUITELOG" ] && \
2512         echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
2513 }
2514
2515 build_test_filter() {
2516     EXCEPT="$EXCEPT $(testslist_filter)"
2517
2518     [ "$ONLY" ] && log "only running test `echo $ONLY`"
2519     for O in $ONLY; do
2520         eval ONLY_${O}=true
2521     done
2522     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
2523         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
2524     [ "$EXCEPT_SLOW" ] && \
2525         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
2526     for E in $EXCEPT $ALWAYS_EXCEPT; do
2527         eval EXCEPT_${E}=true
2528     done
2529     for E in $EXCEPT_SLOW; do
2530         eval EXCEPT_SLOW_${E}=true
2531     done
2532     for G in $GRANT_CHECK_LIST; do
2533         eval GCHECK_ONLY_${G}=true
2534         done
2535 }
2536
2537 basetest() {
2538     if [[ $1 = [a-z]* ]]; then
2539         echo $1
2540     else
2541         echo ${1%%[a-z]*}
2542     fi
2543 }
2544
2545 # print a newline if the last test was skipped
2546 export LAST_SKIPPED=
2547 #
2548 # Main entry into test-framework. This is called with the name and
2549 # description of a test. The name is used to find the function to run
2550 # the test using "test_$name".
2551 #
2552 # This supports a variety of methods of specifying specific test to
2553 # run or not run.  These need to be documented...
2554 #
2555 run_test() {
2556     assert_DIR
2557
2558     export base=`basetest $1`
2559     if [ ! -z "$ONLY" ]; then
2560         testname=ONLY_$1
2561         if [ ${!testname}x != x ]; then
2562             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2563             run_one_logged $1 "$2"
2564             return $?
2565         fi
2566         testname=ONLY_$base
2567         if [ ${!testname}x != x ]; then
2568             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2569             run_one_logged $1 "$2"
2570             return $?
2571         fi
2572         LAST_SKIPPED="y"
2573         echo -n "."
2574         return 0
2575     fi
2576     testname=EXCEPT_$1
2577     if [ ${!testname}x != x ]; then
2578         LAST_SKIPPED="y"
2579         TESTNAME=test_$1 skip "skipping excluded test $1"
2580         return 0
2581     fi
2582     testname=EXCEPT_$base
2583     if [ ${!testname}x != x ]; then
2584         LAST_SKIPPED="y"
2585         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
2586         return 0
2587     fi
2588     testname=EXCEPT_SLOW_$1
2589     if [ ${!testname}x != x ]; then
2590         LAST_SKIPPED="y"
2591         TESTNAME=test_$1 skip "skipping SLOW test $1"
2592         return 0
2593     fi
2594     testname=EXCEPT_SLOW_$base
2595     if [ ${!testname}x != x ]; then
2596         LAST_SKIPPED="y"
2597         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
2598         return 0
2599     fi
2600
2601     LAST_SKIPPED=
2602     run_one_logged $1 "$2"
2603
2604     return $?
2605 }
2606
2607 equals_msg() {
2608     banner "$*"
2609 }
2610
2611 log() {
2612     echo "$*"
2613     module_loaded lnet || load_modules
2614
2615     local MSG="$*"
2616     # Get rid of '
2617     MSG=${MSG//\'/\\\'}
2618     MSG=${MSG//\(/\\\(}
2619     MSG=${MSG//\)/\\\)}
2620     MSG=${MSG//\;/\\\;}
2621     MSG=${MSG//\|/\\\|}
2622     MSG=${MSG//\>/\\\>}
2623     MSG=${MSG//\</\\\<}
2624     MSG=${MSG//\//\\\/}
2625     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
2626 }
2627
2628 trace() {
2629         log "STARTING: $*"
2630         strace -o $TMP/$1.strace -ttt $*
2631         RC=$?
2632         log "FINISHED: $*: rc $RC"
2633         return 1
2634 }
2635
2636 pass() {
2637     # Set TEST_STATUS here; will be used for logging the result
2638     if [ -f $LOGDIR/err ]; then
2639         TEST_STATUS="FAIL"
2640     else
2641         TEST_STATUS="PASS"
2642     fi
2643     echo $TEST_STATUS " " $@
2644 }
2645
2646 check_mds() {
2647     FFREE=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filesfree | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2648     FTOTAL=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filestotal | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2649     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
2650 }
2651
2652 reset_fail_loc () {
2653     echo -n "Resetting fail_loc on all nodes..."
2654     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
2655     echo done.
2656 }
2657
2658
2659 #
2660 # Log a message (on all nodes) padded with "=" before and after. 
2661 # Also appends a timestamp and prepends the testsuite name.
2662
2663
2664 EQUALS="===================================================================================================="
2665 banner() {
2666     msg="== ${TESTSUITE} $*"
2667     last=${msg: -1:1}
2668     [[ $last != "=" && $last != " " ]] && msg="$msg "
2669     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
2670     # always include at least == after the message
2671     log "$msg== $(date +"%H:%M:%S (%s)")"
2672 }
2673
2674 #
2675 # Run a single test function and cleanup after it.  
2676 #
2677 # This function should be run in a subshell so the test func can
2678 # exit() without stopping the whole script.
2679 #
2680 run_one() {
2681     local testnum=$1
2682     local message=$2
2683     tfile=f${testnum}
2684     export tdir=d0.${TESTSUITE}/d${base}
2685     export TESTNAME=test_$testnum
2686     local SAVE_UMASK=`umask`
2687     umask 0022
2688
2689     banner "test $testnum: $message"
2690     test_${testnum} || error "test_$testnum failed with $?"
2691     cd $SAVE_PWD
2692     reset_fail_loc
2693     check_grant ${testnum} || error "check_grant $testnum failed with $?"
2694     check_catastrophe || error "LBUG/LASSERT detected"
2695     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
2696     unset TESTNAME
2697     unset tdir
2698     umask $SAVE_UMASK
2699     return 0
2700 }
2701
2702 #
2703 # Wrapper around run_one to ensure:
2704 #  - test runs in subshell
2705 #  - output of test is saved to separate log file for error reporting
2706 #  - test result is saved to data file
2707 #
2708 run_one_logged() {
2709     local BEFORE=`date +%s`
2710     local TEST_ERROR
2711     local name=${TESTSUITE}.test_${1}.test_log.$(hostname).log
2712     local test_log=$LOGDIR/$name
2713     rm -rf $LOGDIR/err
2714
2715     echo
2716     (run_one $1 "$2") 2>&1 | tee $test_log
2717     local RC=${PIPESTATUS[0]}
2718
2719     [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] && \
2720         echo "test_$1 returned $RC" | tee $LOGDIR/err
2721
2722     duration=$((`date +%s` - $BEFORE))
2723     pass "(${duration}s)"
2724     [ -f $LOGDIR/err ] && TEST_ERROR=$(cat $LOGDIR/err)
2725     log_sub_test test_${1} $TEST_STATUS $duration "$RC" "$TEST_ERROR"
2726
2727     if [ -f $LOGDIR/err ]; then
2728         $FAIL_ON_ERROR && exit $RC
2729     fi
2730
2731     return 0
2732 }
2733
2734 canonical_path() {
2735     (cd `dirname $1`; echo $PWD/`basename $1`)
2736 }
2737
2738 sync_clients() {
2739     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
2740     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
2741         cd $SAVE_PWD
2742 }
2743
2744 check_grant() {
2745     export base=`basetest $1`
2746     [ "$CHECK_GRANT" == "no" ] && return 0
2747
2748         testname=GCHECK_ONLY_${base}
2749         [ ${!testname}x == x ] && return 0
2750
2751     echo -n "checking grant......"
2752         cd $SAVE_PWD
2753         # write some data to sync client lost_grant
2754         rm -f $DIR1/${tfile}_check_grant_* 2>&1
2755         for i in `seq $OSTCOUNT`; do
2756                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
2757                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
2758                                               count=1 > /dev/null 2>&1
2759         done
2760         # sync all the data and make sure no pending data on server
2761         sync_clients
2762         
2763         #get client grant and server grant
2764         client_grant=0
2765     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
2766                 client_grant=$((client_grant + $d))
2767         done
2768         server_grant=0
2769         for d in `lctl get_param -n obdfilter.*.tot_granted`; do
2770                 server_grant=$((server_grant + $d))
2771         done
2772
2773         # cleanup the check_grant file
2774         for i in `seq $OSTCOUNT`; do
2775                 rm $DIR1/${tfile}_check_grant_$i
2776         done
2777
2778         #check whether client grant == server grant
2779         if [ $client_grant != $server_grant ]; then
2780                 echo "failed: client:${client_grant} server: ${server_grant}"
2781                 return 1
2782         else
2783                 echo "pass"
2784         fi
2785 }
2786
2787 ########################
2788 # helper functions
2789
2790 osc_to_ost()
2791 {
2792     osc=$1
2793     ost=`echo $1 | awk -F_ '{print $3}'`
2794     if [ -z $ost ]; then
2795         ost=`echo $1 | sed 's/-osc.*//'`
2796     fi
2797     echo $ost
2798 }
2799
2800 remote_node () {
2801     local node=$1
2802     [ "$node" != "$(hostname)" ]
2803 }
2804
2805 remote_mds ()
2806 {
2807     local node
2808     for node in $(mdts_nodes); do
2809         remote_node $node && return 0
2810     done
2811     return 1
2812 }
2813
2814 remote_mds_nodsh()
2815 {
2816     [ "$CLIENTONLY" ] && return 0 || true
2817     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
2818 }
2819
2820 require_dsh_mds()
2821 {
2822         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
2823             MSKIPPED=1 && return 1
2824         return 0
2825 }
2826
2827 remote_ost ()
2828 {
2829     local node
2830     for node in $(osts_nodes) ; do
2831         remote_node $node && return 0
2832     done
2833     return 1
2834 }
2835
2836 remote_ost_nodsh()
2837 {
2838     [ "$CLIENTONLY" ] && return 0 || true 
2839     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2840 }
2841
2842 require_dsh_ost()
2843 {
2844         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
2845             OSKIPPED=1 && return 1
2846         return 0
2847 }
2848
2849 remote_mgs_nodsh()
2850 {
2851     local MGS 
2852     MGS=$(facet_host mgs)
2853     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2854 }
2855
2856 local_mode ()
2857 {
2858     remote_mds_nodsh || remote_ost_nodsh || \
2859         $(single_local_node $(comma_list $(nodes_list)))
2860 }
2861
2862 mdts_nodes () {
2863     local MDSNODES
2864     local NODES_sort
2865     for num in `seq $MDSCOUNT`; do
2866         MDSNODES="$MDSNODES $(facet_host mds$num)"
2867     done
2868     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
2869
2870     echo $NODES_sort
2871 }
2872
2873 remote_servers () {
2874     remote_ost && remote_mds
2875 }
2876
2877 osts_nodes () {
2878     local OSTNODES=$(facet_host ost1)
2879     local NODES_sort
2880
2881     for num in `seq $OSTCOUNT`; do
2882         local myOST=$(facet_host ost$num)
2883         OSTNODES="$OSTNODES $myOST"
2884     done
2885     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
2886
2887     echo $NODES_sort
2888 }
2889
2890 nodes_list () {
2891     # FIXME. We need a list of clients
2892     local myNODES=$HOSTNAME
2893     local myNODES_sort
2894
2895     # CLIENTS (if specified) contains the local client
2896     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
2897
2898     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
2899         myNODES="$myNODES $(osts_nodes) $(mdts_nodes)"
2900     fi
2901
2902     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
2903
2904     echo $myNODES_sort
2905 }
2906
2907 remote_nodes_list () {
2908     local rnodes=$(nodes_list)
2909     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2910     echo $rnodes
2911 }
2912
2913 init_clients_lists () {
2914     # Sanity check: exclude the local client from RCLIENTS
2915     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2916
2917     # Sanity check: exclude the dup entries
2918     rclients=$(for i in $rclients; do echo $i; done | sort -u)
2919
2920     local clients="$SINGLECLIENT $HOSTNAME $rclients"
2921
2922     # Sanity check: exclude the dup entries from CLIENTS
2923     # for those configs which has SINGLCLIENT set to local client
2924     clients=$(for i in $clients; do echo $i; done | sort -u)
2925
2926     CLIENTS=`comma_list $clients`
2927     local -a remoteclients=($rclients)
2928     for ((i=0; $i<${#remoteclients[@]}; i++)); do
2929             varname=CLIENT$((i + 2))
2930             eval $varname=${remoteclients[i]}
2931     done
2932
2933     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
2934 }
2935
2936 get_random_entry () {
2937     local rnodes=$1
2938
2939     rnodes=${rnodes//,/ }
2940
2941     local -a nodes=($rnodes)
2942     local num=${#nodes[@]} 
2943     local i=$((RANDOM * num * 2 / 65536))
2944
2945     echo ${nodes[i]}
2946 }
2947
2948 client_only () {
2949     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
2950 }
2951
2952 is_patchless ()
2953 {
2954     lctl get_param version | grep -q patchless
2955 }
2956
2957 check_versions () {
2958     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
2959 }
2960
2961 get_node_count() {
2962     local nodes="$@"
2963     echo $nodes | wc -w || true
2964 }
2965
2966 mixed_ost_devs () {
2967     local nodes=$(osts_nodes)
2968     local osscount=$(get_node_count "$nodes")
2969     [ ! "$OSTCOUNT" = "$osscount" ]
2970 }
2971
2972 mixed_mdt_devs () {
2973     local nodes=$(mdts_nodes)
2974     local mdtcount=$(get_node_count "$nodes")
2975     [ ! "$MDSCOUNT" = "$mdtcount" ]
2976 }
2977
2978 generate_machine_file() {
2979     local nodes=${1//,/ }
2980     local machinefile=$2
2981     rm -f $machinefile
2982     for node in $nodes; do
2983         echo $node >>$machinefile || \
2984             { echo "can not generate machinefile $machinefile" && return 1; }
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_nodev $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_nodesv $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_nodesv $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_nodesv $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 # target_start_and_reset_recovery_timer()
3573 #        service_time = at_est2timeout(service_time);
3574 #        service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC +
3575 #                             INITIAL_CONNECT_TIMEOUT);
3576 # CONNECTION_SWITCH_MAX : min(25U, max(CONNECTION_SWITCH_MIN,obd_timeout))
3577 #define CONNECTION_SWITCH_INC 1
3578 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
3579 #define CONNECTION_SWITCH_MIN 5U
3580
3581 max_recovery_time () {
3582     local init_connect_timeout=$(( TIMEOUT / 20 ))
3583     [[ $init_connect_timeout > 5 ]] || init_connect_timeout=5 
3584
3585     local service_time=$(( $(at_max_get client) + $(( 2 * $(( 25 + 1  + init_connect_timeout)) )) ))
3586
3587     echo $service_time 
3588 }
3589
3590 get_clients_mount_count () {
3591     local clients=${CLIENTS:-`hostname`}
3592
3593     # we need to take into account the clients mounts and
3594     # exclude mds/ost mounts if any;
3595     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
3596 }
3597
3598 # gss functions
3599 PROC_CLI="srpc_info"
3600
3601 combination()
3602 {
3603     local M=$1
3604     local N=$2
3605     local R=1
3606
3607     if [ $M -lt $N ]; then
3608         R=0
3609     else
3610         N=$((N + 1))
3611         while [ $N -lt $M ]; do
3612             R=$((R * N))
3613             N=$((N + 1))
3614         done
3615     fi
3616
3617     echo $R
3618     return 0
3619 }
3620
3621 calc_connection_cnt() {
3622     local dir=$1
3623
3624     # MDT->MDT = 2 * C(M, 2)
3625     # MDT->OST = M * O
3626     # CLI->OST = C * O
3627     # CLI->MDT = C * M
3628     comb_m2=$(combination $MDSCOUNT 2)
3629
3630     local num_clients=$(get_clients_mount_count)
3631
3632     local cnt_mdt2mdt=$((comb_m2 * 2))
3633     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
3634     local cnt_cli2ost=$((num_clients * OSTCOUNT))
3635     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
3636     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
3637     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
3638     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
3639
3640     local var=cnt_$dir
3641     local res=${!var}
3642
3643     echo $res
3644 }
3645
3646 set_rule()
3647 {
3648     local tgt=$1
3649     local net=$2
3650     local dir=$3
3651     local flavor=$4
3652     local cmd="$tgt.srpc.flavor"
3653
3654     if [ $net == "any" ]; then
3655         net="default"
3656     fi
3657     cmd="$cmd.$net"
3658
3659     if [ $dir != "any" ]; then
3660         cmd="$cmd.$dir"
3661     fi
3662
3663     cmd="$cmd=$flavor"
3664     log "Setting sptlrpc rule: $cmd"
3665     do_facet mgs "$LCTL conf_param $cmd"
3666 }
3667
3668 count_flvr()
3669 {
3670     local output=$1
3671     local flavor=$2
3672     local count=0
3673
3674     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
3675     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
3676
3677     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
3678
3679     if [ "x$bulkspec" != "x" ]; then
3680         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
3681
3682         if [ "x$algs" != "x" ]; then
3683             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
3684         else
3685             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
3686             if [ $bulk == "bulkn" ]; then
3687                 bulk_count=`echo "$output" | grep "bulk flavor" \
3688                             | grep "null/null" | wc -l`
3689             elif [ $bulk == "bulki" ]; then
3690                 bulk_count=`echo "$output" | grep "bulk flavor" \
3691                             | grep "/null" | grep -v "null/" | wc -l`
3692             else
3693                 bulk_count=`echo "$output" | grep "bulk flavor" \
3694                             | grep -v "/null" | grep -v "null/" | wc -l`
3695             fi
3696         fi
3697
3698         [ $bulk_count -lt $count ] && count=$bulk_count
3699     fi
3700
3701     echo $count
3702 }
3703
3704 flvr_cnt_cli2mdt()
3705 {
3706     local flavor=$1
3707     local cnt
3708
3709     local clients=${CLIENTS:-`hostname`}
3710
3711     for c in ${clients//,/ }; do
3712         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
3713         tmpcnt=`count_flvr "$output" $flavor`
3714         cnt=$((cnt + tmpcnt))
3715     done
3716     echo $cnt
3717 }
3718
3719 flvr_cnt_cli2ost()
3720 {
3721     local flavor=$1
3722     local cnt
3723
3724     local clients=${CLIENTS:-`hostname`}
3725
3726     for c in ${clients//,/ }; do
3727         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$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_mdt2mdt()
3735 {
3736     local flavor=$1
3737     local cnt=0
3738
3739     if [ $MDSCOUNT -le 1 ]; then
3740         echo 0
3741         return
3742     fi
3743
3744     for num in `seq $MDSCOUNT`; do
3745         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
3746         tmpcnt=`count_flvr "$output" $flavor`
3747         cnt=$((cnt + tmpcnt))
3748     done
3749     echo $cnt;
3750 }
3751
3752 flvr_cnt_mdt2ost()
3753 {
3754     local flavor=$1
3755     local cnt=0
3756
3757     for num in `seq $MDSCOUNT`; do
3758         output=`do_facet mds$num lctl get_param -n osc.*OST*-osc-MDT*.$PROC_CLI 2>/dev/null`
3759         tmpcnt=`count_flvr "$output" $flavor`
3760         cnt=$((cnt + tmpcnt))
3761     done
3762     echo $cnt;
3763 }
3764
3765 flvr_cnt_mgc2mgs()
3766 {
3767     local flavor=$1
3768
3769     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
3770     count_flvr "$output" $flavor
3771 }
3772
3773 do_check_flavor()
3774 {
3775     local dir=$1        # from to
3776     local flavor=$2     # flavor expected
3777     local res=0
3778
3779     if [ $dir == "cli2mdt" ]; then
3780         res=`flvr_cnt_cli2mdt $flavor`
3781     elif [ $dir == "cli2ost" ]; then
3782         res=`flvr_cnt_cli2ost $flavor`
3783     elif [ $dir == "mdt2mdt" ]; then
3784         res=`flvr_cnt_mdt2mdt $flavor`
3785     elif [ $dir == "mdt2ost" ]; then
3786         res=`flvr_cnt_mdt2ost $flavor`
3787     elif [ $dir == "all2ost" ]; then
3788         res1=`flvr_cnt_mdt2ost $flavor`
3789         res2=`flvr_cnt_cli2ost $flavor`
3790         res=$((res1 + res2))
3791     elif [ $dir == "all2mdt" ]; then
3792         res1=`flvr_cnt_mdt2mdt $flavor`
3793         res2=`flvr_cnt_cli2mdt $flavor`
3794         res=$((res1 + res2))
3795     elif [ $dir == "all2all" ]; then
3796         res1=`flvr_cnt_mdt2ost $flavor`
3797         res2=`flvr_cnt_cli2ost $flavor`
3798         res3=`flvr_cnt_mdt2mdt $flavor`
3799         res4=`flvr_cnt_cli2mdt $flavor`
3800         res=$((res1 + res2 + res3 + res4))
3801     fi
3802
3803     echo $res
3804 }
3805
3806 wait_flavor()
3807 {
3808     local dir=$1        # from to
3809     local flavor=$2     # flavor expected
3810     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
3811
3812     local res=0
3813
3814     for ((i=0;i<20;i++)); do
3815         echo -n "checking..."
3816         res=$(do_check_flavor $dir $flavor)
3817         if [ $res -eq $expect ]; then
3818             echo "found $res $flavor connections of $dir, OK"
3819             return 0
3820         else
3821             echo "found $res $flavor connections of $dir, not ready ($expect)"
3822             return 0
3823             sleep 4
3824         fi
3825     done
3826
3827     echo "Error checking $flavor of $dir: expect $expect, actual $res"
3828     return 1
3829 }
3830
3831 restore_to_default_flavor()
3832 {
3833     local proc="mgs.MGS.live.$FSNAME"
3834
3835     echo "restoring to default flavor..."
3836
3837     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
3838
3839     # remove all existing rules if any
3840     if [ $nrule -ne 0 ]; then
3841         echo "$nrule existing rules"
3842         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
3843             echo "remove rule: $rule"
3844             spec=`echo $rule | awk -F = '{print $1}'`
3845             do_facet mgs "$LCTL conf_param $spec="
3846         done
3847     fi
3848
3849     # verify no rules left
3850     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
3851     [ $nrule -ne 0 ] && error "still $nrule rules left"
3852
3853     # wait for default flavor to be applied
3854     # currently default flavor for all connections are 'null'
3855     wait_flavor all2all null
3856     echo "now at default flavor settings"
3857 }
3858
3859 set_flavor_all()
3860 {
3861     local flavor=${1:-null}
3862
3863     echo "setting all flavor to $flavor"
3864
3865     # FIXME need parameter to this fn
3866     # and remove global vars
3867     local cnt_all2all=$(calc_connection_cnt all2all)
3868
3869     local res=$(do_check_flavor all2all $flavor)
3870     if [ $res -eq $cnt_all2all ]; then
3871         echo "already have total $res $flavor connections"
3872         return
3873     fi
3874
3875     echo "found $res $flavor out of total $cnt_all2all connections"
3876     restore_to_default_flavor
3877
3878     [[ $flavor = null ]] && return 0
3879
3880     set_rule $FSNAME any any $flavor
3881     wait_flavor all2all $flavor
3882 }
3883
3884
3885 check_logdir() {
3886     local dir=$1
3887     # Checking for shared logdir
3888     if [ ! -d $dir ]; then
3889         # Not found. Create local logdir
3890         mkdir -p $dir
3891     else
3892         touch $dir/node.$(hostname).yml
3893     fi
3894     return 0
3895 }
3896
3897 check_write_access() {
3898     local dir=$1
3899     for node in $(nodes_list); do
3900         if [ ! -f "$dir/node.${node}.yml" ]; then
3901             # Logdir not accessible/writable from this node.
3902             return 1
3903         fi
3904     done
3905     return 0
3906 }
3907
3908 init_logging() {
3909     if [[ -n $YAML_LOG ]]; then
3910         return
3911     fi
3912     export YAML_LOG=${LOGDIR}/results.yml
3913     mkdir -p $LOGDIR
3914     init_clients_lists
3915
3916     do_rpc_nodes $(comma_list $(nodes_list)) check_logdir $LOGDIR
3917     if check_write_access $LOGDIR; then
3918         touch $LOGDIR/shared
3919         echo "Logging to shared log directory: $LOGDIR"
3920     else
3921         echo "Logging to local directory: $LOGDIR"
3922     fi
3923
3924     yml_nodes_file $LOGDIR
3925     yml_results_file >> $YAML_LOG
3926 }
3927
3928 log_test() {
3929     yml_log_test $1 >> $YAML_LOG
3930 }
3931
3932 log_sub_test() {
3933     yml_log_sub_test $@ >> $YAML_LOG
3934 }
3935
3936 run_llverdev()
3937 {
3938         local dev=$1
3939         local devname=$(basename $1)
3940         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
3941         size=$(($size / 1024 / 1024)) # Gb
3942
3943         local partial_arg=""
3944         # Run in partial (fast) mode if the size
3945         # of a partition > 10 GB
3946         [ $size -gt 10 ] && partial_arg="-p"
3947
3948         llverdev --force $partial_arg $dev
3949 }