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