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