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