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