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