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