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