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