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