Whamcloud - gitweb
5bde1882b0ee53e64f8b62e0fe54be6d7d9eb9d0
[fs/lustre-release.git] / lustre / tests / test-framework.sh
1 #!/bin/bash
2
3 trap 'print_summary && touch $TF_FAIL && \
4     echo "test-framework exiting on error"' ERR
5 set -e
6 #set -x
7
8 export LANG=en_US
9 export REFORMAT=${REFORMAT:-""}
10 export WRITECONF=${WRITECONF:-""}
11 export VERBOSE=${VERBOSE:-false}
12 export GSS=false
13 export GSS_KRB5=false
14 export GSS_PIPEFS=false
15 export IDENTITY_UPCALL=default
16 export QUOTA_AUTO=1
17 # specify environment variable containing batch job name for server statistics
18 export JOBID_VAR=${JOBID_VAR:-"procname_uid"}  # or "existing" or "disable"
19
20 # LOAD_LLOOP: LU-409: only load llite_lloop module if kernel < 2.6.32 or
21 #             LOAD_LLOOP is true. LOAD_LLOOP is false by default.
22 export LOAD_LLOOP=${LOAD_LLOOP:-false}
23
24 #export PDSH="pdsh -S -Rssh -w"
25 export MOUNT_CMD=${MOUNT_CMD:-"mount -t lustre"}
26 export UMOUNT=${UMOUNT:-"umount -d"}
27 # sles12 umount has a issue with -d option
28 [ -e /etc/SuSE-release ] && grep -w VERSION /etc/SuSE-release | grep -wq 12 && {
29         export UMOUNT="umount"
30 }
31
32 # function used by scripts run on remote nodes
33 LUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}
34 . $LUSTRE/tests/functions.sh
35 . $LUSTRE/tests/yaml.sh
36
37 export LD_LIBRARY_PATH=${LUSTRE}/utils:${LD_LIBRARY_PATH}
38
39 LUSTRE_TESTS_CFG_DIR=${LUSTRE_TESTS_CFG_DIR:-${LUSTRE}/tests/cfg}
40
41 EXCEPT_LIST_FILE=${EXCEPT_LIST_FILE:-${LUSTRE_TESTS_CFG_DIR}/tests-to-skip.sh}
42
43 if [ -f "$EXCEPT_LIST_FILE" ]; then
44     echo "Reading test skip list from $EXCEPT_LIST_FILE"
45     cat $EXCEPT_LIST_FILE
46     . $EXCEPT_LIST_FILE
47 fi
48
49 # check config files for options in decreasing order of preference
50 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/lustre.conf ] &&
51     MODPROBECONF=/etc/modprobe.d/lustre.conf
52 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/Lustre ] &&
53     MODPROBECONF=/etc/modprobe.d/Lustre
54 [ -z "$MODPROBECONF" -a -f /etc/modprobe.conf ] &&
55     MODPROBECONF=/etc/modprobe.conf
56
57 sanitize_parameters() {
58         for i in DIR DIR1 DIR2 MOUNT MOUNT1 MOUNT2
59         do
60                 local path=${!i}
61                 if [ -d "$path" ]; then
62                         eval export $i=$(echo $path | sed -r 's/\/+$//g')
63                 fi
64         done
65 }
66 assert_DIR () {
67         local failed=""
68         [[ $DIR/ = $MOUNT/* ]] ||
69                 { failed=1 && echo "DIR=$DIR not in $MOUNT. Aborting."; }
70         [[ $DIR1/ = $MOUNT1/* ]] ||
71                 { failed=1 && echo "DIR1=$DIR1 not in $MOUNT1. Aborting."; }
72         [[ $DIR2/ = $MOUNT2/* ]] ||
73                 { failed=1 && echo "DIR2=$DIR2 not in $MOUNT2. Aborting"; }
74
75         [ -n "$failed" ] && exit 99 || true
76 }
77
78 usage() {
79     echo "usage: $0 [-r] [-f cfgfile]"
80     echo "       -r: reformat"
81
82     exit
83 }
84
85 print_summary () {
86     trap 0
87         [ -z "$DEFAULT_SUITES"] && return 0
88     [ -n "$ONLY" ] && echo "WARNING: ONLY is set to $(echo $ONLY)"
89     local details
90     local form="%-13s %-17s %-9s %s %s\n"
91     printf "$form" "status" "script" "Total(sec)" "E(xcluded) S(low)"
92     echo "------------------------------------------------------------------------------------"
93     for O in $DEFAULT_SUITES; do
94         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
95         [ "${!O}" = "no" ] && continue || true
96         local o=$(echo $O  | tr "[:upper:]_" "[:lower:]-")
97         local log=${TMP}/${o}.log
98         if is_sanity_benchmark $o; then
99             log=${TMP}/sanity-benchmark.log
100         fi
101         local slow=
102         local skipped=
103         local total=
104         local status=Unfinished
105         if [ -f $log ]; then
106                 skipped=$(grep excluded $log | awk '{ printf " %s", $3 }' |
107                         sed 's/test_//g')
108                 slow=$(egrep "^PASS|^FAIL" $log | tr -d "("| sed s/s\)$//g |
109                         sort -nr -k 3  | head -n5 |  awk '{ print $2":"$3"s" }')
110                 total=$(grep duration $log | awk '{ print $2 }')
111                 if [ "${!O}" = "done" ]; then
112                         status=Done
113                 fi
114                 if $DDETAILS; then
115                         local durations=$(egrep "^PASS|^FAIL" $log |
116                                 tr -d "("| sed s/s\)$//g |
117                                 awk '{ print $2":"$3"|" }')
118                         details=$(printf "%s\n%s %s %s\n" "$details" \
119                                 "DDETAILS" "$O" "$(echo $durations)")
120                 fi
121         fi
122         printf "$form" $status "$O" "${total}" "E=$skipped"
123         printf "$form" "-" "-" "-" "S=$(echo $slow)"
124     done
125
126     for O in $DEFAULT_SUITES; do
127         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
128         if [ "${!O}" = "no" ]; then
129             printf "$form" "Skipped" "$O" ""
130         fi
131     done
132
133     # print the detailed tests durations if DDETAILS=true
134     if $DDETAILS; then
135         echo "$details"
136     fi
137 }
138
139 init_test_env() {
140         export LUSTRE=$(absolute_path $LUSTRE)
141         export TESTSUITE=$(basename $0 .sh)
142         export TEST_FAILED=false
143         export FAIL_ON_SKIP_ENV=${FAIL_ON_SKIP_ENV:-false}
144         export RPC_MODE=${RPC_MODE:-false}
145
146     export MKE2FS=$MKE2FS
147     if [ -z "$MKE2FS" ]; then
148         if which mkfs.ldiskfs >/dev/null 2>&1; then
149             export MKE2FS=mkfs.ldiskfs
150         else
151             export MKE2FS=mke2fs
152         fi
153     fi
154
155     export DEBUGFS=$DEBUGFS
156     if [ -z "$DEBUGFS" ]; then
157         if which debugfs.ldiskfs >/dev/null 2>&1; then
158             export DEBUGFS=debugfs.ldiskfs
159         else
160             export DEBUGFS=debugfs
161         fi
162     fi
163
164     export TUNE2FS=$TUNE2FS
165     if [ -z "$TUNE2FS" ]; then
166         if which tunefs.ldiskfs >/dev/null 2>&1; then
167             export TUNE2FS=tunefs.ldiskfs
168         else
169             export TUNE2FS=tune2fs
170         fi
171     fi
172
173     export E2LABEL=$E2LABEL
174     if [ -z "$E2LABEL" ]; then
175         if which label.ldiskfs >/dev/null 2>&1; then
176             export E2LABEL=label.ldiskfs
177         else
178             export E2LABEL=e2label
179         fi
180     fi
181
182     export DUMPE2FS=$DUMPE2FS
183     if [ -z "$DUMPE2FS" ]; then
184         if which dumpfs.ldiskfs >/dev/null 2>&1; then
185             export DUMPE2FS=dumpfs.ldiskfs
186         else
187             export DUMPE2FS=dumpe2fs
188         fi
189     fi
190
191     export E2FSCK=$E2FSCK
192     if [ -z "$E2FSCK" ]; then
193         if which fsck.ldiskfs >/dev/null 2>&1; then
194             export E2FSCK=fsck.ldiskfs
195         else
196             export E2FSCK=e2fsck
197         fi
198     fi
199
200         export RESIZE2FS=$RESIZE2FS
201         if [ -z "$RESIZE2FS" ]; then
202                 if which resizefs.ldiskfs >/dev/null 2>&1; then
203                         export RESIZE2FS=resizefs.ldiskfs
204                 else
205                         export RESIZE2FS=resize2fs
206                 fi
207         fi
208
209         export LFSCK_ALWAYS=${LFSCK_ALWAYS:-"no"} # check fs after test suite
210         export FSCK_MAX_ERR=4   # File system errors left uncorrected
211
212         export ZFS=${ZFS:-zfs}
213         export ZPOOL=${ZPOOL:-zpool}
214         export ZDB=${ZDB:-zdb}
215         export PARTPROBE=${PARTPROBE:-partprobe}
216
217     #[ -d /r ] && export ROOT=${ROOT:-/r}
218     export TMP=${TMP:-$ROOT/tmp}
219     export TESTSUITELOG=${TMP}/${TESTSUITE}.log
220     export LOGDIR=${LOGDIR:-${TMP}/test_logs/$(date +%s)}
221     export TESTLOG_PREFIX=$LOGDIR/$TESTSUITE
222
223     export HOSTNAME=${HOSTNAME:-$(hostname -s)}
224     if ! echo $PATH | grep -q $LUSTRE/utils; then
225         export PATH=$LUSTRE/utils:$PATH
226     fi
227     if ! echo $PATH | grep -q $LUSTRE/utils/gss; then
228         export PATH=$LUSTRE/utils/gss:$PATH
229     fi
230     if ! echo $PATH | grep -q $LUSTRE/tests; then
231         export PATH=$LUSTRE/tests:$PATH
232     fi
233     if ! echo $PATH | grep -q $LUSTRE/../lustre-iokit/sgpdd-survey; then
234         export PATH=$LUSTRE/../lustre-iokit/sgpdd-survey:$PATH
235     fi
236     export LST=${LST:-"$LUSTRE/../lnet/utils/lst"}
237     [ ! -f "$LST" ] && export LST=$(which lst)
238     export SGPDDSURVEY=${SGPDDSURVEY:-"$LUSTRE/../lustre-iokit/sgpdd-survey/sgpdd-survey")}
239     [ ! -f "$SGPDDSURVEY" ] && export SGPDDSURVEY=$(which sgpdd-survey)
240         export MCREATE=${MCREATE:-mcreate}
241     # Ubuntu, at least, has a truncate command in /usr/bin
242     # so fully path our truncate command.
243     export TRUNCATE=${TRUNCATE:-$LUSTRE/tests/truncate}
244         export FSX=${FSX:-$LUSTRE/tests/fsx}
245     export MDSRATE=${MDSRATE:-"$LUSTRE/tests/mpi/mdsrate"}
246     [ ! -f "$MDSRATE" ] && export MDSRATE=$(which mdsrate 2> /dev/null)
247     if ! echo $PATH | grep -q $LUSTRE/tests/racer; then
248         export PATH=$LUSTRE/tests/racer:$PATH:
249     fi
250     if ! echo $PATH | grep -q $LUSTRE/tests/mpi; then
251         export PATH=$LUSTRE/tests/mpi:$PATH
252     fi
253     export RSYNC_RSH=${RSYNC_RSH:-rsh}
254
255     export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
256     [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
257     export LFS=${LFS:-"$LUSTRE/utils/lfs"}
258     [ ! -f "$LFS" ] && export LFS=$(which lfs)
259     SETSTRIPE=${SETSTRIPE:-"$LFS setstripe"}
260     GETSTRIPE=${GETSTRIPE:-"$LFS getstripe"}
261
262     export L_GETIDENTITY=${L_GETIDENTITY:-"$LUSTRE/utils/l_getidentity"}
263     if [ ! -f "$L_GETIDENTITY" ]; then
264         if `which l_getidentity > /dev/null 2>&1`; then
265             export L_GETIDENTITY=$(which l_getidentity)
266         else
267             export L_GETIDENTITY=NONE
268         fi
269     fi
270     export LL_DECODE_FILTER_FID=${LL_DECODE_FILTER_FID:-"$LUSTRE/utils/ll_decode_filter_fid"}
271     [ ! -f "$LL_DECODE_FILTER_FID" ] && export LL_DECODE_FILTER_FID="ll_decode_filter_fid"
272     export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
273     [ ! -f "$MKFS" ] && export MKFS="mkfs.lustre"
274     export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
275     [ ! -f "$TUNEFS" ] && export TUNEFS="tunefs.lustre"
276     export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
277     export LUSTRE_RMMOD=${LUSTRE_RMMOD:-$LUSTRE/scripts/lustre_rmmod}
278     [ ! -f "$LUSTRE_RMMOD" ] &&
279         export LUSTRE_RMMOD=$(which lustre_rmmod 2> /dev/null)
280     export LFS_MIGRATE=${LFS_MIGRATE:-$LUSTRE/scripts/lfs_migrate}
281     [ ! -f "$LFS_MIGRATE" ] &&
282         export LFS_MIGRATE=$(which lfs_migrate 2> /dev/null)
283     export LR_READER=${LR_READER:-"$LUSTRE/utils/lr_reader"}
284     [ ! -f "$LR_READER" ] && export LR_READER=$(which lr_reader 2> /dev/null)
285     [ -z "$LR_READER" ] && export LR_READER="/usr/sbin/lr_reader"
286     export NAME=${NAME:-local}
287     export LGSSD=${LGSSD:-"$LUSTRE/utils/gss/lgssd"}
288     [ "$GSS_PIPEFS" = "true" ] && [ ! -f "$LGSSD" ] && \
289         export LGSSD=$(which lgssd)
290     export LSVCGSSD=${LSVCGSSD:-"$LUSTRE/utils/gss/lsvcgssd"}
291     [ ! -f "$LSVCGSSD" ] && export LSVCGSSD=$(which lsvcgssd 2> /dev/null)
292     export KRB5DIR=${KRB5DIR:-"/usr/kerberos"}
293     export DIR2
294     export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
295     export AT_MAX_PATH
296
297     if [ "$ACCEPTOR_PORT" ]; then
298         export PORT_OPT="--port $ACCEPTOR_PORT"
299     fi
300
301     case "x$SEC" in
302         xkrb5*)
303             echo "Using GSS/krb5 ptlrpc security flavor"
304             which lgss_keyring > /dev/null 2>&1 || \
305                 error_exit "built with gss disabled! SEC=$SEC"
306             GSS=true
307             GSS_KRB5=true
308             ;;
309     esac
310
311     case "x$IDUP" in
312         xtrue)
313             IDENTITY_UPCALL=true
314             ;;
315         xfalse)
316             IDENTITY_UPCALL=false
317             ;;
318     esac
319
320     export LOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}
321
322     # Paths on remote nodes, if different
323     export RLUSTRE=${RLUSTRE:-$LUSTRE}
324     export RPWD=${RPWD:-$PWD}
325     export I_MOUNTED=${I_MOUNTED:-"no"}
326         if [ ! -f /lib/modules/$(uname -r)/kernel/fs/lustre/mdt.ko -a \
327              ! -f /lib/modules/$(uname -r)/updates/kernel/fs/lustre/mdt.ko -a \
328              ! -f /lib/modules/$(uname -r)/extra/kernel/fs/lustre/mdt.ko -a \
329              ! -f $LUSTRE/mdt/mdt.ko ]; then
330             export CLIENTMODSONLY=yes
331         fi
332
333         export SHUTDOWN_ATTEMPTS=${SHUTDOWN_ATTEMPTS:-3}
334         export OSD_TRACK_DECLARES_LBUG=${OSD_TRACK_DECLARES_LBUG:-"yes"}
335
336         # command line
337
338         while getopts "rvwf:" opt $*; do
339                 case $opt in
340                         f) CONFIG=$OPTARG;;
341                         r) REFORMAT=yes;;
342                         v) VERBOSE=true;;
343                         w) WRITECONF=writeconf;;
344                         \?) usage;;
345                 esac
346         done
347
348         shift $((OPTIND - 1))
349         ONLY=${ONLY:-$*}
350
351         # print the durations of each test if "true"
352         DDETAILS=${DDETAILS:-false}
353         [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
354         if ! $RPC_MODE; then
355                 rm -f $TMP/*active
356         fi
357
358         export TF_FAIL=${TF_FAIL:-$TMP/tf.fail}
359 }
360
361 check_cpt_number() {
362         local facet=$1
363         local ncpts
364
365         ncpts=$(do_facet $facet "lctl get_param -n " \
366                 "cpu_partition_table 2>/dev/null| wc -l" || echo 1)
367
368         if [ $ncpts -eq 0 ]; then
369                 echo "1"
370         else
371                 echo $ncpts
372         fi
373 }
374
375 # Return a numeric version code based on a version string.  The version
376 # code is useful for comparison two version strings to see which is newer.
377 version_code() {
378         # split arguments like "1.8.6-wc3" into "1", "8", "6", "wc3"
379         eval set -- $(tr "[:punct:]" " " <<< $*)
380
381         echo -n "$((($1 << 16) | ($2 << 8) | $3))"
382 }
383
384 export LINUX_VERSION=$(uname -r | sed -e "s/\([0-9]*\.[0-9]*\.[0-9]*\).*/\1/")
385 export LINUX_VERSION_CODE=$(version_code ${LINUX_VERSION//\./ })
386
387 # Report the Lustre build version string (e.g. 1.8.7.3 or 2.4.1).
388 #
389 # usage: lustre_build_version
390 #
391 # All Lustre versions support "lctl get_param" to report the version of the
392 # code running in the kernel (what our tests are interested in), but it
393 # doesn't work without modules loaded.  If that fails, use "lctl version"
394 # instead, which is easy to parse and works without the kernel modules,
395 # but was only added in 2.6.50.  If that also fails, fall back to calling
396 # "lctl lustre_build_version" which prints either (or both) the userspace
397 # and kernel build versions, but is deprecated and should eventually be
398 # removed.
399 #
400 # output: prints version string to stdout in dotted-decimal format
401 lustre_build_version() {
402         local facet=${1:-client}
403
404         # lustre: 2.6.52
405         # kernel: patchless_client
406         # build: v2_6_92_0-gadb3ee4-2.6.32-431.29.2.el6_lustre.x86_64
407         local VER=$(do_facet $facet $LCTL get_param -n version 2> /dev/null |
408                     awk '/lustre: / { print $2 }')
409         # lctl 2.6.50
410         [ -z "$VER" ] && VER=$(do_facet $facet $LCTL --version 2>/dev/null |
411                                awk '{ print $2 }')
412         # Lustre version: 2.5.3-gfcfd782-CHANGED-2.6.32.26-175.fc12.x86_64
413         # lctl   version: 2.5.3-gfcfd782-CHANGED-2.6.32.26-175.fc12.x86_64
414         [ -z "$VER" ] && VER=$(do_facet $facet $LCTL lustre_build_version |
415                                awk '/version:/ { print $3; exit; }')
416         sed -e 's/^v//' -e 's/-.*//' -e 's/_/./g' <<<$VER
417 }
418
419 # Report the Lustre numeric build version code for the supplied facet.
420 lustre_version_code() {
421         version_code $(lustre_build_version $1)
422 }
423
424 module_loaded () {
425         /sbin/lsmod | grep -q "^\<$1\>"
426 }
427
428 # Load a module on the system where this is running.
429 #
430 # usage: load_module module_name [module arguments for insmod/modprobe]
431 #
432 # If module arguments are not given but MODOPTS_<MODULE> is set, then its value
433 # will be used as the arguments.  Otherwise arguments will be obtained from
434 # /etc/modprobe.conf, from /etc/modprobe.d/Lustre, or else none will be used.
435 #
436 load_module() {
437     local optvar
438     EXT=".ko"
439     module=$1
440     shift
441     BASE=$(basename $module $EXT)
442
443     module_loaded ${BASE} && return
444
445     # If no module arguments were passed, get them from $MODOPTS_<MODULE>,
446     # else from modprobe.conf
447     if [ $# -eq 0 ]; then
448         # $MODOPTS_<MODULE>; we could use associative arrays, but that's not in
449         # Bash until 4.x, so we resort to eval.
450         optvar="MODOPTS_$(basename $module | tr a-z A-Z)"
451         eval set -- \$$optvar
452         if [ $# -eq 0 -a -n "$MODPROBECONF" ]; then
453                 # Nothing in $MODOPTS_<MODULE>; try modprobe.conf
454                 local opt
455                 opt=$(awk -v var="^options $BASE" '$0 ~ var \
456                         {gsub("'"options $BASE"'",""); print}' $MODPROBECONF)
457                 set -- $(echo -n $opt)
458
459                 # Ensure we have accept=all for lnet
460                 if [ $(basename $module) = lnet ]; then
461                         # OK, this is a bit wordy...
462                         local arg accept_all_present=false
463
464                         for arg in "$@"; do
465                                 [ "$arg" = accept=all ] && \
466                                         accept_all_present=true
467                         done
468                         $accept_all_present || set -- "$@" accept=all
469                 fi
470                 export $optvar="$*"
471         fi
472     fi
473
474     [ $# -gt 0 ] && echo "${module} options: '$*'"
475
476         # Note that insmod will ignore anything in modprobe.conf, which is why
477         # we're passing options on the command-line.
478         if [[ "$BASE" == "lnet_selftest" ]] &&
479                 [[ -f ${LUSTRE}/../lnet/selftest/${module}${EXT} ]]; then
480                 insmod ${LUSTRE}/../lnet/selftest/${module}${EXT}
481         elif [[ -f ${LUSTRE}/${module}${EXT} ]]; then
482                 [[ "$BASE" != "ptlrpc_gss" ]] || modprobe sunrpc
483                 insmod ${LUSTRE}/${module}${EXT} "$@"
484         else
485                 # must be testing a "make install" or "rpm" installation
486                 # note failed to load ptlrpc_gss is considered not fatal
487                 if [[ "$BASE" == "ptlrpc_gss" ]]; then
488                         modprobe $BASE "$@" 2>/dev/null ||
489                                 echo "gss/krb5 is not supported"
490                 else
491                         modprobe $BASE "$@"
492                 fi
493         fi
494 }
495
496 llite_lloop_enabled() {
497     local n1=$(uname -r | cut -d. -f1)
498     local n2=$(uname -r | cut -d. -f2)
499     local n3=$(uname -r | cut -d- -f1 | cut -d. -f3)
500
501     # load the llite_lloop module for < 2.6.32 kernels
502     if [[ $n1 -lt 2 ]] || [[ $n1 -eq 2 && $n2 -lt 6 ]] || \
503        [[ $n1 -eq 2 && $n2 -eq 6 && $n3 -lt 32 ]] || \
504         $LOAD_LLOOP; then
505         return 0
506     fi
507     return 1
508 }
509
510 load_modules_local() {
511         if [ -n "$MODPROBE" ]; then
512                 # use modprobe
513                 echo "Using modprobe to load modules"
514                 return 0
515         fi
516
517         echo Loading modules from $LUSTRE
518
519         local ncpus
520
521         if [ -f /sys/devices/system/cpu/online ]; then
522                 ncpus=$(($(cut -d "-" -f 2 /sys/devices/system/cpu/online) + 1))
523                 echo "detected $ncpus online CPUs by sysfs"
524         else
525                 ncpus=$(getconf _NPROCESSORS_CONF 2>/dev/null)
526                 local rc=$?
527                 if [ $rc -eq 0 ]; then
528                         echo "detected $ncpus online CPUs by getconf"
529                 else
530                         echo "Can't detect number of CPUs"
531                         ncpus=1
532                 fi
533         fi
534
535         # if there is only one CPU core, libcfs can only create one partition
536         # if there is more than 4 CPU cores, libcfs should create multiple CPU
537         # partitions. So we just force libcfs to create 2 partitions for
538         # system with 2 or 4 cores
539         if [ $ncpus -le 4 ] && [ $ncpus -gt 1 ]; then
540                 # force to enable multiple CPU partitions
541                 echo "Force libcfs to create 2 CPU partitions"
542                 MODOPTS_LIBCFS="cpu_npartitions=2 $MODOPTS_LIBCFS"
543         else
544                 echo "libcfs will create CPU partition based on online CPUs"
545         fi
546
547         load_module ../libcfs/libcfs/libcfs
548
549     [ "$PTLDEBUG" ] && lctl set_param debug="$PTLDEBUG"
550     [ "$SUBSYSTEM" ] && lctl set_param subsystem_debug="${SUBSYSTEM# }"
551     load_module ../lnet/lnet/lnet
552         case $NETTYPE in
553         o2ib)
554                 LNETLND="o2iblnd/ko2iblnd"
555                 ;;
556         *)
557                 ;;
558         esac
559     LNETLND=${LNETLND:-"socklnd/ksocklnd"}
560     load_module ../lnet/klnds/$LNETLND
561     load_module obdclass/obdclass
562     load_module ptlrpc/ptlrpc
563     load_module ptlrpc/gss/ptlrpc_gss
564     load_module fld/fld
565     load_module fid/fid
566     load_module lmv/lmv
567     load_module mdc/mdc
568     load_module osc/osc
569     load_module lov/lov
570     load_module mgc/mgc
571     load_module obdecho/obdecho
572         if ! client_only; then
573                 SYMLIST=/proc/kallsyms
574                 grep -q crc16 $SYMLIST ||
575                         { modprobe crc16 2>/dev/null || true; }
576                 grep -q -w jbd2 $SYMLIST ||
577                         { modprobe jbd2 2>/dev/null || true; }
578                 load_module lfsck/lfsck
579                 [ "$LQUOTA" != "no" ] &&
580                         load_module quota/lquota $LQUOTAOPTS
581                 if [[ $(node_fstypes $HOSTNAME) == *zfs* ]]; then
582                         modprobe zfs
583                         load_module osd-zfs/osd_zfs
584                 fi
585                 if [[ $(node_fstypes $HOSTNAME) == *ldiskfs* ]]; then
586                         grep -q exportfs_decode_fh $SYMLIST ||
587                                 { modprobe exportfs 2> /dev/null || true; }
588                         grep -q -w mbcache $SYMLIST ||
589                                 { modprobe mbcache 2>/dev/null || true; }
590                         load_module ../ldiskfs/ldiskfs
591                         load_module osd-ldiskfs/osd_ldiskfs
592                 fi
593                 load_module mgs/mgs
594                 load_module mdd/mdd
595                 load_module mdt/mdt
596                 load_module ost/ost
597                 load_module lod/lod
598                 load_module osp/osp
599                 load_module ofd/ofd
600                 load_module osp/osp
601         fi
602
603         load_module llite/lustre
604         llite_lloop_enabled && load_module llite/llite_lloop
605         [ -d /r ] && OGDB=${OGDB:-"/r/tmp"}
606         OGDB=${OGDB:-$TMP}
607         rm -f $OGDB/ogdb-$HOSTNAME
608         $LCTL modules > $OGDB/ogdb-$HOSTNAME
609
610         # 'mount' doesn't look in $PATH, just sbin
611         local mount_lustre=$LUSTRE/utils/mount.lustre
612         if [ -f $mount_lustre ]; then
613                 local sbin_mount=$(readlink -f /sbin)/mount.lustre
614                 if grep -qw "$sbin_mount" /proc/mounts; then
615                         cmp -s $mount_lustre $sbin_mount || umount $sbin_mount
616                 fi
617                 if ! grep -qw "$sbin_mount" /proc/mounts; then
618                         [ ! -f "$sbin_mount" ] && touch "$sbin_mount"
619                         if [ ! -s "$sbin_mount" -a -w "$sbin_mount" ]; then
620                                 cat <<- EOF > "$sbin_mount"
621                                 #!/bin/sh
622                                 #STUB MARK
623                                 echo "This $sbin_mount just a mountpoint." 1>&2
624                                 echo "It is never supposed to be run." 1>&2
625                                 logger -p emerg -- "using stub $sbin_mount $@"
626                                 exit 1
627                                 EOF
628                                 chmod a+x $sbin_mount
629                         fi
630                         mount --bind $mount_lustre $sbin_mount ||
631                                 error "can't bind $mount_lustre to $sbin_mount"
632                 fi
633         fi
634 }
635
636 load_modules () {
637         load_modules_local
638         # bug 19124
639         # load modules on remote nodes optionally
640         # lustre-tests have to be installed on these nodes
641         if $LOAD_MODULES_REMOTE; then
642                 local list=$(comma_list $(remote_nodes_list))
643                 if [ -n "$list" ]; then
644                         echo "loading modules on: '$list'"
645                         do_rpc_nodes "$list" load_modules_local
646                 fi
647         fi
648 }
649
650 check_mem_leak () {
651     LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
652     LEAK_PORTALS=$(dmesg | tail -n 20 | grep "Portals memory leaked" || true)
653     if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
654         echo "$LEAK_LUSTRE" 1>&2
655         echo "$LEAK_PORTALS" 1>&2
656         mv $TMP/debug $TMP/debug-leak.`date +%s` || true
657         echo "Memory leaks detected"
658         [ -n "$IGNORE_LEAK" ] && { echo "ignoring leaks" && return 0; } || true
659         return 1
660     fi
661 }
662
663 unload_modules() {
664         wait_exit_ST client # bug 12845
665
666         $LUSTRE_RMMOD ldiskfs || return 2
667
668         if $LOAD_MODULES_REMOTE; then
669                 local list=$(comma_list $(remote_nodes_list))
670                 if [ -n "$list" ]; then
671                         echo "unloading modules on: '$list'"
672                         do_rpc_nodes "$list" $LUSTRE_RMMOD ldiskfs
673                         do_rpc_nodes "$list" check_mem_leak
674                 fi
675         fi
676
677         local sbin_mount=$(readlink -f /sbin)/mount.lustre
678         if grep -qe "$sbin_mount " /proc/mounts; then
679                 umount $sbin_mount || true
680                 [ -s $sbin_mount ] && ! grep -q "STUB MARK" $sbin_mount ||
681                         rm -f $sbin_mount
682         fi
683
684         check_mem_leak || return 254
685
686         echo "modules unloaded."
687         return 0
688 }
689
690 fs_log_size() {
691         local facet=${1:-$SINGLEMDS}
692         local fstype=$(facet_fstype $facet)
693         local size=0
694         case $fstype in
695                 ldiskfs) size=50;; # largest seen is 44, leave some headroom
696                 zfs)     size=400;; # largest seen is 384
697         esac
698
699         echo -n $size
700 }
701
702 check_gss_daemon_nodes() {
703     local list=$1
704     dname=$2
705
706     do_nodesv $list "num=\\\$(ps -o cmd -C $dname | grep $dname | wc -l);
707 if [ \\\"\\\$num\\\" -ne 1 ]; then
708     echo \\\$num instance of $dname;
709     exit 1;
710 fi; "
711 }
712
713 check_gss_daemon_facet() {
714     facet=$1
715     dname=$2
716
717     num=`do_facet $facet ps -o cmd -C $dname | grep $dname | wc -l`
718     if [ $num -ne 1 ]; then
719         echo "$num instance of $dname on $facet"
720         return 1
721     fi
722     return 0
723 }
724
725 send_sigint() {
726     local list=$1
727     shift
728     echo Stopping $@ on $list
729     do_nodes $list "killall -2 $@ 2>/dev/null || true"
730 }
731
732 # start gss daemons on all nodes, or
733 # "daemon" on "list" if set
734 start_gss_daemons() {
735     local list=$1
736     local daemon=$2
737
738     if [ "$list" ] && [ "$daemon" ] ; then
739         echo "Starting gss daemon on nodes: $list"
740         do_nodes $list "$daemon" || return 8
741         return 0
742     fi
743
744     local list=$(comma_list $(mdts_nodes))
745     echo "Starting gss daemon on mds: $list"
746     do_nodes $list "$LSVCGSSD -v" || return 1
747     if $GSS_PIPEFS; then
748         do_nodes $list "$LGSSD -v" || return 2
749     fi
750
751     list=$(comma_list $(osts_nodes))
752     echo "Starting gss daemon on ost: $list"
753     do_nodes $list "$LSVCGSSD -v" || return 3
754     # starting on clients
755
756     local clients=${CLIENTS:-`hostname`}
757     if $GSS_PIPEFS; then
758         echo "Starting $LGSSD on clients $clients "
759         do_nodes $clients  "$LGSSD -v" || return 4
760     fi
761
762     # wait daemons entering "stable" status
763     sleep 5
764
765     #
766     # check daemons are running
767     #
768     list=$(comma_list $(mdts_nodes) $(osts_nodes))
769     check_gss_daemon_nodes $list lsvcgssd || return 5
770     if $GSS_PIPEFS; then
771         list=$(comma_list $(mdts_nodes))
772         check_gss_daemon_nodes $list lgssd || return 6
773     fi
774     if $GSS_PIPEFS; then
775         check_gss_daemon_nodes $clients lgssd || return 7
776     fi
777 }
778
779 stop_gss_daemons() {
780     local list=$(comma_list $(mdts_nodes))
781
782     send_sigint $list lsvcgssd lgssd
783
784     list=$(comma_list $(osts_nodes))
785     send_sigint $list lsvcgssd
786
787     list=${CLIENTS:-`hostname`}
788     send_sigint $list lgssd
789 }
790
791 init_gss() {
792     if $GSS; then
793         if ! module_loaded ptlrpc_gss; then
794             load_module ptlrpc/gss/ptlrpc_gss
795             module_loaded ptlrpc_gss ||
796                 error_exit "init_gss : GSS=$GSS, but gss/krb5 is not supported!"
797         fi
798         if $GSS_KRB5; then
799                 start_gss_daemons || error_exit "start gss daemon failed! rc=$?"
800         fi
801
802         if [ -n "$LGSS_KEYRING_DEBUG" ]; then
803                 lctl set_param -n \
804                     sptlrpc.gss.lgss_keyring.debug_level=$LGSS_KEYRING_DEBUG
805         fi
806     fi
807 }
808
809 cleanup_gss() {
810     if $GSS; then
811         stop_gss_daemons
812         # maybe cleanup credential cache?
813     fi
814 }
815
816 facet_svc() {
817         local facet=$1
818         local var=${facet}_svc
819
820         echo -n ${!var}
821 }
822
823 facet_type() {
824         local facet=$1
825
826         echo -n $facet | sed -e 's/^fs[0-9]\+//' -e 's/[0-9_]\+//' |
827                 tr '[:lower:]' '[:upper:]'
828 }
829
830 facet_number() {
831         local facet=$1
832
833         if [ $facet == mgs ] || [ $facet == client ]; then
834                 return 1
835         fi
836
837         echo -n $facet | sed -e 's/^fs[0-9]\+//' | sed -e 's/^[a-z]\+//'
838 }
839
840 facet_fstype() {
841         local facet=$1
842         local var
843
844         var=${facet}_FSTYPE
845         if [ -n "${!var}" ]; then
846                 echo -n ${!var}
847                 return
848         fi
849
850         var=$(facet_type $facet)FSTYPE
851         if [ -n "${!var}" ]; then
852                 echo -n ${!var}
853                 return
854         fi
855
856         if [ -n "$FSTYPE" ]; then
857                 echo -n $FSTYPE
858                 return
859         fi
860
861         if [[ $facet == mgs ]] && combined_mgs_mds; then
862                 facet_fstype mds1
863                 return
864         fi
865
866         return 1
867 }
868
869 node_fstypes() {
870         local node=$1
871         local fstypes
872         local fstype
873         local facets=$(get_facets)
874         local facet
875
876         for facet in ${facets//,/ }; do
877                 if [ $node == $(facet_host $facet) ] ||
878                    [ $node == "$(facet_failover_host $facet)" ]; then
879                         fstype=$(facet_fstype $facet)
880                         if [[ $fstypes != *$fstype* ]]; then
881                                 fstypes+="${fstypes:+,}$fstype"
882                         fi
883                 fi
884         done
885         echo -n $fstypes
886 }
887
888 facet_index() {
889         local facet=$1
890         local num=$(facet_number $facet)
891         local index
892
893         if [[ $(facet_type $facet) = OST ]]; then
894                 index=OSTINDEX${num}
895                 if [[ -n "${!index}" ]]; then
896                         echo -n ${!index}
897                         return
898                 fi
899
900                 index=${OST_INDICES[num - 1]}
901         fi
902
903         [[ -n "$index" ]] || index=$((num - 1))
904         echo -n $index
905 }
906
907 devicelabel() {
908         local facet=$1
909         local dev=$2
910         local label
911         local fstype=$(facet_fstype $facet)
912
913         case $fstype in
914         ldiskfs)
915                 label=$(do_facet ${facet} "$E2LABEL ${dev} 2>/dev/null");;
916         zfs)
917                 label=$(do_facet ${facet} "$ZFS get -H -o value lustre:svname \
918                                            ${dev} 2>/dev/null");;
919         *)
920                 error "unknown fstype!";;
921         esac
922
923         echo -n $label
924 }
925
926 mdsdevlabel() {
927         local num=$1
928         local device=$(mdsdevname $num)
929         local label=$(devicelabel mds$num ${device} | grep -v "CMD: ")
930         echo -n $label
931 }
932
933 ostdevlabel() {
934         local num=$1
935         local device=$(ostdevname $num)
936         local label=$(devicelabel ost$num ${device} | grep -v "CMD: ")
937         echo -n $label
938 }
939
940 #
941 # Get the device of a facet.
942 #
943 facet_device() {
944         local facet=$1
945         local device
946
947         case $facet in
948                 mgs) device=$(mgsdevname) ;;
949                 mds*) device=$(mdsdevname $(facet_number $facet)) ;;
950                 ost*) device=$(ostdevname $(facet_number $facet)) ;;
951                 fs2mds) device=$(mdsdevname 1_2) ;;
952                 fs2ost) device=$(ostdevname 1_2) ;;
953                 fs3ost) device=$(ostdevname 2_2) ;;
954                 *) ;;
955         esac
956
957         echo -n $device
958 }
959
960 #
961 # Get the virtual device of a facet.
962 #
963 facet_vdevice() {
964         local facet=$1
965         local device
966
967         case $facet in
968                 mgs) device=$(mgsvdevname) ;;
969                 mds*) device=$(mdsvdevname $(facet_number $facet)) ;;
970                 ost*) device=$(ostvdevname $(facet_number $facet)) ;;
971                 fs2mds) device=$(mdsvdevname 1_2) ;;
972                 fs2ost) device=$(ostvdevname 1_2) ;;
973                 fs3ost) device=$(ostvdevname 2_2) ;;
974                 *) ;;
975         esac
976
977         echo -n $device
978 }
979
980 #
981 # Re-read the partition table on failover partner host.
982 # After a ZFS storage pool is created on a shared device, the partition table
983 # on the device may change. However, the operating system on the failover
984 # host may not notice the change automatically. Without the up-to-date partition
985 # block devices, 'zpool import ..' cannot find the labels, whose positions are
986 # relative to partition rather than disk beginnings.
987 #
988 # This function performs partprobe on the failover host to make it re-read the
989 # partition table.
990 #
991 refresh_partition_table() {
992         local facet=$1
993         local device=$2
994         local host
995
996         host=$(facet_passive_host $facet)
997         if [[ -n "$host" ]]; then
998                 do_node $host "$PARTPROBE $device"
999         fi
1000 }
1001
1002 #
1003 # Get ZFS storage pool name.
1004 #
1005 zpool_name() {
1006         local facet=$1
1007         local device
1008         local poolname
1009
1010         device=$(facet_device $facet)
1011         # poolname is string before "/"
1012         poolname="${device%%/*}"
1013
1014         echo -n $poolname
1015 }
1016
1017 #
1018 # Create ZFS storage pool.
1019 #
1020 create_zpool() {
1021         local facet=$1
1022         local poolname=$2
1023         local vdev=$3
1024         shift 3
1025         local opts=${@:-"-o cachefile=none"}
1026
1027         do_facet $facet "$ZPOOL list -H $poolname >/dev/null 2>&1 ||
1028                 $ZPOOL create -f $opts $poolname $vdev"
1029 }
1030
1031 #
1032 # Create ZFS file system.
1033 #
1034 create_zfs() {
1035         local facet=$1
1036         local dataset=$2
1037         shift 2
1038         local opts=${@:-"-o mountpoint=legacy"}
1039
1040         do_facet $facet "$ZFS list -H $dataset >/dev/null 2>&1 ||
1041                 $ZFS create $opts $dataset"
1042 }
1043
1044 #
1045 # Export ZFS storage pool.
1046 # Before exporting the pool, all datasets within the pool should be unmounted.
1047 #
1048 export_zpool() {
1049         local facet=$1
1050         shift
1051         local opts="$@"
1052         local poolname
1053
1054         poolname=$(zpool_name $facet)
1055
1056         if [[ -n "$poolname" ]]; then
1057                 do_facet $facet "! $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1058                         grep -q ^$poolname/ /proc/mounts ||
1059                         $ZPOOL export $opts $poolname"
1060         fi
1061 }
1062
1063 #
1064 # Destroy ZFS storage pool.
1065 # Destroy the given pool and free up any devices for other use. This command
1066 # tries to unmount any active datasets before destroying the pool.
1067 # -f    Force any active datasets contained within the pool to be unmounted.
1068 #
1069 destroy_zpool() {
1070         local facet=$1
1071         local poolname=${2:-$(zpool_name $facet)}
1072
1073         if [[ -n "$poolname" ]]; then
1074                 do_facet $facet "! $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1075                         $ZPOOL destroy -f $poolname"
1076         fi
1077 }
1078
1079 #
1080 # Import ZFS storage pool.
1081 # Force importing, even if the pool appears to be potentially active.
1082 #
1083 import_zpool() {
1084         local facet=$1
1085         shift
1086         local opts=${@:-"-o cachefile=none"}
1087         local poolname
1088
1089         poolname=$(zpool_name $facet)
1090
1091         if [[ -n "$poolname" ]]; then
1092                 opts+=" -d $(dirname $(facet_vdevice $facet))"
1093                 do_facet $facet "$ZPOOL list -H $poolname >/dev/null 2>&1 ||
1094                         $ZPOOL import -f $opts $poolname"
1095         fi
1096 }
1097
1098 #
1099 # Set the "cachefile=none" property on ZFS storage pool so that the pool
1100 # is not automatically imported on system startup.
1101 #
1102 # In a failover environment, this will provide resource level fencing which
1103 # will ensure that the same ZFS storage pool will not be imported concurrently
1104 # on different nodes.
1105 #
1106 disable_zpool_cache() {
1107         local facet=$1
1108         local poolname
1109
1110         poolname=$(zpool_name $facet)
1111
1112         if [[ -n "$poolname" ]]; then
1113                 do_facet $facet "$ZPOOL set cachefile=none $poolname"
1114         fi
1115 }
1116
1117 #
1118 # This and set_osd_param() shall be used to access OSD parameters
1119 # once existed under "obdfilter":
1120 #
1121 #   mntdev
1122 #   stats
1123 #   read_cache_enable
1124 #   writethrough_cache_enable
1125 #
1126 get_osd_param() {
1127         local nodes=$1
1128         local device=${2:-$FSNAME-OST*}
1129         local name=$3
1130
1131         do_nodes $nodes "$LCTL get_param -n obdfilter.$device.$name \
1132                 osd-*.$device.$name 2>&1" | grep -v 'error:'
1133 }
1134
1135 set_osd_param() {
1136         local nodes=$1
1137         local device=${2:-$FSNAME-OST*}
1138         local name=$3
1139         local value=$4
1140
1141         do_nodes $nodes "$LCTL set_param -n obdfilter.$device.$name=$value \
1142                 osd-*.$device.$name=$value 2>&1" | grep -v 'error:'
1143 }
1144
1145 set_debug_size () {
1146     local dz=${1:-$DEBUG_SIZE}
1147
1148     if [ -f /sys/devices/system/cpu/possible ]; then
1149         local cpus=$(($(cut -d "-" -f 2 /sys/devices/system/cpu/possible)+1))
1150     else
1151         local cpus=$(getconf _NPROCESSORS_CONF)
1152     fi
1153
1154     # bug 19944, adjust size to be -gt num_possible_cpus()
1155     # promise 2MB for every cpu at least
1156     if [ -n "$cpus" ] && [ $((cpus * 2)) -gt $dz ]; then
1157         dz=$((cpus * 2))
1158     fi
1159     lctl set_param debug_mb=$dz
1160 }
1161
1162 set_default_debug () {
1163     local debug=${1:-"$PTLDEBUG"}
1164     local subsys=${2:-"$SUBSYSTEM"}
1165     local debug_size=${3:-$DEBUG_SIZE}
1166
1167     [ -n "$debug" ] && lctl set_param debug="$debug" >/dev/null
1168     [ -n "$subsys" ] && lctl set_param subsystem_debug="${subsys# }" >/dev/null
1169
1170     [ -n "$debug_size" ] && set_debug_size $debug_size > /dev/null
1171 }
1172
1173 set_default_debug_nodes () {
1174         local nodes="$1"
1175
1176         if [[ ,$nodes, = *,$HOSTNAME,* ]]; then
1177                 nodes=$(exclude_items_from_list "$nodes" "$HOSTNAME")
1178                 set_default_debug
1179         fi
1180
1181         do_rpc_nodes "$nodes" set_default_debug \
1182                 \\\"$PTLDEBUG\\\" \\\"$SUBSYSTEM\\\" $DEBUG_SIZE || true
1183 }
1184
1185 set_default_debug_facet () {
1186     local facet=$1
1187     local node=$(facet_active_host $facet)
1188     [ -z "$node" ] && echo "No host defined for facet $facet" && exit 1
1189
1190     set_default_debug_nodes $node
1191 }
1192
1193 set_hostid () {
1194     local hostid=${1:-$(hostid)}
1195
1196     if [ ! -s /etc/hostid ]; then
1197         printf $(echo -n $hostid |
1198             sed 's/\(..\)\(..\)\(..\)\(..\)/\\x\4\\x\3\\x\2\\x\1/') >/etc/hostid
1199     fi
1200 }
1201
1202 # Facet functions
1203 mount_facets () {
1204         local facets=${1:-$(get_facets)}
1205         local facet
1206
1207         for facet in ${facets//,/ }; do
1208                 mount_facet $facet
1209                 local RC=$?
1210                 [ $RC -eq 0 ] && continue
1211
1212                 if [ "$TESTSUITE.$TESTNAME" = "replay-dual.test_0a" ]; then
1213                         skip "Restart of $facet failed!." && touch $LU482_FAILED
1214                 else
1215                         error "Restart of $facet failed!"
1216                 fi
1217                 return $RC
1218         done
1219 }
1220
1221 #
1222 # Add argument "arg" (e.g., "loop") to the comma-separated list
1223 # of arguments for option "opt" (e.g., "-o") on command
1224 # line "opts" (e.g., "-o flock").
1225 #
1226 csa_add() {
1227         local opts=$1
1228         local opt=$2
1229         local arg=$3
1230         local opt_pattern="\([[:space:]]\+\|^\)$opt"
1231
1232         if echo "$opts" | grep -q $opt_pattern; then
1233                 opts=$(echo "$opts" | sed -e \
1234                         "s/$opt_pattern[[:space:]]*[^[:space:]]\+/&,$arg/")
1235         else
1236                 opts+="${opts:+ }$opt $arg"
1237         fi
1238         echo -n "$opts"
1239 }
1240
1241 mount_facet() {
1242         local facet=$1
1243         shift
1244         local dev=$(facet_active $facet)_dev
1245         local opt=${facet}_opt
1246         local mntpt=$(facet_mntpt $facet)
1247         local opts="${!opt} $@"
1248         local fstype=$(facet_fstype $facet)
1249         local devicelabel
1250
1251         module_loaded lustre || load_modules
1252
1253         if [ $(facet_fstype $facet) == ldiskfs ] &&
1254            ! do_facet $facet test -b ${!dev}; then
1255                 opts=$(csa_add "$opts" -o loop)
1256         fi
1257
1258         if [[ $(facet_fstype $facet) == zfs ]]; then
1259                 # import ZFS storage pool
1260                 import_zpool $facet || return ${PIPESTATUS[0]}
1261         fi
1262
1263         case $fstype in
1264         ldiskfs)
1265                 devicelabel=$(do_facet ${facet} "$E2LABEL ${!dev}");;
1266         zfs)
1267                 devicelabel=$(do_facet ${facet} "$ZFS get -H -o value \
1268                                                 lustre:svname ${!dev}");;
1269         *)
1270                 error "unknown fstype!";;
1271         esac
1272
1273         echo "Starting ${facet}: $opts ${!dev} $mntpt"
1274         # for testing LU-482 error handling in mount_facets() and test_0a()
1275         if [ -f $TMP/test-lu482-trigger ]; then
1276                 RC=2
1277         else
1278                 do_facet ${facet} "mkdir -p $mntpt; $MOUNT_CMD $opts \
1279                                    ${!dev} $mntpt"
1280                 RC=${PIPESTATUS[0]}
1281         fi
1282
1283         if [ $RC -ne 0 ]; then
1284                 echo "Start of ${!dev} on ${facet} failed ${RC}"
1285                 return $RC
1286         fi
1287
1288         health=$(do_facet ${facet} "$LCTL get_param -n health_check")
1289         if [[ "$health" != "healthy" ]]; then
1290                 error "$facet is in a unhealthy state"
1291         fi
1292
1293         set_default_debug_facet $facet
1294
1295         if [[ $facet == mds* ]]; then
1296                 do_facet $facet \
1297                 lctl set_param -n mdt.${FSNAME}*.enable_remote_dir=1 2>/dev/null
1298         fi
1299
1300         if [[ $opts =~ .*nosvc.* ]]; then
1301                 echo "Start ${!dev} without service"
1302         else
1303
1304                 case $fstype in
1305                 ldiskfs)
1306                         wait_update_facet ${facet} "$E2LABEL ${!dev} \
1307                                 2>/dev/null | grep -E ':[a-zA-Z]{3}[0-9]{4}'" \
1308                                 "" || error "${!dev} failed to initialize!";;
1309                 zfs)
1310                         wait_update_facet ${facet} "$ZFS get -H -o value \
1311                                 lustre:svname ${!dev} 2>/dev/null | \
1312                                 grep -E ':[a-zA-Z]{3}[0-9]{4}'" "" ||
1313                                 error "${!dev} failed to initialize!";;
1314
1315                 *)
1316                         error "unknown fstype!";;
1317                 esac
1318         fi
1319
1320         # commit the device label change to disk
1321         if [[ $devicelabel =~ (:[a-zA-Z]{3}[0-9]{4}) ]]; then
1322                 do_facet $facet "sync; sync; sync"
1323         fi
1324
1325
1326         label=$(devicelabel ${facet} ${!dev})
1327         [ -z "$label" ] && echo no label for ${!dev} && exit 1
1328         eval export ${facet}_svc=${label}
1329         echo Started ${label}
1330
1331         return $RC
1332 }
1333
1334 # start facet device options
1335 start() {
1336         local facet=$1
1337         shift
1338         local device=$1
1339         shift
1340         eval export ${facet}_dev=${device}
1341         eval export ${facet}_opt=\"$@\"
1342
1343         local varname=${facet}failover_dev
1344         if [ -n "${!varname}" ] ; then
1345                 eval export ${facet}failover_dev=${!varname}
1346         else
1347                 eval export ${facet}failover_dev=$device
1348         fi
1349
1350         local mntpt=$(facet_mntpt $facet)
1351         do_facet ${facet} mkdir -p $mntpt
1352         eval export ${facet}_MOUNT=$mntpt
1353         mount_facet ${facet}
1354         RC=$?
1355
1356         if [[ $facet == mds* ]]; then
1357                 do_facet $facet \
1358                         lctl set_param -n mdt.${FSNAME}*.enable_remote_dir=1 \
1359                                 2>/dev/null
1360         fi
1361
1362         return $RC
1363 }
1364
1365 stop() {
1366     local running
1367     local facet=$1
1368     shift
1369     local HOST=`facet_active_host $facet`
1370     [ -z $HOST ] && echo stop: no host for $facet && return 0
1371
1372     local mntpt=$(facet_mntpt $facet)
1373     running=$(do_facet ${facet} "grep -c $mntpt' ' /proc/mounts") || true
1374     if [ ${running} -ne 0 ]; then
1375         echo "Stopping $mntpt (opts:$@) on $HOST"
1376         do_facet ${facet} $UMOUNT $@ $mntpt
1377     fi
1378
1379         # umount should block, but we should wait for unrelated obd's
1380         # like the MGS or MGC to also stop.
1381         wait_exit_ST ${facet} || return ${PIPESTATUS[0]}
1382
1383         if [[ $(facet_fstype $facet) == zfs ]]; then
1384                 # export ZFS storage pool
1385                 export_zpool $facet
1386         fi
1387 }
1388
1389 # save quota version (both administrative and operational quotas)
1390 # add an additional parameter if mountpoint is ever different from $MOUNT
1391 #
1392 # XXX This function is kept for interoperability with old server (< 2.3.50),
1393 #     it should be removed whenever we drop the interoperability for such
1394 #     server.
1395 quota_save_version() {
1396     local fsname=${2:-$FSNAME}
1397     local spec=$1
1398     local ver=$(tr -c -d "123" <<< $spec)
1399     local type=$(tr -c -d "ug" <<< $spec)
1400
1401     [ -n "$ver" -a "$ver" != "3" ] && error "wrong quota version specifier"
1402
1403     [ -n "$type" ] && { $LFS quotacheck -$type $MOUNT || error "quotacheck has failed"; }
1404
1405     do_facet mgs "lctl conf_param ${fsname}-MDT*.mdd.quota_type=$spec"
1406     local varsvc
1407     local osts=$(get_facets OST)
1408     for ost in ${osts//,/ }; do
1409         varsvc=${ost}_svc
1410         do_facet mgs "lctl conf_param ${!varsvc}.ost.quota_type=$spec"
1411     done
1412 }
1413
1414 # client could mount several lustre
1415 #
1416 # XXX This function is kept for interoperability with old server (< 2.3.50),
1417 #     it should be removed whenever we drop the interoperability for such
1418 #     server.
1419 quota_type() {
1420         local fsname=${1:-$FSNAME}
1421         local rc=0
1422         do_facet $SINGLEMDS lctl get_param mdd.${fsname}-MDT*.quota_type ||
1423                 rc=$?
1424         do_nodes $(comma_list $(osts_nodes)) \
1425                 lctl get_param obdfilter.${fsname}-OST*.quota_type || rc=$?
1426         return $rc
1427 }
1428
1429 # get mdt quota type
1430 mdt_quota_type() {
1431         local varsvc=${SINGLEMDS}_svc
1432         do_facet $SINGLEMDS $LCTL get_param -n \
1433                 osd-$(facet_fstype $SINGLEMDS).${!varsvc}.quota_slave.enabled
1434 }
1435
1436 # get ost quota type
1437 ost_quota_type() {
1438         # All OSTs should have same quota type
1439         local varsvc=ost1_svc
1440         do_facet ost1 $LCTL get_param -n \
1441                 osd-$(facet_fstype ost1).${!varsvc}.quota_slave.enabled
1442 }
1443
1444 # restore old quota type settings
1445 restore_quota() {
1446         if [ "$old_MDT_QUOTA_TYPE" ]; then
1447                 do_facet mgs $LCTL conf_param \
1448                         $FSNAME.quota.mdt=$old_MDT_QUOTA_TYPE
1449         fi
1450         if [ "$old_OST_QUOTA_TYPE" ]; then
1451                 do_facet mgs $LCTL conf_param \
1452                         $FSNAME.quota.ost=$old_OST_QUOTA_TYPE
1453         fi
1454 }
1455
1456 # Handle the case when there is a space in the lfs df
1457 # "filesystem summary" line the same as when there is no space.
1458 # This will allow fixing the "lfs df" summary line in the future.
1459 lfs_df() {
1460         $LFS df $* | sed -e 's/filesystem /filesystem_/'
1461 }
1462
1463 # Get free inodes on the MDT specified by mdt index, free indoes on
1464 # the whole filesystem will be returned when index == -1.
1465 mdt_free_inodes() {
1466         local index=$1
1467         local free_inodes
1468         local mdt_uuid
1469
1470         if [ $index -eq -1 ]; then
1471                 mdt_uuid="summary"
1472         else
1473                 mdt_uuid=$(mdtuuid_from_index $index)
1474         fi
1475
1476         free_inodes=$(lfs_df -i $MOUNT | grep $mdt_uuid | awk '{print $4}')
1477         echo $free_inodes
1478 }
1479
1480 setup_quota(){
1481         local mntpt=$1
1482
1483         # save old quota type & set new quota type
1484         local mdt_qtype=$(mdt_quota_type)
1485         local ost_qtype=$(ost_quota_type)
1486
1487         echo "[HOST:$HOSTNAME] [old_mdt_qtype:$mdt_qtype]" \
1488                 "[old_ost_qtype:$ost_qtype] [new_qtype:$QUOTA_TYPE]"
1489
1490         export old_MDT_QUOTA_TYPE=$mdt_qtype
1491         export old_OST_QUOTA_TYPE=$ost_qtype
1492
1493         do_facet mgs $LCTL conf_param $FSNAME.quota.mdt=$QUOTA_TYPE ||
1494                 error "set mdt quota type failed"
1495         do_facet mgs $LCTL conf_param $FSNAME.quota.ost=$QUOTA_TYPE ||
1496                 error "set ost quota type failed"
1497
1498         local quota_usrs=$QUOTA_USERS
1499
1500         # get_filesystem_size
1501         local disksz=$(lfs_df $mntpt | grep "summary" | awk '{print $2}')
1502         local blk_soft=$((disksz + 1024))
1503         local blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over
1504
1505         local inodes=$(lfs_df -i $mntpt | grep "summary" | awk '{print $2}')
1506         local i_soft=$inodes
1507         local i_hard=$((i_soft + i_soft / 20))
1508
1509         echo "Total disk size: $disksz  block-softlimit: $blk_soft" \
1510                 "block-hardlimit: $blk_hard inode-softlimit: $i_soft" \
1511                 "inode-hardlimit: $i_hard"
1512
1513         local cmd
1514         for usr in $quota_usrs; do
1515                 echo "Setting up quota on $HOSTNAME:$mntpt for $usr..."
1516                 for type in u g; do
1517                         cmd="$LFS setquota -$type $usr -b $blk_soft"
1518                         cmd="$cmd -B $blk_hard -i $i_soft -I $i_hard $mntpt"
1519                         echo "+ $cmd"
1520                         eval $cmd || error "$cmd FAILED!"
1521                 done
1522                 # display the quota status
1523                 echo "Quota settings for $usr : "
1524                 $LFS quota -v -u $usr $mntpt || true
1525         done
1526 }
1527
1528 zconf_mount() {
1529         local client=$1
1530         local mnt=$2
1531         local opts=${3:-$MOUNT_OPTS}
1532         opts=${opts:+-o $opts}
1533         local flags=${4:-$MOUNT_FLAGS}
1534
1535         local device=$MGSNID:/$FSNAME$FILESET
1536         if [ -z "$mnt" -o -z "$FSNAME" ]; then
1537                 echo "Bad mount command: opt=$flags $opts dev=$device " \
1538                      "mnt=$mnt"
1539                 exit 1
1540         fi
1541
1542         echo "Starting client: $client: $flags $opts $device $mnt"
1543         do_node $client mkdir -p $mnt
1544         if [ -n "$FILESET" -a -z "$SKIP_FILESET" ];then
1545                 do_node $client $MOUNT_CMD $flags $opts $MGSNID:/$FSNAME \
1546                         $mnt || return 1
1547                 #disable FILESET if not supported
1548                 do_nodes $client lctl get_param -n \
1549                         mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
1550                                 device=$MGSNID:/$FSNAME
1551                 do_node $client mkdir -p $mnt/$FILESET
1552                 do_node $client "! grep -q $mnt' ' /proc/mounts ||
1553                         umount $mnt"
1554         fi
1555         do_node $client $MOUNT_CMD $flags $opts $device $mnt || return 1
1556
1557         set_default_debug_nodes $client
1558
1559         return 0
1560 }
1561
1562 zconf_umount() {
1563     local client=$1
1564     local mnt=$2
1565     local force
1566     local busy 
1567     local need_kill
1568
1569     [ "$3" ] && force=-f
1570     local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
1571     if [ $running -ne 0 ]; then
1572         echo "Stopping client $client $mnt (opts:$force)"
1573         do_node $client lsof -t $mnt || need_kill=no
1574         if [ "x$force" != "x" -a "x$need_kill" != "xno" ]; then
1575             pids=$(do_node $client lsof -t $mnt | sort -u);
1576             if [ -n $pids ]; then
1577                 do_node $client kill -9 $pids || true
1578             fi
1579         fi
1580
1581         busy=$(do_node $client "umount $force $mnt 2>&1" | grep -c "busy") || true
1582         if [ $busy -ne 0 ] ; then
1583             echo "$mnt is still busy, wait one second" && sleep 1
1584             do_node $client umount $force $mnt
1585         fi
1586     fi
1587 }
1588
1589 # nodes is comma list
1590 sanity_mount_check_nodes () {
1591     local nodes=$1
1592     shift
1593     local mnts="$@"
1594     local mnt
1595
1596     # FIXME: assume that all cluster nodes run the same os
1597     [ "$(uname)" = Linux ] || return 0
1598
1599     local rc=0
1600     for mnt in $mnts ; do
1601         do_nodes $nodes "running=\\\$(grep -c $mnt' ' /proc/mounts);
1602 mpts=\\\$(mount | grep -c $mnt' ');
1603 if [ \\\$running -ne \\\$mpts ]; then
1604     echo \\\$(hostname) env are INSANE!;
1605     exit 1;
1606 fi"
1607     [ $? -eq 0 ] || rc=1 
1608     done
1609     return $rc
1610 }
1611
1612 sanity_mount_check_servers () {
1613     [ "$CLIENTONLY" ] && 
1614         { echo "CLIENTONLY mode, skip mount_check_servers"; return 0; } || true
1615     echo Checking servers environments
1616
1617     # FIXME: modify get_facets to display all facets wo params
1618     local facets="$(get_facets OST),$(get_facets MDS),mgs"
1619     local node
1620     local mntpt
1621     local facet
1622     for facet in ${facets//,/ }; do
1623         node=$(facet_host ${facet})
1624         mntpt=$(facet_mntpt $facet)
1625         sanity_mount_check_nodes $node $mntpt ||
1626             { error "server $node environments are insane!"; return 1; }
1627     done
1628 }
1629
1630 sanity_mount_check_clients () {
1631     local clients=${1:-$CLIENTS}
1632     local mntpt=${2:-$MOUNT}
1633     local mntpt2=${3:-$MOUNT2}
1634
1635     [ -z $clients ] && clients=$(hostname)
1636     echo Checking clients $clients environments
1637
1638     sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
1639        error "clients environments are insane!"
1640 }
1641
1642 sanity_mount_check () {
1643     sanity_mount_check_servers || return 1
1644     sanity_mount_check_clients || return 2
1645 }
1646
1647 # mount clients if not mouted
1648 zconf_mount_clients() {
1649         local clients=$1
1650         local mnt=$2
1651         local opts=${3:-$MOUNT_OPTS}
1652         opts=${opts:+-o $opts}
1653         local flags=${4:-$MOUNT_FLAGS}
1654
1655         local device=$MGSNID:/$FSNAME$FILESET
1656         if [ -z "$mnt" -o -z "$FSNAME" ]; then
1657                 echo "Bad conf mount command: opt=$flags $opts dev=$device " \
1658                      "mnt=$mnt"
1659                 exit 1
1660         fi
1661
1662         echo "Starting client $clients: $flags $opts $device $mnt"
1663         if [ -n "$FILESET" -a ! -n "$SKIP_FILESET" ]; then
1664                 do_nodes $clients "! grep -q $mnt' ' /proc/mounts ||
1665                         umount $mnt"
1666                 do_nodes $clients $MOUNT_CMD $flags $opts $MGSNID:/$FSNAME \
1667                         $mnt || return 1
1668                 #disable FILESET if not supported
1669                 do_nodes $clients lctl get_param -n \
1670                         mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
1671                                 device=$MGSNID:/$FSNAME
1672                 do_nodes $clients mkdir -p $mnt/$FILESET
1673                 do_nodes $clients "! grep -q $mnt' ' /proc/mounts ||
1674                         umount $mnt"
1675         fi
1676
1677         do_nodes $clients "
1678 running=\\\$(mount | grep -c $mnt' ');
1679 rc=0;
1680 if [ \\\$running -eq 0 ] ; then
1681     mkdir -p $mnt;
1682     $MOUNT_CMD $flags $opts $device $mnt;
1683     rc=\\\$?;
1684 fi;
1685 exit \\\$rc" || return ${PIPESTATUS[0]}
1686
1687         echo "Started clients $clients: "
1688         do_nodes $clients "mount | grep $mnt' '"
1689
1690         set_default_debug_nodes $clients
1691
1692         return 0
1693 }
1694
1695 zconf_umount_clients() {
1696     local clients=$1
1697     local mnt=$2
1698     local force
1699
1700     [ "$3" ] && force=-f
1701
1702     echo "Stopping clients: $clients $mnt (opts:$force)"
1703     do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
1704 if [ \\\$running -ne 0 ] ; then
1705 echo Stopping client \\\$(hostname) $mnt opts:$force;
1706 lsof $mnt || need_kill=no;
1707 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
1708     pids=\\\$(lsof -t $mnt | sort -u);
1709     if [ -n \\\"\\\$pids\\\" ]; then
1710              kill -9 \\\$pids;
1711     fi
1712 fi;
1713 while umount $force $mnt 2>&1 | grep -q "busy"; do
1714     echo "$mnt is still busy, wait one second" && sleep 1;
1715 done;
1716 fi"
1717 }
1718
1719 shutdown_node () {
1720     local node=$1
1721     echo + $POWER_DOWN $node
1722     $POWER_DOWN $node
1723 }
1724
1725 shutdown_node_hard () {
1726     local host=$1
1727     local attempts=$SHUTDOWN_ATTEMPTS
1728
1729     for i in $(seq $attempts) ; do
1730         shutdown_node $host
1731         sleep 1
1732         wait_for_function --quiet "! ping -w 3 -c 1 $host" 5 1 && return 0
1733         echo "waiting for $host to fail attempts=$attempts"
1734         [ $i -lt $attempts ] || \
1735             { echo "$host still pingable after power down! attempts=$attempts" && return 1; } 
1736     done
1737 }
1738
1739 shutdown_client() {
1740     local client=$1
1741     local mnt=${2:-$MOUNT}
1742     local attempts=3
1743
1744     if [ "$FAILURE_MODE" = HARD ]; then
1745         shutdown_node_hard $client
1746     else
1747        zconf_umount_clients $client $mnt -f
1748     fi
1749 }
1750
1751 facets_on_host () {
1752     local host=$1
1753     local facets="$(get_facets OST),$(get_facets MDS)"
1754     local affected
1755
1756     combined_mgs_mds || facets="$facets,mgs"
1757
1758     for facet in ${facets//,/ }; do
1759         if [ $(facet_active_host $facet) == $host ]; then
1760            affected="$affected $facet"
1761         fi
1762     done
1763
1764     echo $(comma_list $affected)
1765 }
1766
1767 facet_up() {
1768         local facet=$1
1769         local host=${2:-$(facet_host $facet)}
1770
1771         local label=$(convert_facet2label $facet)
1772         do_node $host $LCTL dl | awk '{ print $4 }' | grep -q "^$label\$"
1773 }
1774
1775 facets_up_on_host () {
1776     local host=$1
1777     local facets=$(facets_on_host $host)
1778     local affected_up
1779
1780     for facet in ${facets//,/ }; do
1781         if $(facet_up $facet $host); then
1782             affected_up="$affected_up $facet"
1783         fi
1784     done
1785
1786     echo $(comma_list $affected_up)
1787 }
1788
1789 shutdown_facet() {
1790     local facet=$1
1791
1792     if [ "$FAILURE_MODE" = HARD ]; then
1793         shutdown_node_hard $(facet_active_host $facet)
1794     else
1795         stop $facet
1796     fi
1797 }
1798
1799 reboot_node() {
1800     local node=$1
1801     echo + $POWER_UP $node
1802     $POWER_UP $node
1803 }
1804
1805 remount_facet() {
1806     local facet=$1
1807
1808     stop $facet
1809     mount_facet $facet
1810 }
1811
1812 reboot_facet() {
1813         local facet=$1
1814         if [ "$FAILURE_MODE" = HARD ]; then
1815                 reboot_node $(facet_active_host $facet)
1816         else
1817                 sleep 10
1818         fi
1819 }
1820
1821 boot_node() {
1822     local node=$1
1823     if [ "$FAILURE_MODE" = HARD ]; then
1824        reboot_node $node
1825        wait_for_host $node
1826     fi
1827 }
1828
1829 facets_hosts () {
1830     local facets=$1
1831     local hosts
1832
1833     for facet in ${facets//,/ }; do
1834         hosts=$(expand_list $hosts $(facet_host $facet) )
1835     done
1836
1837     echo $hosts
1838 }
1839
1840 _check_progs_installed () {
1841     local progs=$@
1842     local rc=0
1843
1844     for prog in $progs; do
1845         if ! [ "$(which $prog)"  -o  "${!prog}" ]; then
1846            echo $prog missing on $(hostname)
1847            rc=1
1848         fi
1849     done
1850     return $rc
1851 }
1852
1853 check_progs_installed () {
1854         local nodes=$1
1855         shift
1856
1857         do_rpc_nodes "$nodes" _check_progs_installed $@
1858 }
1859
1860 # recovery-scale functions
1861 node_var_name() {
1862     echo __$(echo $1 | tr '-' '_' | tr '.' '_')
1863 }
1864
1865 start_client_load() {
1866     local client=$1
1867     local load=$2
1868     local var=$(node_var_name $client)_load
1869     eval export ${var}=$load
1870
1871     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
1872 BREAK_ON_ERROR=$BREAK_ON_ERROR \
1873 END_RUN_FILE=$END_RUN_FILE \
1874 LOAD_PID_FILE=$LOAD_PID_FILE \
1875 TESTLOG_PREFIX=$TESTLOG_PREFIX \
1876 TESTNAME=$TESTNAME \
1877 DBENCH_LIB=$DBENCH_LIB \
1878 DBENCH_SRC=$DBENCH_SRC \
1879 CLIENT_COUNT=$((CLIENTCOUNT - 1)) \
1880 LFS=$LFS \
1881 run_${load}.sh" &
1882     local ppid=$!
1883     log "Started client load: ${load} on $client"
1884
1885     # get the children process IDs
1886     local pids=$(ps --ppid $ppid -o pid= | xargs)
1887     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $ppid $pids"
1888     return 0
1889 }
1890
1891 start_client_loads () {
1892     local -a clients=(${1//,/ })
1893     local numloads=${#CLIENT_LOADS[@]}
1894     local testnum
1895
1896     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
1897         testnum=$((nodenum % numloads))
1898         start_client_load ${clients[nodenum]} ${CLIENT_LOADS[testnum]}
1899     done
1900     # bug 22169: wait the background threads to start
1901     sleep 2
1902 }
1903
1904 # only for remote client
1905 check_client_load () {
1906     local client=$1
1907     local var=$(node_var_name $client)_load
1908     local TESTLOAD=run_${!var}.sh
1909
1910     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
1911
1912     # bug 18914: try to connect several times not only when
1913     # check ps, but  while check_catastrophe also
1914     local tries=3
1915     local RC=254
1916     while [ $RC = 254 -a $tries -gt 0 ]; do
1917         let tries=$tries-1
1918         # assume success
1919         RC=0
1920         if ! check_catastrophe $client; then
1921             RC=${PIPESTATUS[0]}
1922             if [ $RC -eq 254 ]; then
1923                 # FIXME: not sure how long we shuold sleep here
1924                 sleep 10
1925                 continue
1926             fi
1927             echo "check catastrophe failed: RC=$RC "
1928             return $RC
1929         fi
1930     done
1931     # We can continue try to connect if RC=254
1932     # Just print the warning about this
1933     if [ $RC = 254 ]; then
1934         echo "got a return status of $RC from do_node while checking catastrophe on $client"
1935     fi
1936
1937     # see if the load is still on the client
1938     tries=3
1939     RC=254
1940     while [ $RC = 254 -a $tries -gt 0 ]; do
1941         let tries=$tries-1
1942         # assume success
1943         RC=0
1944         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
1945             RC=${PIPESTATUS[0]}
1946             sleep 30
1947         fi
1948     done
1949     if [ $RC = 254 ]; then
1950         echo "got a return status of $RC from do_node while checking (catastrophe and 'ps') the client load on $client"
1951         # see if we can diagnose a bit why this is
1952     fi
1953
1954     return $RC
1955 }
1956 check_client_loads () {
1957    local clients=${1//,/ }
1958    local client=
1959    local rc=0
1960
1961    for client in $clients; do
1962       check_client_load $client
1963       rc=${PIPESTATUS[0]}
1964       if [ "$rc" != 0 ]; then
1965         log "Client load failed on node $client, rc=$rc"
1966         return $rc
1967       fi
1968    done
1969 }
1970
1971 restart_client_loads () {
1972     local clients=${1//,/ }
1973     local expectedfail=${2:-""}
1974     local client=
1975     local rc=0
1976
1977     for client in $clients; do
1978         check_client_load $client
1979         rc=${PIPESTATUS[0]}
1980         if [ "$rc" != 0 -a "$expectedfail" ]; then
1981             local var=$(node_var_name $client)_load
1982             start_client_load $client ${!var}
1983             echo "Restarted client load ${!var}: on $client. Checking ..."
1984             check_client_load $client
1985             rc=${PIPESTATUS[0]}
1986             if [ "$rc" != 0 ]; then
1987                 log "Client load failed to restart on node $client, rc=$rc"
1988                 # failure one client load means test fail
1989                 # we do not need to check other
1990                 return $rc
1991             fi
1992         else
1993             return $rc
1994         fi
1995     done
1996 }
1997
1998 # Start vmstat and save its process ID in a file.
1999 start_vmstat() {
2000     local nodes=$1
2001     local pid_file=$2
2002
2003     [ -z "$nodes" -o -z "$pid_file" ] && return 0
2004
2005     do_nodes $nodes \
2006         "vmstat 1 > $TESTLOG_PREFIX.$TESTNAME.vmstat.\\\$(hostname -s).log \
2007         2>/dev/null </dev/null & echo \\\$! > $pid_file"
2008 }
2009
2010 # Display the nodes on which client loads failed.
2011 print_end_run_file() {
2012     local file=$1
2013     local node
2014
2015     [ -s $file ] || return 0
2016
2017     echo "Found the END_RUN_FILE file: $file"
2018     cat $file
2019
2020     # A client load will stop if it finds the END_RUN_FILE file.
2021     # That does not mean the client load actually failed though.
2022     # The first node in END_RUN_FILE is the one we are interested in.
2023     read node < $file
2024
2025     if [ -n "$node" ]; then
2026         local var=$(node_var_name $node)_load
2027
2028         local prefix=$TESTLOG_PREFIX
2029         [ -n "$TESTNAME" ] && prefix=$prefix.$TESTNAME
2030         local stdout_log=$prefix.run_${!var}_stdout.$node.log
2031         local debug_log=$(echo $stdout_log | sed 's/\(.*\)stdout/\1debug/')
2032
2033         echo "Client load ${!var} failed on node $node:"
2034         echo "$stdout_log"
2035         echo "$debug_log"
2036     fi
2037 }
2038
2039 # Stop the process which had its PID saved in a file.
2040 stop_process() {
2041     local nodes=$1
2042     local pid_file=$2
2043
2044     [ -z "$nodes" -o -z "$pid_file" ] && return 0
2045
2046     do_nodes $nodes "test -f $pid_file &&
2047         { kill -s TERM \\\$(cat $pid_file); rm -f $pid_file; }" || true
2048 }
2049
2050 # Stop all client loads.
2051 stop_client_loads() {
2052     local nodes=${1:-$CLIENTS}
2053     local pid_file=$2
2054
2055     # stop the client loads
2056     stop_process $nodes $pid_file
2057
2058     # clean up the processes that started them
2059     [ -n "$CLIENT_LOAD_PIDS" ] && kill -9 $CLIENT_LOAD_PIDS 2>/dev/null || true
2060 }
2061 # End recovery-scale functions
2062
2063 # verify that lustre actually cleaned up properly
2064 cleanup_check() {
2065         VAR=$(lctl get_param -n catastrophe 2>&1)
2066         if [ $? = 0 ] ; then
2067                 if [ $VAR != 0 ]; then
2068                         error "LBUG/LASSERT detected"
2069                 fi
2070         fi
2071         BUSY=$(dmesg | grep -i destruct || true)
2072         if [ -n "$BUSY" ]; then
2073                 echo "$BUSY" 1>&2
2074                 [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.$(date +%s)
2075                 exit 205
2076         fi
2077
2078         check_mem_leak || exit 204
2079
2080         [[ $($LCTL dl 2>/dev/null | wc -l) -gt 0 ]] && $LCTL dl &&
2081                 echo "$TESTSUITE: lustre didn't clean up..." 1>&2 &&
2082                 return 202 || true
2083
2084         if module_loaded lnet || module_loaded libcfs; then
2085                 echo "$TESTSUITE: modules still loaded..." 1>&2
2086                 /sbin/lsmod 1>&2
2087                 return 203
2088         fi
2089         return 0
2090 }
2091
2092 wait_update () {
2093         local verbose=false
2094         if [[ "$1" == "--verbose" ]]; then
2095                 shift
2096                 verbose=true
2097         fi
2098
2099         local node=$1
2100         local TEST=$2
2101         local FINAL=$3
2102         local MAX=${4:-90}
2103         local RESULT
2104         local PREV_RESULT
2105         local WAIT=0
2106         local sleep=1
2107         local print=10
2108
2109         PREV_RESULT=$(do_node $node "$TEST")
2110         while [ true ]; do
2111                 RESULT=$(do_node $node "$TEST")
2112                 if [[ "$RESULT" == "$FINAL" ]]; then
2113                         [[ -z "$RESULT" || $WAIT -le $sleep ]] ||
2114                                 echo "Updated after ${WAIT}s: wanted '$FINAL'"\
2115                                      "got '$RESULT'"
2116                         return 0
2117                 fi
2118                 if [[ $verbose && "$RESULT" != "$PREV_RESULT" ]]; then
2119                         echo "Changed after ${WAIT}s: from '$PREV_RESULT'"\
2120                              "to '$RESULT'"
2121                         PREV_RESULT=$RESULT
2122                 fi
2123                 [[ $WAIT -ge $MAX ]] && break
2124                 [[ $((WAIT % print)) -eq 0 ]] &&
2125                         echo "Waiting $((MAX - WAIT)) secs for update"
2126                 WAIT=$((WAIT + sleep))
2127                 sleep $sleep
2128         done
2129         echo "Update not seen after ${MAX}s: wanted '$FINAL' got '$RESULT'"
2130         return 3
2131 }
2132
2133 wait_update_facet() {
2134         local verbose=
2135         [ "$1" = "--verbose" ] && verbose="$1" && shift
2136
2137         local facet=$1
2138         shift
2139         wait_update $verbose $(facet_active_host $facet) "$@"
2140 }
2141
2142 sync_all_data() {
2143         do_nodes $(comma_list $(mdts_nodes)) \
2144             "lctl set_param -n osd*.*MDT*.force_sync=1"
2145         do_nodes $(comma_list $(osts_nodes)) \
2146             "lctl set_param -n osd*.*OS*.force_sync=1" 2>&1 |
2147                 grep -v 'Found no match'
2148 }
2149
2150 wait_delete_completed_mds() {
2151         local MAX_WAIT=${1:-20}
2152         # for ZFS, waiting more time for DMUs to be committed
2153         local ZFS_WAIT=${2:-5}
2154         local mds2sync=""
2155         local stime=$(date +%s)
2156         local etime
2157         local node
2158         local changes
2159
2160         # find MDS with pending deletions
2161         for node in $(mdts_nodes); do
2162                 changes=$(do_node $node "$LCTL get_param -n osc.*MDT*.sync_*" \
2163                         2>/dev/null | calc_sum)
2164                 if [[ $changes -eq 0 ]]; then
2165                         continue
2166                 fi
2167                 mds2sync="$mds2sync $node"
2168         done
2169         if [ -z "$mds2sync" ]; then
2170                 return
2171         fi
2172         mds2sync=$(comma_list $mds2sync)
2173
2174         # sync MDS transactions
2175         do_nodes $mds2sync "$LCTL set_param -n osd*.*MD*.force_sync 1"
2176
2177         # wait till all changes are sent and commmitted by OSTs
2178         # for ldiskfs space is released upon execution, but DMU
2179         # do this upon commit
2180
2181         local WAIT=0
2182         while [[ $WAIT -ne $MAX_WAIT ]]; do
2183                 changes=$(do_nodes $mds2sync \
2184                         "$LCTL get_param -n osc.*MDT*.sync_*" | calc_sum)
2185                 #echo "$node: $changes changes on all"
2186                 if [[ $changes -eq 0 ]]; then
2187                         etime=$(date +%s)
2188                         #echo "delete took $((etime - stime)) seconds"
2189
2190                         # the occupied disk space will be released
2191                         # only after DMUs are committed
2192                         if [[ $(facet_fstype $SINGLEMDS) == zfs ]]; then
2193                                 echo "sleep $ZFS_WAIT for ZFS OSD"
2194                                 sleep $ZFS_WAIT
2195                         fi
2196
2197                         return
2198                 fi
2199                 sleep 1
2200                 WAIT=$(( WAIT + 1))
2201         done
2202
2203         etime=$(date +%s)
2204         echo "Delete is not completed in $((etime - stime)) seconds"
2205         do_nodes $mds2sync "$LCTL get_param osc.*MDT*.sync_*"
2206 }
2207
2208 wait_for_host() {
2209     local hostlist=$1
2210
2211     # we can use "for" here because we are waiting the slowest
2212     for host in ${hostlist//,/ }; do
2213         check_network "$host" 900
2214     done
2215     while ! do_nodes $hostlist hostname  > /dev/null; do sleep 5; done
2216 }
2217
2218 wait_for_facet() {
2219     local facetlist=$1
2220     local hostlist
2221
2222     for facet in ${facetlist//,/ }; do
2223         hostlist=$(expand_list $hostlist $(facet_active_host $facet))
2224     done
2225     wait_for_host $hostlist
2226 }
2227
2228 _wait_recovery_complete () {
2229     local param=$1
2230
2231     # Use default policy if $2 is not passed by caller.
2232     local MAX=${2:-$(max_recovery_time)}
2233
2234     local WAIT=0
2235     local STATUS=
2236
2237     while [ $WAIT -lt $MAX ]; do
2238         STATUS=$(lctl get_param -n $param | grep status)
2239         echo $param $STATUS
2240         [[ $STATUS = "status: COMPLETE" || $STATUS = "status: INACTIVE" ]] && return 0
2241         sleep 5
2242         WAIT=$((WAIT + 5))
2243         echo "Waiting $((MAX - WAIT)) secs for $param recovery done. $STATUS"
2244     done
2245     echo "$param recovery not done in $MAX sec. $STATUS"
2246     return 1
2247 }
2248
2249 wait_recovery_complete () {
2250     local facet=$1
2251
2252     # with an assumption that at_max is the same on all nodes
2253     local MAX=${2:-$(max_recovery_time)}
2254
2255     local facets=$facet
2256     if [ "$FAILURE_MODE" = HARD ]; then
2257         facets=$(facets_on_host $(facet_active_host $facet))
2258     fi
2259     echo affected facets: $facets
2260
2261         # we can use "for" here because we are waiting the slowest
2262         for facet in ${facets//,/ }; do
2263                 local var_svc=${facet}_svc
2264                 local param="*.${!var_svc}.recovery_status"
2265
2266                 local host=$(facet_active_host $facet)
2267                 do_rpc_nodes "$host" _wait_recovery_complete $param $MAX
2268         done
2269 }
2270
2271 wait_mds_ost_sync () {
2272         # just because recovery is done doesn't mean we've finished
2273         # orphan cleanup. Wait for llogs to get synchronized.
2274         echo "Waiting for orphan cleanup..."
2275         # MAX value includes time needed for MDS-OST reconnection
2276         local MAX=$(( TIMEOUT * 2 ))
2277         local WAIT_TIMEOUT=${1:-$MAX}
2278         local WAIT=0
2279         local new_wait=true
2280         local list=$(comma_list $(mdts_nodes))
2281         local cmd="$LCTL get_param -n osp.*osc*.old_sync_processed"
2282         if ! do_facet $SINGLEMDS \
2283                 "$LCTL list_param osp.*osc*.old_sync_processed 2> /dev/null"
2284         then
2285                 # old way, use mds_sync
2286                 new_wait=false
2287                 list=$(comma_list $(osts_nodes))
2288                 cmd="$LCTL get_param -n obdfilter.*.mds_sync"
2289         fi
2290
2291         echo "wait $WAIT_TIMEOUT secs maximumly for $list mds-ost sync done."
2292         while [ $WAIT -lt $WAIT_TIMEOUT ]; do
2293                 local -a sync=($(do_nodes $list "$cmd"))
2294                 local con=1
2295                 local i
2296                 for ((i=0; i<${#sync[@]}; i++)); do
2297                         if $new_wait; then
2298                                 [ ${sync[$i]} -eq 1 ] && continue
2299                         else
2300                                 [ ${sync[$i]} -eq 0 ] && continue
2301                         fi
2302                         # there is a not finished MDS-OST synchronization
2303                         con=0
2304                         break;
2305                 done
2306                 sleep 2 # increase waiting time and cover statfs cache
2307                 [ ${con} -eq 1 ] && return 0
2308                 echo "Waiting $WAIT secs for $list $i mds-ost sync done."
2309                 WAIT=$((WAIT + 2))
2310         done
2311
2312         # show which nodes are not finished.
2313         do_nodes $list "$cmd"
2314         echo "$facet recovery node $i not done in $WAIT_TIMEOUT sec. $STATUS"
2315         return 1
2316 }
2317
2318 wait_destroy_complete () {
2319         echo "Waiting for local destroys to complete"
2320         # MAX value shouldn't be big as this mean server responsiveness
2321         # never increase this just to make test pass but investigate
2322         # why it takes so long time
2323         local MAX=5
2324         local WAIT=0
2325         while [ $WAIT -lt $MAX ]; do
2326                 local -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))
2327                 local con=1
2328                 local i
2329
2330                 for ((i=0; i<${#RPCs[@]}; i++)); do
2331                         [ ${RPCs[$i]} -eq 0 ] && continue
2332                         # there are still some destroy RPCs in flight
2333                         con=0
2334                         break;
2335                 done
2336                 sleep 1
2337                 [ ${con} -eq 1 ] && return 0 # done waiting
2338                 echo "Waiting ${WAIT}s for local destroys to complete"
2339                 WAIT=$((WAIT + 1))
2340         done
2341         echo "Local destroys weren't done in $MAX sec."
2342         return 1
2343 }
2344
2345 wait_delete_completed() {
2346         wait_delete_completed_mds $1 || return $?
2347         wait_destroy_complete
2348 }
2349
2350 wait_exit_ST () {
2351     local facet=$1
2352
2353     local WAIT=0
2354     local INTERVAL=1
2355     local running
2356     # conf-sanity 31 takes a long time cleanup
2357     while [ $WAIT -lt 300 ]; do
2358         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
2359         [ -z "${running}" ] && return 0
2360         echo "waited $WAIT for${running}"
2361         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
2362         sleep $INTERVAL
2363         WAIT=$((WAIT + INTERVAL))
2364     done
2365     echo "service didn't stop after $WAIT seconds.  Still running:"
2366     echo ${running}
2367     return 1
2368 }
2369
2370 wait_remote_prog () {
2371    local prog=$1
2372    local WAIT=0
2373    local INTERVAL=5
2374    local rc=0
2375
2376    [ "$PDSH" = "no_dsh" ] && return 0
2377
2378    while [ $WAIT -lt $2 ]; do
2379         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
2380         [ -z "${running}" ] && return 0 || true
2381         echo "waited $WAIT for: "
2382         echo "$running"
2383         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
2384         sleep $INTERVAL
2385         WAIT=$((WAIT + INTERVAL))
2386     done
2387     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
2388     [ -z "$pids" ] && return 0
2389     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
2390     # FIXME: not portable
2391     for pid in $pids; do
2392         cat /proc/${pid}/status || true
2393         cat /proc/${pid}/wchan || true
2394         echo "Killing $pid"
2395         kill -9 $pid || true
2396         sleep 1
2397         ps -P $pid && rc=1
2398     done
2399
2400     return $rc
2401 }
2402
2403 clients_up() {
2404     # not every config has many clients
2405     sleep 1
2406     if [ ! -z "$CLIENTS" ]; then
2407         $PDSH $CLIENTS "stat -f $MOUNT" > /dev/null
2408     else
2409         stat -f $MOUNT > /dev/null
2410     fi
2411 }
2412
2413 client_up() {
2414     local client=$1
2415     # usually checked on particular client or locally
2416     sleep 1
2417     if [ ! -z "$client" ]; then
2418         $PDSH $client "stat -f $MOUNT" > /dev/null
2419     else
2420         stat -f $MOUNT > /dev/null
2421     fi
2422 }
2423
2424 client_evicted() {
2425     ! client_up $1
2426 }
2427
2428 client_reconnect_try() {
2429     uname -n >> $MOUNT/recon
2430     if [ -z "$CLIENTS" ]; then
2431         df $MOUNT; uname -n >> $MOUNT/recon
2432     else
2433         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
2434     fi
2435     echo Connected clients:
2436     cat $MOUNT/recon
2437     ls -l $MOUNT/recon > /dev/null
2438     rm $MOUNT/recon
2439 }
2440
2441 client_reconnect() {
2442         # one client_reconnect_try call does not always do the job...
2443         while true ; do
2444                 client_reconnect_try && break
2445                 sleep 1
2446         done
2447 }
2448
2449 affected_facets () {
2450     local facet=$1
2451
2452     local host=$(facet_active_host $facet)
2453     local affected=$facet
2454
2455     if [ "$FAILURE_MODE" = HARD ]; then
2456         affected=$(facets_up_on_host $host)
2457     fi
2458     echo $affected
2459 }
2460
2461 facet_failover() {
2462         local E2FSCK_ON_MDT0=false
2463         if [ "$1" == "--fsck" ]; then
2464                 shift
2465                 [ $(facet_fstype $SINGLEMDS) == ldiskfs ] &&
2466                         E2FSCK_ON_MDT0=true
2467         fi
2468
2469         local facets=$1
2470         local sleep_time=$2
2471         local -a affecteds
2472         local facet
2473         local total=0
2474         local index=0
2475         local skip
2476
2477         #Because it will only get up facets, we need get affected
2478         #facets before shutdown
2479         #For HARD Failure mode, it needs make sure facets on the same
2480         #HOST will only be shutdown and reboot once
2481         for facet in ${facets//,/ }; do
2482                 local affected_facet
2483                 skip=0
2484                 #check whether facet has been included in other affected facets
2485                 for ((index=0; index<$total; index++)); do
2486                         [[ *,$facet,* == ,${affecteds[index]}, ]] && skip=1
2487                 done
2488
2489                 if [ $skip -eq 0 ]; then
2490                         affecteds[$total]=$(affected_facets $facet)
2491                         total=$((total+1))
2492                 fi
2493         done
2494
2495         for ((index=0; index<$total; index++)); do
2496                 facet=$(echo ${affecteds[index]} | tr -s " " | cut -d"," -f 1)
2497                 local host=$(facet_active_host $facet)
2498                 echo "Failing ${affecteds[index]} on $host"
2499                 shutdown_facet $facet
2500         done
2501
2502         $E2FSCK_ON_MDT0 && (run_e2fsck $(facet_active_host $SINGLEMDS) \
2503                 $(mdsdevname 1) "-n" || error "Running e2fsck")
2504
2505         for ((index=0; index<$total; index++)); do
2506                 facet=$(echo ${affecteds[index]} | tr -s " " | cut -d"," -f 1)
2507                 echo reboot facets: ${affecteds[index]}
2508
2509                 reboot_facet $facet
2510
2511                 change_active ${affecteds[index]}
2512
2513                 wait_for_facet ${affecteds[index]}
2514                 # start mgs first if it is affected
2515                 if ! combined_mgs_mds &&
2516                         list_member ${affecteds[index]} mgs; then
2517                         mount_facet mgs || error "Restart of mgs failed"
2518                 fi
2519                 # FIXME; has to be changed to mount all facets concurrently
2520                 affected=$(exclude_items_from_list ${affecteds[index]} mgs)
2521                 echo mount facets: ${affecteds[index]}
2522                 mount_facets ${affecteds[index]}
2523         done
2524 }
2525
2526 obd_name() {
2527     local facet=$1
2528 }
2529
2530 replay_barrier() {
2531         local facet=$1
2532         do_facet $facet "sync; sync; sync"
2533         df $MOUNT
2534
2535         # make sure there will be no seq change
2536         local clients=${CLIENTS:-$HOSTNAME}
2537         local f=fsa-\\\$\(hostname\)
2538         do_nodes $clients "mcreate $MOUNT/$f; rm $MOUNT/$f"
2539         do_nodes $clients "if [ -d $MOUNT2 ]; then mcreate $MOUNT2/$f; rm $MOUNT2/$f; fi"
2540
2541         local svc=${facet}_svc
2542         do_facet $facet $LCTL --device ${!svc} notransno
2543         #
2544         # If a ZFS OSD is made read-only here, its pool is "freezed". This
2545         # in-memory state has to be cleared by either rebooting the host or
2546         # exporting and reimporting the pool.
2547         #
2548         # Although the uberblocks are not updated when a pool is freezed,
2549         # transactions are still written to the disks. Modified blocks may be
2550         # cached in memory when tests try reading them back. The
2551         # export-and-reimport process also evicts any cached pool data from
2552         # memory to provide the correct "data loss" semantics.
2553         #
2554         # In the test framework, the exporting and importing operations are
2555         # handled by stop() and mount_facet() separately, which are used
2556         # inside fail() and fail_abort().
2557         #
2558         do_facet $facet $LCTL --device ${!svc} readonly
2559         do_facet $facet $LCTL mark "$HOSTNAME: $facet REPLAY BARRIER on ${!svc}"
2560         $LCTL mark "$HOSTNAME: local REPLAY BARRIER on ${!svc}"
2561 }
2562
2563 replay_barrier_nodf() {
2564         local facet=$1    echo running=${running}
2565         do_facet $facet "sync; sync; sync"
2566         local svc=${facet}_svc
2567         echo Replay barrier on ${!svc}
2568         do_facet $facet $LCTL --device ${!svc} notransno
2569         do_facet $facet $LCTL --device ${!svc} readonly
2570         do_facet $facet $LCTL mark "$HOSTNAME: $facet REPLAY BARRIER on ${!svc}"
2571         $LCTL mark "$HOSTNAME: local REPLAY BARRIER on ${!svc}"
2572 }
2573
2574 replay_barrier_nosync() {
2575         local facet=$1    echo running=${running}
2576         local svc=${facet}_svc
2577         echo Replay barrier on ${!svc}
2578         do_facet $facet $LCTL --device ${!svc} notransno
2579         do_facet $facet $LCTL --device ${!svc} readonly
2580         do_facet $facet $LCTL mark "$HOSTNAME: $facet REPLAY BARRIER on ${!svc}"
2581         $LCTL mark "$HOSTNAME: local REPLAY BARRIER on ${!svc}"
2582 }
2583
2584 #
2585 # Get Lustre client uuid for a given Lustre mount point.
2586 #
2587 get_client_uuid() {
2588         local mntpnt=${1:-$MOUNT}
2589
2590         local name=$($LFS getname $mntpnt | cut -d' ' -f1)
2591         local uuid=$($LCTL get_param -n llite.$name.uuid)
2592
2593         echo -n $uuid
2594 }
2595
2596 mds_evict_client() {
2597         local mntpnt=${1:-$MOUNT}
2598         local uuid=$(get_client_uuid $mntpnt)
2599
2600         do_facet $SINGLEMDS \
2601                 "$LCTL set_param -n mdt.${mds1_svc}.evict_client $uuid"
2602 }
2603
2604 ost_evict_client() {
2605         local mntpnt=${1:-$MOUNT}
2606         local uuid=$(get_client_uuid $mntpnt)
2607
2608         do_facet ost1 \
2609                 "$LCTL set_param -n obdfilter.${ost1_svc}.evict_client $uuid"
2610 }
2611
2612 fail() {
2613         local facets=$1
2614         local clients=${CLIENTS:-$HOSTNAME}
2615
2616         facet_failover $* || error "failover: $?"
2617         wait_clients_import_state "$clients" "$facets" FULL
2618         clients_up || error "post-failover df: $?"
2619 }
2620
2621 fail_nodf() {
2622         local facet=$1
2623         facet_failover $facet
2624 }
2625
2626 fail_abort() {
2627         local facet=$1
2628         stop $facet
2629         change_active $facet
2630         wait_for_facet $facet
2631         mount_facet $facet -o abort_recovery
2632         clients_up || echo "first df failed: $?"
2633         clients_up || error "post-failover df: $?"
2634 }
2635
2636 do_lmc() {
2637     echo There is no lmc.  This is mountconf, baby.
2638     exit 1
2639 }
2640
2641 host_nids_address() {
2642     local nodes=$1
2643     local kind=$2
2644
2645     if [ -n "$kind" ]; then
2646         nids=$(do_nodes $nodes "$LCTL list_nids | grep $kind | cut -f 1 -d '@'")
2647     else
2648         nids=$(do_nodes $nodes "$LCTL list_nids all | cut -f 1 -d '@'")
2649     fi
2650     echo $nids
2651 }
2652
2653 h2name_or_ip() {
2654         if [ "$1" = "'*'" ]; then echo \'*\'; else
2655                 echo $1"@$2"
2656         fi
2657 }
2658
2659 h2ptl() {
2660         if [ "$1" = "'*'" ]; then echo \'*\'; else
2661                 ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | \
2662                                                         awk '{print $1}'`
2663                 if [ -z "$ID" ]; then
2664                         echo "Could not get a ptl id for $1..."
2665                         exit 1
2666                 fi
2667                 echo $ID"@ptl"
2668         fi
2669 }
2670 declare -fx h2ptl
2671
2672 h2tcp() {
2673         h2name_or_ip "$1" "tcp"
2674 }
2675 declare -fx h2tcp
2676
2677 h2elan() {
2678         if [ "$1" = "'*'" ]; then echo \'*\'; else
2679                 if type __h2elan >/dev/null 2>&1; then
2680                         ID=$(__h2elan $1)
2681                 else
2682                         ID=`echo $1 | sed 's/[^0-9]*//g'`
2683                 fi
2684                 echo $ID"@elan"
2685         fi
2686 }
2687 declare -fx h2elan
2688
2689 h2o2ib() {
2690         h2name_or_ip "$1" "o2ib"
2691 }
2692 declare -fx h2o2ib
2693
2694 # This enables variables in cfg/"setup".sh files to support the pdsh HOSTLIST
2695 # expressions format. As a bonus we can then just pass in those variables
2696 # to pdsh. What this function does is take a HOSTLIST type string and
2697 # expand it into a space deliminated list for us.
2698 hostlist_expand() {
2699     local hostlist=$1
2700     local offset=$2
2701     local myList
2702     local item
2703     local list
2704
2705     [ -z "$hostlist" ] && return
2706
2707     # Translate the case of [..],..,[..] to [..] .. [..]
2708     list="${hostlist/],/] }"
2709     front=${list%%[*}
2710     [[ "$front" == *,* ]] && {
2711         new="${list%,*} "
2712         old="${list%,*},"
2713         list=${list/${old}/${new}}
2714     }
2715
2716     for item in $list; do
2717         # Test if we have any []'s at all
2718         if [ "$item" != "${item/\[/}" ]; then {
2719             # Expand the [*] into list
2720             name=${item%%[*}
2721             back=${item#*]}
2722
2723             if [ "$name" != "$item" ]; then
2724                 group=${item#$name[*}
2725                 group=${group%%]*}
2726
2727                 for range in ${group//,/ }; do
2728                     begin=${range%-*}
2729                     end=${range#*-}
2730
2731                     # Number of leading zeros
2732                     padlen=${#begin}
2733                     padlen2=${#end}
2734                     end=$(echo $end | sed 's/0*//')
2735                     [[ -z "$end" ]] && end=0
2736                     [[ $padlen2 -gt $padlen ]] && {
2737                         [[ $padlen2 -eq ${#end} ]] && padlen2=0
2738                         padlen=$padlen2
2739                     }
2740                     begin=$(echo $begin | sed 's/0*//')
2741                     [ -z $begin ] && begin=0
2742
2743                     for num in $(seq -f "%0${padlen}g" $begin $end); do
2744                         value="${name#*,}${num}${back}"
2745                         [ "$value" != "${value/\[/}" ] && {
2746                             value=$(hostlist_expand "$value")
2747                         }
2748                         myList="$myList $value"
2749                     done
2750                 done
2751             fi
2752         } else {
2753             myList="$myList $item"
2754         } fi
2755     done
2756     myList=${myList//,/ }
2757     myList=${myList:1} # Remove first character which is a space
2758
2759     # Filter any duplicates without sorting
2760     list="$myList "
2761     myList="${list%% *}"
2762
2763     while [[ "$list" != ${myList##* } ]]; do
2764         list=${list//${list%% *} /}
2765         myList="$myList ${list%% *}"
2766     done
2767     myList="${myList%* }";
2768
2769     # We can select an object at an offset in the list
2770     [ $# -eq 2 ] && {
2771         cnt=0
2772         for item in $myList; do
2773             let cnt=cnt+1
2774             [ $cnt -eq $offset ] && {
2775                 myList=$item
2776             }
2777         done
2778         [ $(get_node_count $myList) -ne 1 ] && myList=""
2779     }
2780     echo $myList
2781 }
2782
2783 facet_host() {
2784         local facet=$1
2785         local varname
2786
2787         [ "$facet" == client ] && echo -n $HOSTNAME && return
2788         varname=${facet}_HOST
2789         if [ -z "${!varname}" ]; then
2790                 if [ "${facet:0:3}" == "ost" ]; then
2791                         local fh=${facet%failover}_HOST
2792                         eval export ${facet}_HOST=${!fh}
2793                         if [ -z "${!varname}" ]; then
2794                                 eval export ${facet}_HOST=${ost_HOST}
2795                         fi
2796                 elif [ "${facet:0:3}" == "mdt" -o \
2797                         "${facet:0:3}" == "mds" -o \
2798                         "${facet:0:3}" == "mgs" ]; then
2799                         eval export ${facet}_HOST=${mds_HOST}
2800                 fi
2801         fi
2802         echo -n ${!varname}
2803 }
2804
2805 facet_failover_host() {
2806         local facet=$1
2807         local varname
2808
2809         var=${facet}failover_HOST
2810         if [ -n "${!var}" ]; then
2811                 echo ${!var}
2812                 return
2813         fi
2814
2815         if [ "${facet:0:3}" == "mdt" -o "${facet:0:3}" == "mds" -o \
2816              "${facet:0:3}" == "mgs" ]; then
2817
2818                 eval export ${facet}failover_host=${mds_HOST}
2819                 echo ${mds_HOST}
2820                 return
2821         fi
2822
2823         if [[ $facet == ost* ]]; then
2824                 eval export ${facet}failover_host=${ost_HOST}
2825                 echo ${ost_HOST}
2826                 return
2827         fi
2828 }
2829
2830 facet_active() {
2831     local facet=$1
2832     local activevar=${facet}active
2833
2834     if [ -f $TMP/${facet}active ] ; then
2835         source $TMP/${facet}active
2836     fi
2837
2838     active=${!activevar}
2839     if [ -z "$active" ] ; then
2840         echo -n ${facet}
2841     else
2842         echo -n ${active}
2843     fi
2844 }
2845
2846 facet_active_host() {
2847         facet_host $(facet_active $1)
2848 }
2849
2850 # Get the passive failover partner host of facet.
2851 facet_passive_host() {
2852         local facet=$1
2853         [[ $facet = client ]] && return
2854
2855         local host=${facet}_HOST
2856         local failover_host=${facet}failover_HOST
2857         local active_host=$(facet_active_host $facet)
2858
2859         [[ -z ${!failover_host} || ${!failover_host} = ${!host} ]] && return
2860
2861         if [[ $active_host = ${!host} ]]; then
2862                 echo -n ${!failover_host}
2863         else
2864                 echo -n ${!host}
2865         fi
2866 }
2867
2868 change_active() {
2869     local facetlist=$1
2870     local facet
2871
2872     facetlist=$(exclude_items_from_list $facetlist mgs)
2873
2874     for facet in ${facetlist//,/ }; do
2875     local failover=${facet}failover
2876     local host=`facet_host $failover`
2877     [ -z "$host" ] && return
2878
2879     local curactive=`facet_active $facet`
2880     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
2881         eval export ${facet}active=$facet
2882     else
2883         eval export ${facet}active=$failover
2884     fi
2885     # save the active host for this facet
2886     local activevar=${facet}active
2887     echo "$activevar=${!activevar}" > $TMP/$activevar
2888     [[ $facet = mds1 ]] && combined_mgs_mds && \
2889         echo "mgsactive=${!activevar}" > $TMP/mgsactive
2890     local TO=`facet_active_host $facet`
2891     echo "Failover $facet to $TO"
2892     done
2893 }
2894
2895 do_node() {
2896         local verbose=false
2897         # do not stripe off hostname if verbose, bug 19215
2898         if [ x$1 = x--verbose ]; then
2899                 shift
2900                 verbose=true
2901         fi
2902
2903         local HOST=$1
2904         shift
2905         local myPDSH=$PDSH
2906         if [ "$HOST" = "$HOSTNAME" ]; then
2907                 myPDSH="no_dsh"
2908         elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
2909                 echo "cannot run remote command on $HOST with $myPDSH"
2910                 return 128
2911         fi
2912         if $VERBOSE; then
2913                 echo "CMD: $HOST $@" >&2
2914                 $myPDSH $HOST "$LCTL mark \"$HOSTNAME: $@\"" &>/dev/null || :
2915         fi
2916
2917     if [ "$myPDSH" = "rsh" ]; then
2918 # we need this because rsh does not return exit code of an executed command
2919         local command_status="$TMP/cs"
2920         rsh $HOST ":> $command_status"
2921         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
2922                     cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
2923                     echo command failed >$command_status"
2924         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
2925         return 0
2926     fi
2927
2928     if $verbose ; then
2929         # print HOSTNAME for myPDSH="no_dsh"
2930         if [[ $myPDSH = no_dsh ]]; then
2931             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
2932         else
2933             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
2934         fi
2935     else
2936         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
2937     fi
2938     return ${PIPESTATUS[0]}
2939 }
2940
2941 do_nodev() {
2942     do_node --verbose "$@"
2943 }
2944
2945 single_local_node () {
2946    [ "$1" = "$HOSTNAME" ]
2947 }
2948
2949 # Outputs environment variable assignments that should be passed to remote nodes
2950 get_env_vars() {
2951         local var
2952         local value
2953         local facets=$(get_facets)
2954         local facet
2955
2956         for var in ${!MODOPTS_*}; do
2957                 value=${!var//\"/\\\"}
2958                 echo -n " ${var}=\"$value\""
2959         done
2960
2961         for facet in ${facets//,/ }; do
2962                 var=${facet}_FSTYPE
2963                 if [ -n "${!var}" ]; then
2964                         echo -n " $var=${!var}"
2965                 fi
2966         done
2967
2968         for var in MGSFSTYPE MDSFSTYPE OSTFSTYPE; do
2969                 if [ -n "${!var}" ]; then
2970                         echo -n " $var=${!var}"
2971                 fi
2972         done
2973
2974         for var in VERBOSE; do
2975                 if [ -n "${!var}" ]; then
2976                         echo -n " $var=${!var}"
2977                 fi
2978         done
2979
2980         if [ -n "$FSTYPE" ]; then
2981                 echo -n " FSTYPE=$FSTYPE"
2982         fi
2983
2984         for var in LNETLND NETTYPE; do
2985                 if [ -n "${!var}" ]; then
2986                         echo -n " $var=${!var}"
2987                 fi
2988         done
2989 }
2990
2991 do_nodes() {
2992     local verbose=false
2993     # do not stripe off hostname if verbose, bug 19215
2994     if [ x$1 = x--verbose ]; then
2995         shift
2996         verbose=true
2997     fi
2998
2999     local rnodes=$1
3000     shift
3001
3002     if single_local_node $rnodes; then
3003         if $verbose; then
3004            do_nodev $rnodes "$@"
3005         else
3006            do_node $rnodes "$@"
3007         fi
3008         return $?
3009     fi
3010
3011         # This is part from do_node
3012         local myPDSH=$PDSH
3013
3014         [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] &&
3015                 echo "cannot run remote command on $rnodes with $myPDSH" &&
3016                 return 128
3017
3018         export FANOUT=$(get_node_count "${rnodes//,/ }")
3019         if $VERBOSE; then
3020                 echo "CMD: $rnodes $@" >&2
3021                 $myPDSH $rnodes "$LCTL mark \"$HOSTNAME: $@\"" &>/dev/null || :
3022         fi
3023
3024     # do not replace anything from pdsh output if -N is used
3025     # -N     Disable hostname: prefix on lines of output.
3026     if $verbose || [[ $myPDSH = *-N* ]]; then
3027         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")"
3028     else
3029         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")" | sed -re "s/^[^:]*: //g"
3030     fi
3031     return ${PIPESTATUS[0]}
3032 }
3033
3034 ##
3035 # Execute commands on a single service's host
3036 #
3037 # The \a facet (service) may be on a local or remote node, which is
3038 # determined at the time the command is run.
3039 #
3040 # usage: do_facet $facet command [arg ...]
3041 do_facet() {
3042         local facet=$1
3043         shift
3044         local HOST=$(facet_active_host $facet)
3045         [ -z $HOST ] && echo "No host defined for facet ${facet}" && exit 1
3046         do_node $HOST "$@"
3047 }
3048
3049 # Function: do_facet_random_file $FACET $FILE $SIZE
3050 # Creates FILE with random content on the given FACET of given SIZE
3051
3052 do_facet_random_file() {
3053         local facet="$1"
3054         local fpath="$2"
3055         local fsize="$3"
3056         local cmd="dd if=/dev/urandom of='$fpath' bs=$fsize count=1"
3057         do_facet $facet "$cmd 2>/dev/null"
3058 }
3059
3060 do_facet_create_file() {
3061         local facet="$1"
3062         local fpath="$2"
3063         local fsize="$3"
3064         local cmd="dd if=/dev/zero of='$fpath' bs=$fsize count=1"
3065         do_facet $facet "$cmd 2>/dev/null"
3066 }
3067
3068 do_nodesv() {
3069     do_nodes --verbose "$@"
3070 }
3071
3072 add() {
3073         local facet=$1
3074         shift
3075         # make sure its not already running
3076         stop ${facet} -f
3077         rm -f $TMP/${facet}active
3078         [[ $facet = mds1 ]] && combined_mgs_mds && rm -f $TMP/mgsactive
3079         do_facet ${facet} $MKFS $* || return ${PIPESTATUS[0]}
3080
3081         if [[ $(facet_fstype $facet) == zfs ]]; then
3082                 #
3083                 # After formatting a ZFS target, "cachefile=none" property will
3084                 # be set on the ZFS storage pool so that the pool is not
3085                 # automatically imported on system startup. And then the pool
3086                 # will be exported so as to leave the importing and exporting
3087                 # operations handled by mount_facet() and stop() separately.
3088                 #
3089                 refresh_partition_table $facet $(facet_vdevice $facet)
3090                 disable_zpool_cache $facet
3091                 export_zpool $facet
3092         fi
3093 }
3094
3095 # Device formatted as ost
3096 ostdevname() {
3097         local num=$1
3098         local DEVNAME=OSTDEV$num
3099
3100         local fstype=$(facet_fstype ost$num)
3101
3102         case $fstype in
3103                 ldiskfs )
3104                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
3105                         eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
3106                 zfs )
3107                         #try $OSTZFSDEVn - independent of vdev
3108                         DEVNAME=OSTZFSDEV$num
3109                         eval DEVPTR=${!DEVNAME:=${FSNAME}-ost${num}/ost${num}};;
3110                 * )
3111                         error "unknown fstype!";;
3112         esac
3113
3114     echo -n $DEVPTR
3115 }
3116
3117 # Physical device location of data
3118 ostvdevname() {
3119         local num=$1
3120         local DEVNAME
3121         local VDEVPTR
3122
3123         local fstype=$(facet_fstype ost$num)
3124
3125         case $fstype in
3126                 ldiskfs )
3127                         # vdevs are not supported by ldiskfs
3128                         eval VDEVPTR="";;
3129                 zfs )
3130                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE{n}
3131                         # Device formatted by zfs
3132                         DEVNAME=OSTDEV$num
3133                         eval VDEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
3134                 * )
3135                         error "unknown fstype!";;
3136         esac
3137
3138         echo -n $VDEVPTR
3139 }
3140
3141 # Logical device formatted for lustre
3142 mdsdevname() {
3143         local num=$1
3144         local DEVNAME=MDSDEV$num
3145
3146         local fstype=$(facet_fstype mds$num)
3147
3148         case $fstype in
3149                 ldiskfs )
3150                         #if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
3151                         eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
3152                 zfs )
3153                         # try $MDSZFSDEVn - independent of vdev
3154                         DEVNAME=MDSZFSDEV$num
3155                         eval DEVPTR=${!DEVNAME:=${FSNAME}-mdt${num}/mdt${num}};;
3156                 * )
3157                         error "unknown fstype!";;
3158         esac
3159
3160         echo -n $DEVPTR
3161 }
3162
3163 # Physical location of data
3164 mdsvdevname() {
3165         local VDEVPTR=""
3166         local num=$1
3167         local fstype=$(facet_fstype mds$num)
3168
3169         case $fstype in
3170                 ldiskfs )
3171                         # vdevs are not supported by ldiskfs
3172                         eval VDEVPTR="";;
3173                 zfs )
3174                         # if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
3175                         # Device formatted by ZFS
3176                         local DEVNAME=MDSDEV$num
3177                         eval VDEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
3178                 * )
3179                         error "unknown fstype!";;
3180         esac
3181
3182         echo -n $VDEVPTR
3183 }
3184
3185 mgsdevname() {
3186         local DEVPTR
3187         local fstype=$(facet_fstype mgs)
3188
3189         case $fstype in
3190         ldiskfs )
3191                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3192                    ( [ -z "$MGSDEV" ] || [ $MGSDEV = $(mdsdevname 1) ] ); then
3193                         DEVPTR=$(mdsdevname 1)
3194                 else
3195                         DEVPTR=$MGSDEV
3196                 fi;;
3197         zfs )
3198                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3199                     ( [ -z "$MGSZFSDEV" ] &&
3200                         [ -z "$MGSDEV" -o "$MGSDEV" = $(mdsvdevname 1) ] ); then
3201                         DEVPTR=$(mdsdevname 1)
3202                 else
3203                         DEVPTR=${MGSZFSDEV:-${FSNAME}-mgs/mgs}
3204                 fi;;
3205         * )
3206                 error "unknown fstype!";;
3207         esac
3208
3209         echo -n $DEVPTR
3210 }
3211
3212 mgsvdevname() {
3213         local VDEVPTR=""
3214
3215         local fstype=$(facet_fstype mgs)
3216
3217         case $fstype in
3218         ldiskfs )
3219                 # vdevs are not supported by ldiskfs
3220                 ;;
3221         zfs )
3222                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3223                    ( [ -z "$MGSDEV" ] &&
3224                        [ -z "$MGSZFSDEV" -o "$MGSZFSDEV" = $(mdsdevname 1) ]); then
3225                         VDEVPTR=$(mdsvdevname 1)
3226                 elif [ -n "$MGSDEV" ]; then
3227                         VDEVPTR=$MGSDEV
3228                 fi;;
3229         * )
3230                 error "unknown fstype!";;
3231         esac
3232
3233         echo -n $VDEVPTR
3234 }
3235
3236 facet_mntpt () {
3237     local facet=$1
3238     [[ $facet = mgs ]] && combined_mgs_mds && facet="mds1"
3239
3240     local var=${facet}_MOUNT
3241     eval mntpt=${!var:-${MOUNT%/*}/$facet}
3242
3243     echo -n $mntpt
3244 }
3245
3246 mount_ldiskfs() {
3247         local facet=$1
3248         local dev=$(facet_device $facet)
3249         local mnt=$(facet_mntpt $facet)
3250         local opts
3251
3252         if ! do_facet $facet test -b $dev; then
3253                 opts="-o loop"
3254         fi
3255         do_facet $facet mount -t ldiskfs $opts $dev $mnt
3256 }
3257
3258 unmount_ldiskfs() {
3259         local facet=$1
3260         local dev=$(facet_device $facet)
3261         local mnt=$(facet_mntpt $facet)
3262
3263         do_facet $facet $UMOUNT $mnt
3264 }
3265
3266 var_name() {
3267         echo -n "$1" | tr -c '[:alnum:]\n' '_'
3268 }
3269
3270 mount_zfs() {
3271         local facet=$1
3272         local ds=$(facet_device $facet)
3273         local mnt=$(facet_mntpt $facet)
3274         local canmnt
3275         local mntpt
3276
3277         import_zpool $facet
3278         canmnt=$(do_facet $facet $ZFS get -H -o value canmount $ds)
3279         mntpt=$(do_facet $facet $ZFS get -H -o value mountpoint $ds)
3280         do_facet $facet $ZFS set canmount=noauto $ds
3281         #
3282         # The "legacy" mount method is used here because "zfs unmount $mnt"
3283         # calls stat(2) on $mnt/../*, which may include $MOUNT.  If certain
3284         # targets are not available at the time, the stat(2) on $MOUNT will
3285         # hang.
3286         #
3287         do_facet $facet $ZFS set mountpoint=legacy $ds
3288         do_facet $facet mount -t zfs $ds $mnt
3289         eval export mz_$(var_name ${facet}_$ds)_canmount=$canmnt
3290         eval export mz_$(var_name ${facet}_$ds)_mountpoint=$mntpt
3291 }
3292
3293 unmount_zfs() {
3294         local facet=$1
3295         local ds=$(facet_device $facet)
3296         local mnt=$(facet_mntpt $facet)
3297         local var_mntpt=mz_$(var_name ${facet}_$ds)_mountpoint
3298         local var_canmnt=mz_$(var_name ${facet}_$ds)_canmount
3299         local mntpt=${!var_mntpt}
3300         local canmnt=${!var_canmnt}
3301
3302         unset $var_mntpt
3303         unset $var_canmnt
3304         do_facet $facet umount $mnt
3305         do_facet $facet $ZFS set mountpoint=$mntpt $ds
3306         do_facet $facet $ZFS set canmount=$canmnt $ds
3307         export_zpool $facet
3308 }
3309
3310 mount_fstype() {
3311         local facet=$1
3312         local fstype=$(facet_fstype $facet)
3313
3314         mount_$fstype $facet
3315 }
3316
3317 unmount_fstype() {
3318         local facet=$1
3319         local fstype=$(facet_fstype $facet)
3320
3321         unmount_$fstype $facet
3322 }
3323
3324 ########
3325 ## MountConf setup
3326
3327 stopall() {
3328     # make sure we are using the primary server, so test-framework will
3329     # be able to clean up properly.
3330     activemds=`facet_active mds1`
3331     if [ $activemds != "mds1" ]; then
3332         fail mds1
3333     fi
3334
3335     local clients=$CLIENTS
3336     [ -z $clients ] && clients=$(hostname)
3337
3338     zconf_umount_clients $clients $MOUNT "$*" || true
3339     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
3340
3341     [ "$CLIENTONLY" ] && return
3342     # The add fn does rm ${facet}active file, this would be enough
3343     # if we use do_facet <facet> only after the facet added, but
3344     # currently we use do_facet mds in local.sh
3345     for num in `seq $MDSCOUNT`; do
3346         stop mds$num -f
3347         rm -f ${TMP}/mds${num}active
3348     done
3349     combined_mgs_mds && rm -f $TMP/mgsactive
3350
3351     for num in `seq $OSTCOUNT`; do
3352         stop ost$num -f
3353         rm -f $TMP/ost${num}active
3354     done
3355
3356     if ! combined_mgs_mds ; then
3357         stop mgs
3358     fi
3359
3360     return 0
3361 }
3362
3363 cleanup_echo_devs () {
3364     local devs=$($LCTL dl | grep echo | awk '{print $4}')
3365
3366     for dev in $devs; do
3367         $LCTL --device $dev cleanup
3368         $LCTL --device $dev detach
3369     done
3370 }
3371
3372 cleanupall() {
3373     nfs_client_mode && return
3374         cifs_client_mode && return
3375
3376     stopall $*
3377     cleanup_echo_devs
3378
3379     unload_modules
3380     cleanup_gss
3381 }
3382
3383 combined_mgs_mds () {
3384         [[ "$(mdsdevname 1)" = "$(mgsdevname)" ]] &&
3385                 [[ "$(facet_host mds1)" = "$(facet_host mgs)" ]]
3386 }
3387
3388 lower() {
3389         echo -n "$1" | tr '[:upper:]' '[:lower:]'
3390 }
3391
3392 upper() {
3393         echo -n "$1" | tr '[:lower:]' '[:upper:]'
3394 }
3395
3396 mkfs_opts() {
3397         local facet=$1
3398         local dev=$2
3399         local fsname=${3:-"$FSNAME"}
3400         local type=$(facet_type $facet)
3401         local index=$(facet_index $facet)
3402         local fstype=$(facet_fstype $facet)
3403         local host=$(facet_host $facet)
3404         local opts
3405         local fs_mkfs_opts
3406         local var
3407
3408         if [ $type == MGS ] || ( [ $type == MDS ] &&
3409                                  [ "$dev" == $(mgsdevname) ] &&
3410                                  [ "$host" == "$(facet_host mgs)" ] ); then
3411                 opts="--mgs"
3412         else
3413                 opts="--mgsnode=$MGSNID"
3414         fi
3415
3416         if [ $type != MGS ]; then
3417                 opts+=" --fsname=$fsname --$(lower ${type/MDS/MDT}) \
3418                         --index=$index"
3419         fi
3420
3421         var=${facet}failover_HOST
3422         if [ -n "${!var}" ] && [ ${!var} != $(facet_host $facet) ]; then
3423                 opts+=" --failnode=$(h2$NETTYPE ${!var})"
3424         fi
3425
3426         opts+=${TIMEOUT:+" --param=sys.timeout=$TIMEOUT"}
3427         opts+=${LDLM_TIMEOUT:+" --param=sys.ldlm_timeout=$LDLM_TIMEOUT"}
3428
3429         if [ $type == MDS ]; then
3430                 opts+=${SECLEVEL:+" --param=mdt.sec_level"}
3431                 opts+=${MDSCAPA:+" --param-mdt.capa=$MDSCAPA"}
3432                 opts+=${STRIPE_BYTES:+" --param=lov.stripesize=$STRIPE_BYTES"}
3433                 opts+=${STRIPES_PER_OBJ:+" --param=lov.stripecount=$STRIPES_PER_OBJ"}
3434                 opts+=${L_GETIDENTITY:+" --param=mdt.identity_upcall=$L_GETIDENTITY"}
3435
3436                 if [ $fstype == ldiskfs ]; then
3437                         # Check for wide striping
3438                         if [ $OSTCOUNT -gt 160 ]; then
3439                                 MDSJOURNALSIZE=${MDSJOURNALSIZE:-4096}
3440                                 fs_mkfs_opts+="-O large_xattr"
3441                         fi
3442
3443                         var=${facet}_JRN
3444                         if [ -n "${!var}" ]; then
3445                                 fs_mkfs_opts+=" -J device=${!var}"
3446                         else
3447                                 fs_mkfs_opts+=${MDSJOURNALSIZE:+" -J size=$MDSJOURNALSIZE"}
3448                         fi
3449                         fs_mkfs_opts+=${MDSISIZE:+" -i $MDSISIZE"}
3450                 fi
3451         fi
3452
3453         if [ $type == OST ]; then
3454                 opts+=${SECLEVEL:+" --param=ost.sec_level"}
3455                 opts+=${OSSCAPA:+" --param=ost.capa=$OSSCAPA"}
3456
3457                 if [ $fstype == ldiskfs ]; then
3458                         var=${facet}_JRN
3459                         if [ -n "${!var}" ]; then
3460                                 fs_mkfs_opts+=" -J device=${!var}"
3461                         else
3462                                 fs_mkfs_opts+=${OSTJOURNALSIZE:+" -J size=$OSTJOURNALSIZE"}
3463                         fi
3464                 fi
3465         fi
3466
3467         opts+=" --backfstype=$fstype"
3468
3469         var=${type}SIZE
3470         if [ -n "${!var}" ]; then
3471                 opts+=" --device-size=${!var}"
3472         fi
3473
3474         var=$(upper $fstype)_MKFS_OPTS
3475         fs_mkfs_opts+=${!var:+" ${!var}"}
3476
3477         var=${type}_FS_MKFS_OPTS
3478         fs_mkfs_opts+=${!var:+" ${!var}"}
3479
3480         if [ -n "${fs_mkfs_opts## }" ]; then
3481                 opts+=" --mkfsoptions=\\\"${fs_mkfs_opts## }\\\""
3482         fi
3483
3484         var=${type}OPT
3485         opts+=${!var:+" ${!var}"}
3486
3487         echo -n "$opts"
3488 }
3489
3490 check_ost_indices() {
3491         local index_count=${#OST_INDICES[@]}
3492         [[ $index_count -eq 0 || $OSTCOUNT -le $index_count ]] && return 0
3493
3494         # OST count is greater than the index count in $OST_INDEX_LIST.
3495         # We need check whether there are duplicate indices.
3496         local i
3497         local j
3498         local index
3499         for i in $(seq $((index_count + 1)) $OSTCOUNT); do
3500                 index=$(facet_index ost$i)
3501                 for j in $(seq 0 $((index_count - 1))); do
3502                         [[ $index -ne ${OST_INDICES[j]} ]] ||
3503                         error "ost$i has the same index $index as ost$((j+1))"
3504                 done
3505         done
3506 }
3507
3508 format_mgs() {
3509         local quiet
3510
3511         if ! $VERBOSE; then
3512                 quiet=yes
3513         fi
3514         echo "Format mgs: $(mgsdevname)"
3515         reformat_external_journal mgs
3516         add mgs $(mkfs_opts mgs $(mgsdevname)) --reformat \
3517                 $(mgsdevname) $(mgsvdevname) ${quiet:+>/dev/null} || exit 10
3518 }
3519
3520 format_mdt() {
3521         local num=$1
3522         local quiet
3523
3524         if ! $VERBOSE; then
3525                 quiet=yes
3526         fi
3527         echo "Format mds$num: $(mdsdevname $num)"
3528         reformat_external_journal mds$num
3529         add mds$num $(mkfs_opts mds$num $(mdsdevname ${num})) \
3530                 --reformat $(mdsdevname $num) $(mdsvdevname $num) \
3531                 ${quiet:+>/dev/null} || exit 10
3532 }
3533
3534 format_ost() {
3535         local num=$1
3536
3537         if ! $VERBOSE; then
3538                 quiet=yes
3539         fi
3540         echo "Format ost$num: $(ostdevname $num)"
3541         reformat_external_journal ost$num
3542         add ost$num $(mkfs_opts ost$num $(ostdevname ${num})) \
3543                 --reformat $(ostdevname $num) $(ostvdevname ${num}) \
3544                 ${quiet:+>/dev/null} || exit 10
3545 }
3546
3547 formatall() {
3548         stopall
3549         # Set hostid for ZFS/SPL zpool import protection
3550         do_rpc_nodes "$(comma_list $(remote_nodes_list))" set_hostid
3551
3552         # We need ldiskfs here, may as well load them all
3553         load_modules
3554         [ "$CLIENTONLY" ] && return
3555         echo Formatting mgs, mds, osts
3556         if ! combined_mgs_mds ; then
3557                 format_mgs
3558         fi
3559
3560         for num in $(seq $MDSCOUNT); do
3561                 format_mdt $num
3562         done
3563
3564         export OST_INDICES=($(hostlist_expand "$OST_INDEX_LIST"))
3565         check_ost_indices
3566         for num in $(seq $OSTCOUNT); do
3567                 format_ost $num
3568         done
3569 }
3570
3571 mount_client() {
3572     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
3573 }
3574
3575 umount_client() {
3576     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
3577 }
3578
3579 # return value:
3580 # 0: success, the old identity set already.
3581 # 1: success, the old identity does not set.
3582 # 2: fail.
3583 switch_identity() {
3584     local num=$1
3585     local switch=$2
3586     local j=`expr $num - 1`
3587     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
3588
3589     if [ -z "$MDT" ]; then
3590         return 2
3591     fi
3592
3593     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
3594
3595     if $switch; then
3596         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
3597     else
3598         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
3599     fi
3600
3601     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush=-1"
3602
3603     if [ $old = "NONE" ]; then
3604         return 1
3605     else
3606         return 0
3607     fi
3608 }
3609
3610 remount_client()
3611 {
3612         zconf_umount `hostname` $1 || error "umount failed"
3613         zconf_mount `hostname` $1 || error "mount failed"
3614 }
3615
3616 writeconf_facet() {
3617         local facet=$1
3618         local dev=$2
3619
3620         stop ${facet} -f
3621         rm -f $TMP/${facet}active
3622         do_facet ${facet} "$TUNEFS --quiet --writeconf $dev" || return 1
3623         return 0
3624 }
3625
3626 writeconf_all () {
3627         local mdt_count=${1:-$MDSCOUNT}
3628         local ost_count=${2:-$OSTCOUNT}
3629         local rc=0
3630
3631         for num in $(seq $mdt_count); do
3632                 DEVNAME=$(mdsdevname $num)
3633                 writeconf_facet mds$num $DEVNAME || rc=$?
3634         done
3635
3636         for num in $(seq $ost_count); do
3637                 DEVNAME=$(ostdevname $num)
3638                 writeconf_facet ost$num $DEVNAME || rc=$?
3639         done
3640         return $rc
3641 }
3642
3643 setupall() {
3644     nfs_client_mode && return
3645         cifs_client_mode && return
3646
3647     sanity_mount_check ||
3648         error "environments are insane!"
3649
3650     load_modules
3651
3652     if [ -z "$CLIENTONLY" ]; then
3653         echo Setup mgs, mdt, osts
3654         echo $WRITECONF | grep -q "writeconf" && \
3655             writeconf_all
3656         if ! combined_mgs_mds ; then
3657                         start mgs $(mgsdevname) $MGS_MOUNT_OPTS
3658         fi
3659
3660         for num in `seq $MDSCOUNT`; do
3661             DEVNAME=$(mdsdevname $num)
3662             start mds$num $DEVNAME $MDS_MOUNT_OPTS
3663
3664             # We started mds, now we should set failover variables properly.
3665             # Set mds${num}failover_HOST if it is not set (the default failnode).
3666             local varname=mds${num}failover_HOST
3667             if [ -z "${!varname}" ]; then
3668                 eval mds${num}failover_HOST=$(facet_host mds$num)
3669             fi
3670
3671             if [ $IDENTITY_UPCALL != "default" ]; then
3672                 switch_identity $num $IDENTITY_UPCALL
3673             fi
3674         done
3675         for num in `seq $OSTCOUNT`; do
3676             DEVNAME=$(ostdevname $num)
3677             start ost$num $DEVNAME $OST_MOUNT_OPTS
3678
3679             # We started ost$num, now we should set ost${num}failover variable properly.
3680             # Set ost${num}failover_HOST if it is not set (the default failnode).
3681             varname=ost${num}failover_HOST
3682             if [ -z "${!varname}" ]; then
3683                 eval ost${num}failover_HOST=$(facet_host ost${num})
3684             fi
3685
3686         done
3687     fi
3688
3689     init_gss
3690
3691     # wait a while to allow sptlrpc configuration be propogated to targets,
3692     # only needed when mounting new target devices.
3693     if $GSS; then
3694         sleep 10
3695     fi
3696
3697     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
3698     mount_client $MOUNT
3699     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
3700     clients_up
3701
3702     if [ "$MOUNT_2" ]; then
3703         mount_client $MOUNT2
3704         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
3705     fi
3706
3707     init_param_vars
3708
3709     # by remounting mdt before ost, initial connect from mdt to ost might
3710     # timeout because ost is not ready yet. wait some time to its fully
3711     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
3712     # by a context negotiation rpc with $TIMEOUT.
3713     # FIXME better by monitoring import status.
3714     if $GSS; then
3715         set_flavor_all $SEC
3716         sleep $((TIMEOUT + 5))
3717     else
3718         sleep 5
3719     fi
3720 }
3721
3722 mounted_lustre_filesystems() {
3723         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
3724 }
3725
3726 init_facet_vars () {
3727         [ "$CLIENTONLY" ] && return 0
3728         local facet=$1
3729         shift
3730         local device=$1
3731
3732         shift
3733
3734         eval export ${facet}_dev=${device}
3735         eval export ${facet}_opt=\"$@\"
3736
3737         local dev=${facet}_dev
3738
3739         # We need to loop for the label
3740         # in case its not initialized yet.
3741         for wait_time in {0,1,3,5,10}; do
3742
3743                 if [ $wait_time -gt 0 ]; then
3744                         echo "${!dev} not yet initialized,"\
3745                                 "waiting ${wait_time} seconds."
3746                         sleep $wait_time
3747                 fi
3748
3749                 local label=$(devicelabel ${facet} ${!dev})
3750
3751                 # Check to make sure the label does
3752                 # not include ffff at the end of the label.
3753                 # This indicates it has not been initialized yet.
3754
3755                 if [[ $label =~ [f|F]{4}$ ]]; then
3756                         # label is not initialized, unset the result
3757                         # and either try again or fail
3758                         unset label
3759                 else
3760                         break
3761                 fi
3762         done
3763
3764         [ -z "$label" ] && echo no label for ${!dev} && exit 1
3765
3766         eval export ${facet}_svc=${label}
3767
3768         local varname=${facet}failover_HOST
3769         if [ -z "${!varname}" ]; then
3770                 eval export $varname=$(facet_host $facet)
3771         fi
3772
3773         varname=${facet}_HOST
3774         if [ -z "${!varname}" ]; then
3775                 eval export $varname=$(facet_host $facet)
3776         fi
3777
3778         # ${facet}failover_dev is set in cfg file
3779         varname=${facet}failover_dev
3780         if [ -n "${!varname}" ] ; then
3781                 eval export ${facet}failover_dev=${!varname}
3782         else
3783                 eval export ${facet}failover_dev=$device
3784         fi
3785
3786         # get mount point of already mounted device
3787         # is facet_dev is already mounted then use the real
3788         #  mount point of this facet; otherwise use $(facet_mntpt $facet)
3789         # i.e. ${facet}_MOUNT if specified by user or default
3790         local mntpt=$(do_facet ${facet} cat /proc/mounts | \
3791                         awk '"'${!dev}'" == $1 && $3 == "lustre" { print $2 }')
3792         if [ -z $mntpt ]; then
3793                 mntpt=$(facet_mntpt $facet)
3794         fi
3795         eval export ${facet}_MOUNT=$mntpt
3796 }
3797
3798 init_facets_vars () {
3799         local DEVNAME
3800
3801         if ! remote_mds_nodsh; then
3802                 for num in $(seq $MDSCOUNT); do
3803                         DEVNAME=`mdsdevname $num`
3804                         init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
3805                 done
3806         fi
3807
3808         combined_mgs_mds || init_facet_vars mgs $(mgsdevname) $MGS_MOUNT_OPTS
3809
3810         if ! remote_ost_nodsh; then
3811                 for num in $(seq $OSTCOUNT); do
3812                         DEVNAME=$(ostdevname $num)
3813                         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
3814                 done
3815         fi
3816 }
3817
3818 osc_ensure_active () {
3819     local facet=$1
3820     local timeout=$2
3821     local period=0
3822
3823     while [ $period -lt $timeout ]; do
3824         count=$(do_facet $facet "lctl dl | grep ' IN osc ' 2>/dev/null | wc -l")
3825         if [ $count -eq 0 ]; then
3826             break
3827         fi
3828
3829         echo "There are $count OST are inactive, wait $period seconds, and try again"
3830         sleep 3
3831         period=$((period+3))
3832     done
3833
3834     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
3835 }
3836
3837 set_conf_param_and_check() {
3838         local myfacet=$1
3839         local TEST=$2
3840         local PARAM=$3
3841         local ORIG=$(do_facet $myfacet "$TEST")
3842         if [ $# -gt 3 ]; then
3843                 local FINAL=$4
3844         else
3845                 local -i FINAL
3846                 FINAL=$((ORIG + 5))
3847         fi
3848         echo "Setting $PARAM from $ORIG to $FINAL"
3849         do_facet mgs "$LCTL conf_param $PARAM='$FINAL'" ||
3850                 error "conf_param $PARAM failed"
3851
3852         wait_update $(facet_host $myfacet) "$TEST" "$FINAL" ||
3853                 error "check $PARAM failed!"
3854 }
3855
3856 init_param_vars () {
3857         remote_mds_nodsh ||
3858                 TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
3859
3860         log "Using TIMEOUT=$TIMEOUT"
3861
3862         osc_ensure_active $SINGLEMDS $TIMEOUT
3863         osc_ensure_active client $TIMEOUT
3864
3865         if [ -n "$(lctl get_param -n mdc.*.connect_flags|grep jobstats)" ]; then
3866                 local current_jobid_var=$($LCTL get_param -n jobid_var)
3867
3868                 if [ $JOBID_VAR = "existing" ]; then
3869                         echo "keeping jobstats as $current_jobid_var"
3870                 elif [ $current_jobid_var != $JOBID_VAR ]; then
3871                         echo "seting jobstats to $JOBID_VAR"
3872
3873                         set_conf_param_and_check client                 \
3874                                 "$LCTL get_param -n jobid_var"          \
3875                                 "$FSNAME.sys.jobid_var" $JOBID_VAR
3876                 fi
3877         else
3878                 echo "jobstats not supported by server"
3879         fi
3880
3881         if [ $QUOTA_AUTO -ne 0 ]; then
3882                 if [ "$ENABLE_QUOTA" ]; then
3883                         echo "enable quota as required"
3884                         setup_quota $MOUNT || return 2
3885                 else
3886                         echo "disable quota as required"
3887                         # $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
3888                 fi
3889         fi
3890         return 0
3891 }
3892
3893 nfs_client_mode () {
3894     if [ "$NFSCLIENT" ]; then
3895         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
3896         local clients=$CLIENTS
3897         [ -z $clients ] && clients=$(hostname)
3898
3899         # FIXME: remove hostname when 19215 fixed
3900         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
3901         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
3902         if [[ ${#nfsexport[@]} -eq 0 ]]; then
3903                 error_exit NFSCLIENT=$NFSCLIENT mode, but no NFS export found!
3904         fi
3905         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
3906         return
3907     fi
3908     return 1
3909 }
3910
3911 cifs_client_mode () {
3912         [ x$CIFSCLIENT = xyes ] &&
3913                 echo "CIFSCLIENT=$CIFSCLIENT mode: setup, cleanup, check config skipped"
3914 }
3915
3916 check_config_client () {
3917     local mntpt=$1
3918
3919     local mounted=$(mount | grep " $mntpt ")
3920     if [ "$CLIENTONLY" ]; then
3921         # bug 18021
3922         # CLIENTONLY should not depend on *_HOST settings
3923         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
3924         # in theory someone could create a new,
3925         # client-only config file that assumed lustre was already
3926         # configured and didn't set the MGSNID. If MGSNID is not set,
3927         # then we should use the mgs nid currently being used 
3928         # as the default value. bug 18021
3929         [[ x$MGSNID = x ]] &&
3930             MGSNID=${mgc//MGC/}
3931
3932         if [[ x$mgc != xMGC$MGSNID ]]; then
3933             if [ "$mgs_HOST" ]; then
3934                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
3935 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
3936 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
3937             fi
3938         fi
3939         return 0
3940     fi
3941
3942     local myMGS_host=$mgs_HOST   
3943     if [ "$NETTYPE" = "ptl" ]; then
3944         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
3945     fi
3946
3947     echo Checking config lustre mounted on $mntpt
3948     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
3949     mgshost=$(echo $mgshost | awk -F: '{print $1}')
3950
3951 #    if [ "$mgshost" != "$myMGS_host" ]; then
3952 #            log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
3953 #                   Please use correct config or set mds_HOST correctly!"
3954 #    fi
3955
3956 }
3957
3958 check_config_clients () {
3959         local clients=${CLIENTS:-$HOSTNAME}
3960         local mntpt=$1
3961
3962         nfs_client_mode && return
3963         cifs_client_mode && return
3964
3965         do_rpc_nodes "$clients" check_config_client $mntpt
3966
3967         sanity_mount_check || error "environments are insane!"
3968 }
3969
3970 check_timeout () {
3971     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
3972     local cltimeout=$(lctl get_param -n timeout)
3973     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
3974         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
3975         return 1
3976     fi
3977 }
3978
3979 is_mounted () {
3980     local mntpt=$1
3981     [ -z $mntpt ] && return 1
3982     local mounted=$(mounted_lustre_filesystems)
3983
3984     echo $mounted' ' | grep -w -q $mntpt' '
3985 }
3986
3987 is_empty_dir() {
3988         [ $(find $1 -maxdepth 1 -print | wc -l) = 1 ] && return 0
3989         return 1
3990 }
3991
3992 # empty lustre filesystem may have empty directories lost+found and .lustre
3993 is_empty_fs() {
3994         # exclude .lustre & lost+found
3995         [ $(find $1 -maxdepth 1 -name lost+found -o -name .lustre -prune -o \
3996                 -print | wc -l) = 1 ] || return 1
3997         [ ! -d $1/lost+found ] || is_empty_dir $1/lost+found || return 1
3998         if [ $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.4.0) ]; then
3999                 # exclude .lustre/fid (LU-2780)
4000                 [ $(find $1/.lustre -maxdepth 1 -name fid -prune -o \
4001                         -print | wc -l) = 1 ] || return 1
4002         else
4003                 [ ! -d $1/.lustre ] || is_empty_dir $1/.lustre || return 1
4004         fi
4005         return 0
4006 }
4007
4008 check_and_setup_lustre() {
4009         sanitize_parameters
4010         nfs_client_mode && return
4011         cifs_client_mode && return
4012
4013         local MOUNTED=$(mounted_lustre_filesystems)
4014
4015         local do_check=true
4016         # 1.
4017         # both MOUNT and MOUNT2 are not mounted
4018         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
4019                 [ "$REFORMAT" = "yes" ] && formatall
4020                 # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
4021                 setupall
4022                 is_mounted $MOUNT || error "NAME=$NAME not mounted"
4023                 export I_MOUNTED=yes
4024                 do_check=false
4025     # 2.
4026     # MOUNT2 is mounted
4027     elif is_mounted $MOUNT2; then
4028             # 3.
4029             # MOUNT2 is mounted, while MOUNT_2 is not set
4030             if ! [ "$MOUNT_2" ]; then
4031                 cleanup_mount $MOUNT2
4032                 export I_UMOUNTED2=yes
4033
4034             # 4.
4035             # MOUNT2 is mounted, MOUNT_2 is set
4036             else
4037                 # FIXME: what to do if check_config failed?
4038                 # i.e. if:
4039                 # 1) remote client has mounted other Lustre fs ?
4040                 # 2) it has insane env ?
4041                 # let's try umount MOUNT2 on all clients and mount it again:
4042                 if ! check_config_clients $MOUNT2; then
4043                     cleanup_mount $MOUNT2
4044                     restore_mount $MOUNT2
4045                     export I_MOUNTED2=yes
4046                 fi
4047             fi 
4048
4049     # 5.
4050     # MOUNT is mounted MOUNT2 is not mounted
4051     elif [ "$MOUNT_2" ]; then
4052         restore_mount $MOUNT2
4053         export I_MOUNTED2=yes
4054     fi
4055
4056     if $do_check; then
4057         # FIXME: what to do if check_config failed?
4058         # i.e. if:
4059         # 1) remote client has mounted other Lustre fs?
4060         # 2) lustre is mounted on remote_clients atall ?
4061         check_config_clients $MOUNT
4062         init_facets_vars
4063         init_param_vars
4064
4065         set_default_debug_nodes $(comma_list $(nodes_list))
4066     fi
4067
4068         if [ $(lower $OSD_TRACK_DECLARES_LBUG) == 'yes' ] ; then
4069                 local facets=""
4070                 [ "$(facet_fstype ost1)" = "ldiskfs" ] &&
4071                         facets="$(get_facets OST)"
4072                 [ "$(facet_fstype mds1)" = "ldiskfs" ] &&
4073                         facets="$facets,$(get_facets MDS)"
4074                 [ "$(facet_fstype mgs)" = "ldiskfs" ] &&
4075                         facets="$facets,mgs"
4076                 local nodes="$(facets_hosts ${facets})"
4077                 if [ -n "$nodes" ] ; then
4078                         do_nodes $nodes "$LCTL set_param \
4079                                  osd-ldiskfs.track_declares_assert=1 || true"
4080                 fi
4081         fi
4082
4083         init_gss
4084         if $GSS; then
4085                 set_flavor_all $SEC
4086         fi
4087
4088         #Enable remote MDT create for testing
4089         for num in $(seq $MDSCOUNT); do
4090                 do_facet mds$num \
4091                         lctl set_param -n mdt.${FSNAME}*.enable_remote_dir=1 \
4092                                 2>/dev/null
4093         done
4094
4095         if [ "$ONLY" == "setup" ]; then
4096                 exit 0
4097         fi
4098 }
4099
4100 restore_mount () {
4101    local clients=${CLIENTS:-$HOSTNAME}
4102    local mntpt=$1
4103
4104    zconf_mount_clients $clients $mntpt
4105 }
4106
4107 cleanup_mount () {
4108         local clients=${CLIENTS:-$HOSTNAME}
4109         local mntpt=$1
4110
4111         zconf_umount_clients $clients $mntpt
4112 }
4113
4114 cleanup_and_setup_lustre() {
4115     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
4116         lctl set_param debug=0 || true
4117         cleanupall
4118         if [ "$ONLY" == "cleanup" ]; then
4119             exit 0
4120         fi
4121     fi
4122     check_and_setup_lustre
4123 }
4124
4125 # Get all of the server target devices from a given server node and type.
4126 get_mnt_devs() {
4127         local node=$1
4128         local type=$2
4129         local devs
4130         local dev
4131
4132         if [ "$type" == ost ]; then
4133                 devs=$(get_osd_param $node "" mntdev)
4134         else
4135                 devs=$(do_node $node $LCTL get_param -n osd-*.$FSNAME-M*.mntdev)
4136         fi
4137         for dev in $devs; do
4138                 case $dev in
4139                 *loop*) do_node $node "losetup $dev" | \
4140                                 sed -e "s/.*(//" -e "s/).*//" ;;
4141                 *) echo $dev ;;
4142                 esac
4143         done
4144 }
4145
4146 # Get all of the server target devices.
4147 get_svr_devs() {
4148         local node
4149         local i
4150
4151         # Master MDS parameters used by lfsck
4152         MDTNODE=$(facet_active_host $SINGLEMDS)
4153         MDTDEV=$(echo $(get_mnt_devs $MDTNODE mdt) | awk '{print $1}')
4154
4155         # MDT devices
4156         i=0
4157         for node in $(mdts_nodes); do
4158                 MDTDEVS[i]=$(get_mnt_devs $node mdt)
4159                 i=$((i + 1))
4160         done
4161
4162         # OST devices
4163         i=0
4164         for node in $(osts_nodes); do
4165                 OSTDEVS[i]=$(get_mnt_devs $node ost)
4166                 i=$((i + 1))
4167         done
4168 }
4169
4170 # Run e2fsck on MDT or OST device.
4171 run_e2fsck() {
4172         local node=$1
4173         local target_dev=$2
4174         local extra_opts=$3
4175         local cmd="$E2FSCK -d -v -t -t -f $extra_opts $target_dev"
4176         local log=$TMP/e2fsck.log
4177         local rc=0
4178
4179         echo $cmd
4180         do_node $node $cmd 2>&1 | tee $log
4181         rc=${PIPESTATUS[0]}
4182         if [ -n "$(grep "DNE mode isn't supported" $log)" ]; then
4183                 rm -f $log
4184                 if [ $MDSCOUNT -gt 1 ]; then
4185                         skip "DNE mode isn't supported!"
4186                         cleanupall
4187                         exit_status
4188                 else
4189                         error "It's not DNE mode."
4190                 fi
4191         fi
4192         rm -f $log
4193
4194         [ $rc -le $FSCK_MAX_ERR ] ||
4195                 error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
4196
4197         return 0
4198 }
4199
4200 #
4201 # Run resize2fs on MDT or OST device.
4202 #
4203 run_resize2fs() {
4204         local facet=$1
4205         local device=$2
4206         local size=$3
4207         shift 3
4208         local opts="$@"
4209
4210         do_facet $facet "$RESIZE2FS $opts $device $size"
4211 }
4212
4213 # verify a directory is shared among nodes.
4214 check_shared_dir() {
4215         local dir=$1
4216         local list=${2:-$(comma_list $(nodes_list))}
4217
4218         [ -z "$dir" ] && return 1
4219         do_rpc_nodes "$list" check_logdir $dir
4220         check_write_access $dir "$list" || return 1
4221         return 0
4222 }
4223
4224 run_lfsck() {
4225         do_nodes $(comma_list $(mdts_nodes) $(osts_nodes)) \
4226                 $LCTL set_param printk=+lfsck
4227         do_facet $SINGLEMDS "$LCTL lfsck_start -M $FSNAME-MDT0000 -r -A -t all"
4228
4229         for k in $(seq $MDSCOUNT); do
4230                 # wait up to 10+1 minutes for LFSCK to complete
4231                 wait_update_facet --verbose mds${k} "$LCTL get_param -n \
4232                         mdd.$(facet_svc mds${k}).lfsck_layout |
4233                         awk '/^status/ { print \\\$2 }'" "completed" 600 ||
4234                         error "MDS${k} layout isn't the expected 'completed'"
4235                 wait_update_facet --verbose mds${k} "$LCTL get_param -n \
4236                         mdd.$(facet_svc mds${k}).lfsck_namespace |
4237                         awk '/^status/ { print \\\$2 }'" "completed" 60 ||
4238                         error "MDS${k} namespace isn't the expected 'completed'"
4239         done
4240         local rep_mdt=$(do_nodes $(comma_list $(mdts_nodes)) \
4241                         $LCTL get_param -n mdd.$FSNAME-*.lfsck_* |
4242                         awk '/repaired/ { print $2 }' | calc_sum)
4243         local rep_ost=$(do_nodes $(comma_list $(osts_nodes)) \
4244                         $LCTL get_param -n obdfilter.$FSNAME-*.lfsck_* |
4245                         awk '/repaired/ { print $2 }' | calc_sum)
4246         local repaired=$((rep_mdt + rep_ost))
4247         [ $repaired -eq 0 ] ||
4248                 error "lfsck repaired $rep_mdt MDT and $rep_ost OST errors"
4249 }
4250
4251 dump_file_contents() {
4252         local nodes=$1
4253         local dir=$2
4254         local logname=$3
4255         local node
4256
4257         if [ -z "$nodes" -o -z "$dir" -o -z "$logname" ]; then
4258                 error_noexit false \
4259                         "Invalid parameters for dump_file_contents()"
4260                 return 1
4261         fi
4262         for node in ${nodes}; do
4263                 do_node $node "for i in \\\$(find $dir -type f); do
4264                                 echo ====\\\${i}=======================;
4265                                 cat \\\${i};
4266                                 done" >> ${logname}.${node}.log
4267         done
4268 }
4269
4270 dump_command_output() {
4271         local nodes=$1
4272         local cmd=$2
4273         local logname=$3
4274         local node
4275
4276         if [ -z "$nodes" -o -z "$cmd" -o -z "$logname" ]; then
4277                 error_noexit false \
4278                         "Invalid parameters for dump_command_output()"
4279                 return 1
4280         fi
4281
4282         for node in ${nodes}; do
4283                 do_node $node "echo ====${cmd}=======================;
4284                                 $cmd" >> ${logname}.${node}.log
4285         done
4286 }
4287
4288 log_zfs_info() {
4289         local logname=$1
4290
4291         # dump file contents from /proc/spl in case of zfs test
4292         if [ "$(facet_fstype ost1)" = "zfs" ]; then
4293                 dump_file_contents "$(osts_nodes)" "/proc/spl" "${logname}"
4294                 dump_command_output \
4295                         "$(osts_nodes)" "zpool events -v" "${logname}"
4296         fi
4297
4298         if [ "$(facet_fstype $SINGLEMDS)" = "zfs" ]; then
4299                 dump_file_contents "$(mdts_nodes)" "/proc/spl" "${logname}"
4300                 dump_command_output \
4301                         "$(mdts_nodes)" "zpool events -v" "${logname}"
4302         fi
4303 }
4304
4305 check_and_cleanup_lustre() {
4306         if [ "$LFSCK_ALWAYS" = "yes" -a "$TESTSUITE" != "sanity-lfsck" -a \
4307              "$TESTSUITE" != "sanity-scrub" ]; then
4308                 run_lfsck
4309         fi
4310
4311         if is_mounted $MOUNT; then
4312                 [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]* ||
4313                         error "remove sub-test dirs failed"
4314                 [ "$ENABLE_QUOTA" ] && restore_quota || true
4315         fi
4316
4317         if [ "$I_UMOUNTED2" = "yes" ]; then
4318                 restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
4319         fi
4320
4321         if [ "$I_MOUNTED2" = "yes" ]; then
4322                 cleanup_mount $MOUNT2
4323         fi
4324
4325         if [ "$I_MOUNTED" = "yes" ]; then
4326                 cleanupall -f || error "cleanup failed"
4327                 unset I_MOUNTED
4328         fi
4329 }
4330
4331 #######
4332 # General functions
4333
4334 wait_for_function () {
4335     local quiet=""
4336
4337     # suppress fn both stderr and stdout
4338     if [ "$1" = "--quiet" ]; then
4339         shift
4340         quiet=" > /dev/null 2>&1"
4341
4342     fi
4343
4344     local fn=$1
4345     local max=${2:-900}
4346     local sleep=${3:-5}
4347
4348     local wait=0
4349
4350     while true; do
4351
4352         eval $fn $quiet && return 0
4353
4354         wait=$((wait + sleep))
4355         [ $wait -lt $max ] || return 1
4356         echo waiting $fn, $((max - wait)) secs left ...
4357         sleep $sleep
4358     done
4359 }
4360
4361 check_network() {
4362     local host=$1
4363     local max=$2
4364     local sleep=${3:-5}
4365
4366     echo `date +"%H:%M:%S (%s)"` waiting for $host network $max secs ...
4367     if ! wait_for_function --quiet "ping -c 1 -w 3 $host" $max $sleep ; then
4368         echo "Network not available!"
4369         exit 1
4370     fi
4371
4372     echo `date +"%H:%M:%S (%s)"` network interface is UP
4373 }
4374
4375 no_dsh() {
4376     shift
4377     eval $@
4378 }
4379
4380 # Convert a space-delimited list to a comma-delimited list.  If the input is
4381 # only whitespace, ensure the output is empty (i.e. "") so [ -n $list ] works
4382 comma_list() {
4383         # echo is used to convert newlines to spaces, since it doesn't
4384         # introduce a trailing space as using "tr '\n' ' '" does
4385         echo $(tr -s " " "\n" <<< $* | sort -b -u) | tr ' ' ','
4386 }
4387
4388 list_member () {
4389     local list=$1
4390     local item=$2
4391     echo $list | grep -qw $item
4392 }
4393
4394 # list, excluded are the comma separated lists
4395 exclude_items_from_list () {
4396     local list=$1
4397     local excluded=$2
4398     local item
4399
4400     list=${list//,/ }
4401     for item in ${excluded//,/ }; do
4402         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
4403     done
4404     echo $(comma_list $list)
4405 }
4406
4407 # list, expand  are the comma separated lists
4408 expand_list () {
4409     local list=${1//,/ }
4410     local expand=${2//,/ }
4411     local expanded=
4412
4413     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
4414     echo $(comma_list $expanded)
4415 }
4416
4417 testslist_filter () {
4418     local script=$LUSTRE/tests/${TESTSUITE}.sh
4419
4420     [ -f $script ] || return 0
4421
4422     local start_at=$START_AT
4423     local stop_at=$STOP_AT
4424
4425     local var=${TESTSUITE//-/_}_START_AT
4426     [ x"${!var}" != x ] && start_at=${!var}
4427     var=${TESTSUITE//-/_}_STOP_AT
4428     [ x"${!var}" != x ] && stop_at=${!var}
4429
4430     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
4431         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
4432             /^'${start_at}'$/ {flag = 0}
4433             {if (flag == 1) print $0}
4434             /^'${stop_at}'$/ { flag = 1 }'
4435 }
4436
4437 absolute_path() {
4438     (cd `dirname $1`; echo $PWD/`basename $1`)
4439 }
4440
4441 get_facets () {
4442     local types=${1:-"OST MDS MGS"}
4443
4444     local list=""
4445
4446     for entry in $types; do
4447         local name=$(echo $entry | tr "[:upper:]" "[:lower:]")
4448         local type=$(echo $entry | tr "[:lower:]" "[:upper:]")
4449
4450         case $type in
4451                 MGS ) list="$list $name";;
4452             MDS|OST|AGT ) local count=${type}COUNT
4453                        for ((i=1; i<=${!count}; i++)) do
4454                           list="$list ${name}$i"
4455                       done;;
4456                   * ) error "Invalid facet type"
4457                  exit 1;;
4458         esac
4459     done
4460     echo $(comma_list $list)
4461 }
4462
4463 ##################################
4464 # Adaptive Timeouts funcs
4465
4466 at_is_enabled() {
4467     # only check mds, we assume at_max is the same on all nodes
4468     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
4469     if [ $at_max -eq 0 ]; then
4470         return 1
4471     else
4472         return 0
4473     fi
4474 }
4475
4476 at_get() {
4477     local facet=$1
4478     local at=$2
4479
4480     # suppose that all ost-s have the same $at value set
4481     [ $facet != "ost" ] || facet=ost1
4482
4483     do_facet $facet "lctl get_param -n $at"
4484 }
4485
4486 at_max_get() {
4487     at_get $1 at_max
4488 }
4489
4490 at_min_get() {
4491         at_get $1 at_min
4492 }
4493
4494 at_max_set() {
4495     local at_max=$1
4496     shift
4497
4498     local facet
4499     local hosts
4500     for facet in $@; do
4501         if [ $facet == "ost" ]; then
4502             facet=$(get_facets OST)
4503         elif [ $facet == "mds" ]; then
4504             facet=$(get_facets MDS)
4505         fi
4506         hosts=$(expand_list $hosts $(facets_hosts $facet))
4507     done
4508
4509     do_nodes $hosts lctl set_param at_max=$at_max
4510 }
4511
4512 ##################################
4513 # OBD_FAIL funcs
4514
4515 drop_request() {
4516 # OBD_FAIL_MDS_ALL_REQUEST_NET
4517     RC=0
4518     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
4519     do_facet client "$1" || RC=$?
4520     do_facet $SINGLEMDS lctl set_param fail_loc=0
4521     return $RC
4522 }
4523
4524 drop_reply() {
4525 # OBD_FAIL_MDS_ALL_REPLY_NET
4526         RC=0
4527         do_facet $SINGLEMDS $LCTL set_param fail_loc=0x122
4528         eval "$@" || RC=$?
4529         do_facet $SINGLEMDS $LCTL set_param fail_loc=0
4530         return $RC
4531 }
4532
4533 drop_reint_reply() {
4534 # OBD_FAIL_MDS_REINT_NET_REP
4535         RC=0
4536         do_facet $SINGLEMDS $LCTL set_param fail_loc=0x119
4537         eval "$@" || RC=$?
4538         do_facet $SINGLEMDS $LCTL set_param fail_loc=0
4539         return $RC
4540 }
4541
4542 drop_update_reply() {
4543 # OBD_FAIL_OUT_UPDATE_NET_REP
4544         local index=$1
4545         shift 1
4546         RC=0
4547         do_facet mds${index} lctl set_param fail_loc=0x1701
4548         do_facet client "$@" || RC=$?
4549         do_facet mds${index} lctl set_param fail_loc=0
4550         return $RC
4551 }
4552
4553 pause_bulk() {
4554 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
4555         RC=0
4556
4557         local timeout=${2:-0}
4558         # default is (obd_timeout / 4) if unspecified
4559         echo "timeout is $timeout/$2"
4560         do_facet ost1 lctl set_param fail_val=$timeout fail_loc=0x80000214
4561         do_facet client "$1" || RC=$?
4562         do_facet client "sync"
4563         do_facet ost1 lctl set_param fail_loc=0
4564         return $RC
4565 }
4566
4567 drop_ldlm_cancel() {
4568 #define OBD_FAIL_LDLM_CANCEL_NET                        0x304
4569         local RC=0
4570         local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4571         do_nodes $list lctl set_param fail_loc=0x304
4572
4573         do_facet client "$@" || RC=$?
4574
4575         do_nodes $list lctl set_param fail_loc=0
4576         return $RC
4577 }
4578
4579 drop_bl_callback_once() {
4580         local rc=0
4581         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0
4582 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
4583         do_facet client lctl set_param fail_loc=0x80000305
4584         do_facet client "$@" || rc=$?
4585         do_facet client lctl set_param fail_loc=0
4586         do_facet client lctl set_param fail_val=0
4587         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1
4588         return $rc
4589 }
4590
4591 drop_bl_callback() {
4592         rc=0
4593         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0
4594 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
4595         do_facet client lctl set_param fail_loc=0x305
4596         do_facet client "$@" || rc=$?
4597         do_facet client lctl set_param fail_loc=0
4598         do_facet client lctl set_param fail_val=0
4599         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1
4600         return $rc
4601 }
4602
4603 drop_ldlm_reply() {
4604 #define OBD_FAIL_LDLM_REPLY              0x30c
4605     RC=0
4606     local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4607     do_nodes $list lctl set_param fail_loc=0x30c
4608
4609     do_facet client "$@" || RC=$?
4610
4611     do_nodes $list lctl set_param fail_loc=0
4612     return $RC
4613 }
4614
4615 drop_ldlm_reply_once() {
4616 #define OBD_FAIL_LDLM_REPLY              0x30c
4617     RC=0
4618     local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4619     do_nodes $list lctl set_param fail_loc=0x8000030c
4620
4621     do_facet client "$@" || RC=$?
4622
4623     do_nodes $list lctl set_param fail_loc=0
4624     return $RC
4625 }
4626
4627 clear_failloc() {
4628     facet=$1
4629     pause=$2
4630     sleep $pause
4631     echo "clearing fail_loc on $facet"
4632     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
4633 }
4634
4635 set_nodes_failloc () {
4636         do_nodes $(comma_list $1)  lctl set_param fail_val=0 fail_loc=$2
4637 }
4638
4639 cancel_lru_locks() {
4640         #$LCTL mark "$HOSTNAME: cancel_lru_locks $1 start"
4641         $LCTL set_param -n ldlm.namespaces.*$1*.lru_size=clear
4642         $LCTL get_param ldlm.namespaces.*$1*.lock_unused_count | grep -v '=0'
4643         #$LCTL mark "$HOSTNAME: cancel_lru_locks $1 stop"
4644 }
4645
4646 default_lru_size()
4647 {
4648         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
4649         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
4650         echo "$DEFAULT_LRU_SIZE"
4651 }
4652
4653 lru_resize_enable()
4654 {
4655     lctl set_param ldlm.namespaces.*$1*.lru_size=0
4656 }
4657
4658 lru_resize_disable()
4659 {
4660     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
4661 }
4662
4663 flock_is_enabled()
4664 {
4665         local RC=0
4666         [ -z "$(mount | grep "$MOUNT.*flock" | grep -v noflock)" ] && RC=1
4667         return $RC
4668 }
4669
4670 pgcache_empty() {
4671     local FILE
4672     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
4673         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
4674             echo there is still data in page cache $FILE ?
4675             lctl get_param -n $FILE
4676             return 1
4677         fi
4678     done
4679     return 0
4680 }
4681
4682 debugsave() {
4683     DEBUGSAVE="$(lctl get_param -n debug)"
4684 }
4685
4686 debugrestore() {
4687     [ -n "$DEBUGSAVE" ] && \
4688         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
4689     DEBUGSAVE=""
4690 }
4691
4692 debug_size_save() {
4693     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
4694 }
4695
4696 debug_size_restore() {
4697     [ -n "$DEBUG_SIZE_SAVED" ] && \
4698         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
4699     DEBUG_SIZE_SAVED=""
4700 }
4701
4702 start_full_debug_logging() {
4703     debugsave
4704     debug_size_save
4705
4706     local FULLDEBUG=-1
4707     local DEBUG_SIZE=150
4708
4709     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
4710     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
4711 }
4712
4713 stop_full_debug_logging() {
4714     debug_size_restore
4715     debugrestore
4716 }
4717
4718 # prints bash call stack
4719 print_stack_trace() {
4720         local skip=${1:-1}
4721         echo "  Trace dump:"
4722         for (( i=$skip; i < ${#BASH_LINENO[*]} ; i++ )) ; do
4723                 local src=${BASH_SOURCE[$i]}
4724                 local lineno=${BASH_LINENO[$i-1]}
4725                 local funcname=${FUNCNAME[$i]}
4726                 echo "  = $src:$lineno:$funcname()"
4727         done
4728 }
4729
4730 report_error() {
4731         local TYPE=${TYPE:-"FAIL"}
4732
4733         local dump=true
4734         # do not dump logs if $1=false
4735         if [ "x$1" = "xfalse" ]; then
4736                 shift
4737                 dump=false
4738         fi
4739
4740         log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
4741         (print_stack_trace 2) >&2
4742         mkdir -p $LOGDIR
4743         # We need to dump the logs on all nodes
4744         if $dump; then
4745                 gather_logs $(comma_list $(nodes_list))
4746         fi
4747
4748         debugrestore
4749         [ "$TESTSUITELOG" ] &&
4750                 echo "$TESTSUITE: $TYPE: $TESTNAME $@" >> $TESTSUITELOG
4751         if [ -z "$*" ]; then
4752                 echo "error() without useful message, please fix" > $LOGDIR/err
4753         else
4754                 if [[ `echo $TYPE | grep ^IGNORE` ]]; then
4755                         echo "$@" > $LOGDIR/ignore
4756                 else
4757                         echo "$@" > $LOGDIR/err
4758                 fi
4759         fi
4760
4761         # cleanup the env for failed tests
4762         reset_fail_loc
4763 }
4764
4765 ##################################
4766 # Test interface
4767 ##################################
4768
4769 error_noexit() {
4770         report_error "$@"
4771 }
4772
4773 exit_status () {
4774         local status=0
4775         local log=$TESTSUITELOG
4776
4777         [ -f "$log" ] && grep -q FAIL $log && status=1
4778         exit $status
4779 }
4780
4781 error() {
4782         report_error "$@"
4783         exit 1
4784 }
4785
4786 error_exit() {
4787         report_error "$@"
4788         exit 1
4789 }
4790
4791 # use only if we are ignoring failures for this test, bugno required.
4792 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
4793 # e.g. error_ignore bz5494 "your message" or
4794 # error_ignore LU-5494 "your message"
4795 error_ignore() {
4796         local TYPE="IGNORE ($1)"
4797         shift
4798         report_error "$@"
4799 }
4800
4801 error_and_remount() {
4802         report_error "$@"
4803         remount_client $MOUNT
4804         exit 1
4805 }
4806
4807 skip_env () {
4808         $FAIL_ON_SKIP_ENV && error false $@ || skip $@
4809 }
4810
4811 skip() {
4812         echo
4813         log " SKIP: $TESTSUITE $TESTNAME $@"
4814
4815         if [[ -n "$ALWAYS_SKIPPED" ]]; then
4816                 skip_logged $TESTNAME "$@"
4817         else
4818                 mkdir -p $LOGDIR
4819                 echo "$@" > $LOGDIR/skip
4820         fi
4821
4822         [[ -n "$TESTSUITELOG" ]] &&
4823                 echo "$TESTSUITE: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
4824 }
4825
4826 build_test_filter() {
4827     EXCEPT="$EXCEPT $(testslist_filter)"
4828
4829         for O in $ONLY; do
4830                 if [[ $O = [0-9]*-[0-9]* ]]; then
4831                         for num in $(seq $(echo $O | tr '-' ' ')); do
4832                                 eval ONLY_$num=true
4833                         done
4834                 else
4835                         eval ONLY_${O}=true
4836                 fi
4837         done
4838
4839     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
4840         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
4841     [ "$EXCEPT_SLOW" ] && \
4842         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
4843     for E in $EXCEPT; do
4844         eval EXCEPT_${E}=true
4845     done
4846     for E in $ALWAYS_EXCEPT; do
4847         eval EXCEPT_ALWAYS_${E}=true
4848     done
4849     for E in $EXCEPT_SLOW; do
4850         eval EXCEPT_SLOW_${E}=true
4851     done
4852     for G in $GRANT_CHECK_LIST; do
4853         eval GCHECK_ONLY_${G}=true
4854         done
4855 }
4856
4857 basetest() {
4858     if [[ $1 = [a-z]* ]]; then
4859         echo $1
4860     else
4861         echo ${1%%[a-z]*}
4862     fi
4863 }
4864
4865 # print a newline if the last test was skipped
4866 export LAST_SKIPPED=
4867 export ALWAYS_SKIPPED=
4868 #
4869 # Main entry into test-framework. This is called with the name and
4870 # description of a test. The name is used to find the function to run
4871 # the test using "test_$name".
4872 #
4873 # This supports a variety of methods of specifying specific test to
4874 # run or not run.  These need to be documented...
4875 #
4876 run_test() {
4877         assert_DIR
4878
4879         export base=$(basetest $1)
4880         if [ -n "$ONLY" ]; then
4881                 testname=ONLY_$1
4882                 if [ ${!testname}x != x ]; then
4883                         [ -n "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
4884                         run_one_logged $1 "$2"
4885                         return $?
4886                 fi
4887                 testname=ONLY_$base
4888                 if [ ${!testname}x != x ]; then
4889                         [ -n "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
4890                         run_one_logged $1 "$2"
4891                         return $?
4892                 fi
4893                 LAST_SKIPPED="y"
4894                 return 0
4895         fi
4896
4897         LAST_SKIPPED="y"
4898         ALWAYS_SKIPPED="y"
4899         testname=EXCEPT_$1
4900         if [ ${!testname}x != x ]; then
4901                 TESTNAME=test_$1 skip "skipping excluded test $1"
4902                 return 0
4903         fi
4904         testname=EXCEPT_$base
4905         if [ ${!testname}x != x ]; then
4906                 TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
4907                 return 0
4908         fi
4909         testname=EXCEPT_ALWAYS_$1
4910         if [ ${!testname}x != x ]; then
4911                 TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1"
4912                 return 0
4913         fi
4914         testname=EXCEPT_ALWAYS_$base
4915         if [ ${!testname}x != x ]; then
4916                 TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1 (base $base)"
4917                 return 0
4918         fi
4919         testname=EXCEPT_SLOW_$1
4920         if [ ${!testname}x != x ]; then
4921                 TESTNAME=test_$1 skip "skipping SLOW test $1"
4922                 return 0
4923         fi
4924         testname=EXCEPT_SLOW_$base
4925         if [ ${!testname}x != x ]; then
4926                 TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
4927                 return 0
4928         fi
4929
4930         LAST_SKIPPED=
4931         ALWAYS_SKIPPED=
4932         run_one_logged $1 "$2"
4933
4934         return $?
4935 }
4936
4937 log() {
4938         echo "$*" >&2
4939         load_module ../libcfs/libcfs/libcfs
4940
4941         local MSG="$HOSTNAME: $*"
4942         # Get rid of '
4943         MSG=${MSG//\'/\\\'}
4944         MSG=${MSG//\(/\\\(}
4945         MSG=${MSG//\)/\\\)}
4946         MSG=${MSG//\;/\\\;}
4947         MSG=${MSG//\|/\\\|}
4948         MSG=${MSG//\>/\\\>}
4949         MSG=${MSG//\</\\\<}
4950         MSG=${MSG//\//\\\/}
4951         do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null ||
4952                 true
4953 }
4954
4955 trace() {
4956         log "STARTING: $*"
4957         strace -o $TMP/$1.strace -ttt $*
4958         RC=$?
4959         log "FINISHED: $*: rc $RC"
4960         return 1
4961 }
4962
4963 complete () {
4964     local duration=$1
4965
4966     banner test complete, duration $duration sec
4967     [ -f "$TESTSUITELOG" ] && egrep .FAIL $TESTSUITELOG || true
4968     echo duration $duration >>$TESTSUITELOG
4969 }
4970
4971 pass() {
4972         # Set TEST_STATUS here. It will be used for logging the result.
4973         TEST_STATUS="PASS"
4974
4975         if [[ -f $LOGDIR/err ]]; then
4976                 TEST_STATUS="FAIL"
4977         elif [[ -f $LOGDIR/skip ]]; then
4978                 TEST_STATUS="SKIP"
4979         fi
4980         echo "$TEST_STATUS $@" 2>&1 | tee -a $TESTSUITELOG
4981 }
4982
4983 check_mds() {
4984     local FFREE=$(do_node $SINGLEMDS \
4985         lctl get_param -n osd*.*MDT*.filesfree | calc_sum)
4986     local FTOTAL=$(do_node $SINGLEMDS \
4987         lctl get_param -n osd*.*MDT*.filestotal | calc_sum)
4988
4989     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
4990 }
4991
4992 reset_fail_loc () {
4993     echo -n "Resetting fail_loc on all nodes..."
4994     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 \
4995             fail_val=0 2>/dev/null || true"
4996     echo done.
4997 }
4998
4999
5000 #
5001 # Log a message (on all nodes) padded with "=" before and after. 
5002 # Also appends a timestamp and prepends the testsuite name.
5003
5004
5005 EQUALS="===================================================================================================="
5006 banner() {
5007     msg="== ${TESTSUITE} $*"
5008     last=${msg: -1:1}
5009     [[ $last != "=" && $last != " " ]] && msg="$msg "
5010     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
5011     # always include at least == after the message
5012     log "$msg== $(date +"%H:%M:%S (%s)")"
5013 }
5014
5015 check_dmesg_for_errors() {
5016         local res
5017         local errors="VFS: Busy inodes after unmount of\|\
5018 ldiskfs_check_descriptors: Checksum for group 0 failed\|\
5019 group descriptors corrupted"
5020
5021         res=$(do_nodes $(comma_list $(nodes_list)) "dmesg" | grep "$errors")
5022         [ -z "$res" ] && return 0
5023         echo "Kernel error detected: $res"
5024         return 1
5025 }
5026
5027 #
5028 # Run a single test function and cleanup after it.
5029 #
5030 # This function should be run in a subshell so the test func can
5031 # exit() without stopping the whole script.
5032 #
5033 run_one() {
5034         local testnum=$1
5035         local message=$2
5036         export tfile=f${testnum}.${TESTSUITE}
5037         export tdir=d${testnum}.${TESTSUITE}
5038         export TESTNAME=test_$testnum
5039         local SAVE_UMASK=`umask`
5040         umask 0022
5041
5042         if ! grep -q $DIR /proc/mounts; then
5043                 $SETUP
5044         fi
5045
5046         banner "test $testnum: $message"
5047         test_${testnum} || error "test_$testnum failed with $?"
5048         cd $SAVE_PWD
5049         reset_fail_loc
5050         check_grant ${testnum} || error "check_grant $testnum failed with $?"
5051         check_catastrophe || error "LBUG/LASSERT detected"
5052         check_dmesg_for_errors || error "Error in dmesg detected"
5053         if [ "$PARALLEL" != "yes" ]; then
5054                 ps auxww | grep -v grep | grep -q multiop &&
5055                                         error "multiop still running"
5056         fi
5057         unset TESTNAME
5058         unset tdir
5059         unset tfile
5060         umask $SAVE_UMASK
5061         $CLEANUP
5062         return 0
5063 }
5064
5065 #
5066 # Wrapper around run_one to ensure:
5067 #  - test runs in subshell
5068 #  - output of test is saved to separate log file for error reporting
5069 #  - test result is saved to data file
5070 #
5071 run_one_logged() {
5072         local BEFORE=$(date +%s)
5073         local TEST_ERROR
5074         local name=${TESTSUITE}.test_${1}.test_log.$(hostname -s).log
5075         local test_log=$LOGDIR/$name
5076         local zfs_log_name=${TESTSUITE}.test_${1}.zfs_log
5077         local zfs_debug_log=$LOGDIR/$zfs_log_name
5078         rm -rf $LOGDIR/err
5079         rm -rf $LOGDIR/ignore
5080         rm -rf $LOGDIR/skip
5081         local SAVE_UMASK=$(umask)
5082         umask 0022
5083
5084         echo
5085         log_sub_test_begin test_${1}
5086         (run_one $1 "$2") 2>&1 | tee -i $test_log
5087         local RC=${PIPESTATUS[0]}
5088
5089         [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] &&
5090                 echo "test_$1 returned $RC" | tee $LOGDIR/err
5091
5092         duration=$(($(date +%s) - $BEFORE))
5093         pass "$1" "(${duration}s)"
5094
5095         if [[ -f $LOGDIR/err ]]; then
5096                 TEST_ERROR=$(cat $LOGDIR/err)
5097         elif [[ -f $LOGDIR/ignore ]]; then
5098                 TEST_ERROR=$(cat $LOGDIR/ignore)
5099         elif [[ -f $LOGDIR/skip ]]; then
5100                 TEST_ERROR=$(cat $LOGDIR/skip)
5101         fi
5102         log_sub_test_end $TEST_STATUS $duration "$RC" "$TEST_ERROR"
5103
5104         if [[ "$TEST_STATUS" != "SKIP" ]] && [[ -f $TF_SKIP ]]; then
5105                 rm -f $TF_SKIP
5106         fi
5107
5108         if [ -f $LOGDIR/err ]; then
5109                 log_zfs_info "$zfs_debug_log"
5110                 $FAIL_ON_ERROR && exit $RC
5111         fi
5112
5113         umask $SAVE_UMASK
5114
5115         return 0
5116 }
5117
5118 #
5119 # Print information of skipped tests to result.yml
5120 #
5121 skip_logged(){
5122         log_sub_test_begin $1
5123         shift
5124         log_sub_test_end "SKIP" "0" "0" "$@"
5125 }
5126
5127 canonical_path() {
5128         (cd $(dirname $1); echo $PWD/$(basename $1))
5129 }
5130
5131
5132 check_grant() {
5133         export base=$(basetest $1)
5134         [ "$CHECK_GRANT" == "no" ] && return 0
5135
5136         testname=GCHECK_ONLY_${base}
5137         [ ${!testname}x == x ] && return 0
5138
5139         echo -n "checking grant......"
5140
5141         local clients=$CLIENTS
5142         [ -z "$clients" ] && clients=$(hostname)
5143
5144         # sync all the data and make sure no pending data on server
5145         do_nodes $clients sync
5146
5147         # get client grant
5148         client_grant=$(do_nodes $clients \
5149                 "$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes" |
5150                 awk '{ total += $1 } END { printf("%0.0f", total) }')
5151
5152         # get server grant
5153         server_grant=$(do_nodes $(comma_list $(osts_nodes)) \
5154                 "$LCTL get_param -n obdfilter.${FSNAME}-OST*.tot_granted" |
5155                 awk '{ total += $1 } END { printf("%0.0f", total) }')
5156
5157         # check whether client grant == server grant
5158         if [[ $client_grant -ne $server_grant ]]; then
5159                 echo "failed: client:${client_grant} server: ${server_grant}."
5160                 do_nodes $(comma_list $(osts_nodes)) \
5161                         "$LCTL get_param obdfilter.${FSNAME}-OST*.tot*"
5162                 do_nodes $clients "$LCTL get_param osc.${FSNAME}-*.cur_*_bytes"
5163                 return 1
5164         else
5165                 echo "pass: client:${client_grant} server: ${server_grant}"
5166         fi
5167 }
5168
5169 ########################
5170 # helper functions
5171
5172 osc_to_ost()
5173 {
5174     osc=$1
5175     ost=`echo $1 | awk -F_ '{print $3}'`
5176     if [ -z $ost ]; then
5177         ost=`echo $1 | sed 's/-osc.*//'`
5178     fi
5179     echo $ost
5180 }
5181
5182 ostuuid_from_index()
5183 {
5184     $LFS osts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
5185 }
5186
5187 ostname_from_index() {
5188     local uuid=$(ostuuid_from_index $1)
5189     echo ${uuid/_UUID/}
5190 }
5191
5192 index_from_ostuuid()
5193 {
5194     $LFS osts $2 | sed -ne "/${1}/s/\(.*\): .* .*$/\1/p"
5195 }
5196
5197 mdtuuid_from_index()
5198 {
5199     $LFS mdts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
5200 }
5201
5202 # Description:
5203 #   Return unique identifier for given hostname
5204 host_id() {
5205         local host_name=$1
5206         echo $host_name | md5sum | cut -d' ' -f1
5207 }
5208
5209 # Description:
5210 #   Returns list of ip addresses for each interface
5211 local_addr_list() {
5212         ip addr | awk '/inet\ / {print $2}' | awk -F\/ '{print $1}'
5213 }
5214
5215 is_local_addr() {
5216         local addr=$1
5217         # Cache address list to avoid mutiple execution of local_addr_list
5218         LOCAL_ADDR_LIST=${LOCAL_ADDR_LIST:-$(local_addr_list)}
5219         local i
5220         for i in $LOCAL_ADDR_LIST ; do
5221                 [[ "$i" == "$addr" ]] && return 0
5222         done
5223         return 1
5224 }
5225
5226 local_node() {
5227         local host_name=$1
5228         local is_local="IS_LOCAL_$(host_id $host_name)"
5229         if [ -z "${!is_local-}" ] ; then
5230                 eval $is_local=0
5231                 local host_ip=$($LUSTRE/tests/resolveip $host_name)
5232                 is_local_addr "$host_ip" && eval $is_local=1
5233         fi
5234         [[ "${!is_local}" == "1" ]]
5235 }
5236
5237 remote_node () {
5238         local node=$1
5239         local_node $node && return 1
5240         return 0
5241 }
5242
5243 remote_mds ()
5244 {
5245     local node
5246     for node in $(mdts_nodes); do
5247         remote_node $node && return 0
5248     done
5249     return 1
5250 }
5251
5252 remote_mds_nodsh()
5253 {
5254     [ "$CLIENTONLY" ] && return 0 || true
5255     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
5256 }
5257
5258 require_dsh_mds()
5259 {
5260         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
5261             MSKIPPED=1 && return 1
5262         return 0
5263 }
5264
5265 remote_ost ()
5266 {
5267     local node
5268     for node in $(osts_nodes) ; do
5269         remote_node $node && return 0
5270     done
5271     return 1
5272 }
5273
5274 remote_ost_nodsh()
5275 {
5276     [ "$CLIENTONLY" ] && return 0 || true 
5277     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
5278 }
5279
5280 require_dsh_ost()
5281 {
5282         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
5283             OSKIPPED=1 && return 1
5284         return 0
5285 }
5286
5287 remote_mgs_nodsh()
5288 {
5289         [ "$CLIENTONLY" ] && return 0 || true
5290     local MGS 
5291     MGS=$(facet_host mgs)
5292     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
5293 }
5294
5295 local_mode ()
5296 {
5297     remote_mds_nodsh || remote_ost_nodsh || \
5298         $(single_local_node $(comma_list $(nodes_list)))
5299 }
5300
5301 remote_servers () {
5302     remote_ost && remote_mds
5303 }
5304
5305 # Get the active nodes for facets.
5306 facets_nodes () {
5307         local facets=$1
5308         local facet
5309         local nodes
5310         local nodes_sort
5311         local i
5312
5313         for facet in ${facets//,/ }; do
5314                 nodes="$nodes $(facet_active_host $facet)"
5315         done
5316
5317         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5318         echo -n $nodes_sort
5319 }
5320
5321 # Get all of the active MDS nodes.
5322 mdts_nodes () {
5323         echo -n $(facets_nodes $(get_facets MDS))
5324 }
5325
5326 # Get all of the active OSS nodes.
5327 osts_nodes () {
5328         echo -n $(facets_nodes $(get_facets OST))
5329 }
5330
5331 # Get all of the active AGT (HSM agent) nodes.
5332 agts_nodes () {
5333         echo -n $(facets_nodes $(get_facets AGT))
5334 }
5335
5336 # Get all of the client nodes and active server nodes.
5337 nodes_list () {
5338         local nodes=$HOSTNAME
5339         local nodes_sort
5340         local i
5341
5342         # CLIENTS (if specified) contains the local client
5343         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
5344
5345         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
5346                 nodes="$nodes $(facets_nodes $(get_facets))"
5347         fi
5348
5349         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5350         echo -n $nodes_sort
5351 }
5352
5353 # Get all of the remote client nodes and remote active server nodes.
5354 remote_nodes_list () {
5355         echo -n $(nodes_list) | sed -re "s/\<$HOSTNAME\>//g"
5356 }
5357
5358 # Get all of the MDS nodes, including active and passive nodes.
5359 all_mdts_nodes () {
5360         local host
5361         local failover_host
5362         local nodes
5363         local nodes_sort
5364         local i
5365
5366         for i in $(seq $MDSCOUNT); do
5367                 host=mds${i}_HOST
5368                 failover_host=mds${i}failover_HOST
5369                 nodes="$nodes ${!host} ${!failover_host}"
5370         done
5371
5372         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5373         echo -n $nodes_sort
5374 }
5375
5376 # Get all of the OSS nodes, including active and passive nodes.
5377 all_osts_nodes () {
5378         local host
5379         local failover_host
5380         local nodes
5381         local nodes_sort
5382         local i
5383
5384         for i in $(seq $OSTCOUNT); do
5385                 host=ost${i}_HOST
5386                 failover_host=ost${i}failover_HOST
5387                 nodes="$nodes ${!host} ${!failover_host}"
5388         done
5389
5390         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5391         echo -n $nodes_sort
5392 }
5393
5394 # Get all of the server nodes, including active and passive nodes.
5395 all_server_nodes () {
5396         local nodes
5397         local nodes_sort
5398         local i
5399
5400         nodes="$mgs_HOST $mgsfailover_HOST $(all_mdts_nodes) $(all_osts_nodes)"
5401
5402         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5403         echo -n $nodes_sort
5404 }
5405
5406 # Get all of the client and server nodes, including active and passive nodes.
5407 all_nodes () {
5408         local nodes=$HOSTNAME
5409         local nodes_sort
5410         local i
5411
5412         # CLIENTS (if specified) contains the local client
5413         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
5414
5415         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
5416                 nodes="$nodes $(all_server_nodes)"
5417         fi
5418
5419         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5420         echo -n $nodes_sort
5421 }
5422
5423 init_clients_lists () {
5424     # Sanity check: exclude the local client from RCLIENTS
5425     local clients=$(hostlist_expand "$RCLIENTS")
5426     local rclients=$(exclude_items_from_list "$clients" $HOSTNAME)
5427
5428     # Sanity check: exclude the dup entries
5429     RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)
5430
5431     clients="$SINGLECLIENT $HOSTNAME $RCLIENTS"
5432
5433     # Sanity check: exclude the dup entries from CLIENTS
5434     # for those configs which has SINGLCLIENT set to local client
5435     clients=$(for i in $clients; do echo $i; done | sort -u)
5436
5437     CLIENTS=$(comma_list $clients)
5438     local -a remoteclients=($RCLIENTS)
5439     for ((i=0; $i<${#remoteclients[@]}; i++)); do
5440             varname=CLIENT$((i + 2))
5441             eval $varname=${remoteclients[i]}
5442     done
5443
5444     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
5445 }
5446
5447 get_random_entry () {
5448     local rnodes=$1
5449
5450     rnodes=${rnodes//,/ }
5451
5452     local -a nodes=($rnodes)
5453     local num=${#nodes[@]} 
5454     local i=$((RANDOM * num * 2 / 65536))
5455
5456     echo ${nodes[i]}
5457 }
5458
5459 client_only () {
5460         [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
5461 }
5462
5463 check_versions () {
5464     [ "$(lustre_version_code client)" = "$(lustre_version_code $SINGLEMDS)" -a \
5465       "$(lustre_version_code client)" = "$(lustre_version_code ost1)" ]
5466 }
5467
5468 get_node_count() {
5469     local nodes="$@"
5470     echo $nodes | wc -w || true
5471 }
5472
5473 mixed_ost_devs () {
5474     local nodes=$(osts_nodes)
5475     local osscount=$(get_node_count "$nodes")
5476     [ ! "$OSTCOUNT" = "$osscount" ]
5477 }
5478
5479 mixed_mdt_devs () {
5480     local nodes=$(mdts_nodes)
5481     local mdtcount=$(get_node_count "$nodes")
5482     [ ! "$MDSCOUNT" = "$mdtcount" ]
5483 }
5484
5485 generate_machine_file() {
5486     local nodes=${1//,/ }
5487     local machinefile=$2
5488     rm -f $machinefile
5489     for node in $nodes; do
5490         echo $node >>$machinefile || \
5491             { echo "can not generate machinefile $machinefile" && return 1; }
5492     done
5493 }
5494
5495 get_stripe () {
5496         local file=$1/stripe
5497
5498         touch $file
5499         $LFS getstripe -v $file || error "getstripe $file failed"
5500         rm -f $file
5501 }
5502
5503 setstripe_nfsserver () {
5504         local dir=$1
5505
5506         local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
5507                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -n1)
5508
5509         [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
5510
5511         do_nodev $nfsserver lfs setstripe "$@"
5512 }
5513
5514 # Check and add a test group.
5515 add_group() {
5516         local group_id=$1
5517         local group_name=$2
5518         local rc=0
5519
5520         local gid=$(getent group $group_name | cut -d: -f3)
5521         if [[ -n "$gid" ]]; then
5522                 [[ "$gid" -eq "$group_id" ]] || {
5523                         error_noexit "inconsistent group ID:" \
5524                                      "new: $group_id, old: $gid"
5525                         rc=1
5526                 }
5527         else
5528                 groupadd -g $group_id $group_name
5529                 rc=${PIPESTATUS[0]}
5530         fi
5531
5532         return $rc
5533 }
5534
5535 # Check and add a test user.
5536 add_user() {
5537         local user_id=$1
5538         shift
5539         local user_name=$1
5540         shift
5541         local group_name=$1
5542         shift
5543         local home=$1
5544         shift
5545         local opts="$@"
5546         local rc=0
5547
5548         local uid=$(getent passwd $user_name | cut -d: -f3)
5549         if [[ -n "$uid" ]]; then
5550                 if [[ "$uid" -eq "$user_id" ]]; then
5551                         local dir=$(getent passwd $user_name | cut -d: -f6)
5552                         if [[ "$dir" != "$home" ]]; then
5553                                 mkdir -p $home
5554                                 usermod -d $home $user_name
5555                                 rc=${PIPESTATUS[0]}
5556                         fi
5557                 else
5558                         error_noexit "inconsistent user ID:" \
5559                                      "new: $user_id, old: $uid"
5560                         rc=1
5561                 fi
5562         else
5563                 mkdir -p $home
5564                 useradd -M -u $user_id -d $home -g $group_name $opts $user_name
5565                 rc=${PIPESTATUS[0]}
5566         fi
5567
5568         return $rc
5569 }
5570
5571 check_runas_id_ret() {
5572     local myRC=0
5573     local myRUNAS_UID=$1
5574     local myRUNAS_GID=$2
5575     shift 2
5576     local myRUNAS=$@
5577     if [ -z "$myRUNAS" ]; then
5578         error_exit "myRUNAS command must be specified for check_runas_id"
5579     fi
5580     if $GSS_KRB5; then
5581         $myRUNAS krb5_login.sh || \
5582             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
5583     fi
5584     mkdir $DIR/d0_runas_test
5585     chmod 0755 $DIR
5586     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
5587     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
5588     rm -rf $DIR/d0_runas_test
5589     return $myRC
5590 }
5591
5592 check_runas_id() {
5593     local myRUNAS_UID=$1
5594     local myRUNAS_GID=$2
5595     shift 2
5596     local myRUNAS=$@
5597     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
5598         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
5599         Please set RUNAS_ID to some UID which exists on MDS and client or
5600         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
5601 }
5602
5603 # obtain the UID/GID for MPI_USER
5604 get_mpiuser_id() {
5605     local mpi_user=$1
5606
5607     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
5608 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
5609
5610     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
5611 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
5612 }
5613
5614 # obtain and cache Kerberos ticket-granting ticket
5615 refresh_krb5_tgt() {
5616     local myRUNAS_UID=$1
5617     local myRUNAS_GID=$2
5618     shift 2
5619     local myRUNAS=$@
5620     if [ -z "$myRUNAS" ]; then
5621         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
5622     fi
5623
5624     CLIENTS=${CLIENTS:-$HOSTNAME}
5625     do_nodes $CLIENTS "set -x
5626 if ! $myRUNAS krb5_login.sh; then
5627     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
5628     exit 1
5629 fi"
5630 }
5631
5632 # Run multiop in the background, but wait for it to print
5633 # "PAUSING" to its stdout before returning from this function.
5634 multiop_bg_pause() {
5635     MULTIOP_PROG=${MULTIOP_PROG:-$MULTIOP}
5636     FILE=$1
5637     ARGS=$2
5638
5639     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
5640     mkfifo $TMPPIPE
5641
5642     echo "$MULTIOP_PROG $FILE v$ARGS"
5643     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
5644
5645     echo "TMPPIPE=${TMPPIPE}"
5646     read -t 60 multiop_output < $TMPPIPE
5647     if [ $? -ne 0 ]; then
5648         rm -f $TMPPIPE
5649         return 1
5650     fi
5651     rm -f $TMPPIPE
5652     if [ "$multiop_output" != "PAUSING" ]; then
5653         echo "Incorrect multiop output: $multiop_output"
5654         kill -9 $PID
5655         return 1
5656     fi
5657
5658     return 0
5659 }
5660
5661 do_and_time () {
5662     local cmd=$1
5663     local rc
5664
5665     SECONDS=0
5666     eval '$cmd'
5667
5668     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
5669
5670     echo $SECONDS
5671     return $rc
5672 }
5673
5674 inodes_available () {
5675         local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{ print $4 }' |
5676                 sort -un | head -n1) || return 1
5677         echo $((IFree))
5678 }
5679
5680 mdsrate_inodes_available () {
5681     local min_inodes=$(inodes_available)
5682     echo $((min_inodes * 99 / 100))
5683 }
5684
5685 # reset llite stat counters
5686 clear_llite_stats(){
5687         lctl set_param -n llite.*.stats 0
5688 }
5689
5690 # sum llite stat items
5691 calc_llite_stats() {
5692         local res=$(lctl get_param -n llite.*.stats |
5693                 awk '/^'"$1"'/ {sum += $2} END { printf("%0.0f", sum) }')
5694         echo $((res))
5695 }
5696
5697 # reset osc stat counters
5698 clear_osc_stats(){
5699         lctl set_param -n osc.*.osc_stats 0
5700 }
5701
5702 # sum osc stat items
5703 calc_osc_stats() {
5704         local res=$(lctl get_param -n osc.*.osc_stats |
5705                 awk '/^'"$1"'/ {sum += $2} END { printf("%0.0f", sum) }')
5706         echo $((res))
5707 }
5708
5709 calc_sum () {
5710         awk '{sum += $1} END { printf("%0.0f", sum) }'
5711 }
5712
5713 calc_osc_kbytes () {
5714         df $MOUNT > /dev/null
5715         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
5716 }
5717
5718 # save_lustre_params(comma separated facet list, parameter_mask)
5719 # generate a stream of formatted strings (<facet> <param name>=<param value>)
5720 save_lustre_params() {
5721         local facets=$1
5722         local facet
5723         local nodes
5724         local node
5725
5726         for facet in ${facets//,/ }; do
5727                 node=$(facet_active_host $facet)
5728                 [[ *\ $node\ * = " $nodes " ]] && continue
5729                 nodes="$nodes $node"
5730
5731                 do_node $node "$LCTL get_param $2 |
5732                         while read s; do echo $facet \\\$s; done"
5733         done
5734 }
5735
5736 # restore lustre parameters from input stream, produces by save_lustre_params
5737 restore_lustre_params() {
5738         local facet
5739         local name
5740         local val
5741
5742         while IFS=" =" read facet name val; do
5743                 do_facet $facet "$LCTL set_param -n $name $val"
5744         done
5745 }
5746
5747 check_catastrophe() {
5748         local nodes=${1:-$(comma_list $(nodes_list))}
5749
5750         do_nodes $nodes "rc=0;
5751 val=\\\$($LCTL get_param -n catastrophe 2>&1);
5752 if [[ \\\$? -eq 0 && \\\$val -ne 0 ]]; then
5753         echo \\\$(hostname -s): \\\$val;
5754         rc=\\\$val;
5755 fi;
5756 exit \\\$rc"
5757 }
5758
5759 mdsrate_cleanup () {
5760         if [ -d $4 ]; then
5761                 mpi_run ${MACHINEFILE_OPTION} $2 -np $1 ${MDSRATE} --unlink \
5762                         --nfiles $3 --dir $4 --filefmt $5 $6
5763                 rmdir $4
5764         fi
5765 }
5766
5767 delayed_recovery_enabled () {
5768     local var=${SINGLEMDS}_svc
5769     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
5770 }
5771
5772 ########################
5773
5774 convert_facet2label() {
5775     local facet=$1
5776
5777     if [ x$facet = xost ]; then
5778        facet=ost1
5779     fi
5780
5781     local varsvc=${facet}_svc
5782
5783     if [ -n ${!varsvc} ]; then
5784         echo ${!varsvc}
5785     else
5786         error "No lablel for $facet!"
5787     fi
5788 }
5789
5790 get_clientosc_proc_path() {
5791         echo "${1}-osc-*"
5792 }
5793
5794 # If the 2.0 MDS was mounted on 1.8 device, then the OSC and LOV names
5795 # used by MDT would not be changed.
5796 # mdt lov: fsname-mdtlov
5797 # mdt osc: fsname-OSTXXXX-osc
5798 mds_on_old_device() {
5799     local mds=${1:-"$SINGLEMDS"}
5800
5801     if [ $(lustre_version_code $mds) -gt $(version_code 1.9.0) ]; then
5802         do_facet $mds "lctl list_param osc.$FSNAME-OST*-osc \
5803             > /dev/null 2>&1" && return 0
5804     fi
5805     return 1
5806 }
5807
5808 get_mdtosc_proc_path() {
5809         local mds_facet=$1
5810         local ost_label=${2:-"*OST*"}
5811
5812         [ "$mds_facet" = "mds" ] && mds_facet=$SINGLEMDS
5813         local mdt_label=$(convert_facet2label $mds_facet)
5814         local mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')
5815
5816         if [ $(lustre_version_code $mds_facet) -le $(version_code 1.8.0) ] ||
5817            mds_on_old_device $mds_facet; then
5818                 echo "${ost_label}-osc"
5819         elif [[ $ost_label = *OST* ]]; then
5820                 echo "${ost_label}-osc-${mdt_index}"
5821         else
5822                 echo "${ost_label}-osp-${mdt_index}"
5823         fi
5824 }
5825
5826 get_osc_import_name() {
5827     local facet=$1
5828     local ost=$2
5829     local label=$(convert_facet2label $ost)
5830
5831     if [ "${facet:0:3}" = "mds" ]; then
5832         get_mdtosc_proc_path $facet $label
5833         return 0
5834     fi
5835
5836     get_clientosc_proc_path $label
5837     return 0
5838 }
5839
5840 _wait_import_state () {
5841     local expected=$1
5842     local CONN_PROC=$2
5843     local maxtime=${3:-$(max_recovery_time)}
5844     local error_on_failure=${4:-1}
5845     local CONN_STATE
5846     local i=0
5847
5848         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
5849     while [ "${CONN_STATE}" != "${expected}" ]; do
5850         if [ "${expected}" == "DISCONN" ]; then
5851             # for disconn we can check after proc entry is removed
5852             [ "x${CONN_STATE}" == "x" ] && return 0
5853             #  with AT enabled, we can have connect request timeout near of
5854             # reconnect timeout and test can't see real disconnect
5855             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
5856         fi
5857         if [ $i -ge $maxtime ]; then
5858             [ $error_on_failure -ne 0 ] && \
5859                 error "can't put import for $CONN_PROC into ${expected}" \
5860                       "state after $i sec, have ${CONN_STATE}"
5861             return 1
5862         fi
5863         sleep 1
5864         # Add uniq for multi-mount case
5865         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
5866         i=$(($i + 1))
5867     done
5868
5869     log "$CONN_PROC in ${CONN_STATE} state after $i sec"
5870     return 0
5871 }
5872
5873 wait_import_state() {
5874     local state=$1
5875     local params=$2
5876     local maxtime=${3:-$(max_recovery_time)}
5877     local error_on_failure=${4:-1}
5878     local param
5879
5880     for param in ${params//,/ }; do
5881         _wait_import_state $state $param $maxtime $error_on_failure || return
5882     done
5883 }
5884
5885 wait_import_state_mount() {
5886         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
5887                 return 0
5888         fi
5889
5890         wait_import_state $*
5891 }
5892
5893 # One client request could be timed out because server was not ready
5894 # when request was sent by client.
5895 # The request timeout calculation details :
5896 # ptl_send_rpc ()
5897 #      /* We give the server rq_timeout secs to process the req, and
5898 #      add the network latency for our local timeout. */
5899 #      request->rq_deadline = request->rq_sent + request->rq_timeout +
5900 #           ptlrpc_at_get_net_latency(request) ;
5901 #
5902 # ptlrpc_connect_import ()
5903 #      request->rq_timeout = INITIAL_CONNECT_TIMEOUT
5904 #
5905 # init_imp_at () ->
5906 #   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0
5907 # ptlrpc_at_get_net_latency(request) ->
5908 #       at_get (max (iat_net_latency=0, at_min)) = at_min
5909 #
5910 # i.e.:
5911 # request->rq_timeout + ptlrpc_at_get_net_latency(request) =
5912 # INITIAL_CONNECT_TIMEOUT + at_min
5913 #
5914 # We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT
5915 # because we can not get this value in runtime,
5916 # the value depends on configure options, and it is not stored in /proc.
5917 # obd_support.h:
5918 # #define CONNECTION_SWITCH_MIN 5U
5919 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
5920
5921 request_timeout () {
5922     local facet=$1
5923
5924     # request->rq_timeout = INITIAL_CONNECT_TIMEOUT
5925     local init_connect_timeout=$TIMEOUT
5926     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
5927
5928     local at_min=$(at_get $facet at_min)
5929
5930     echo $(( init_connect_timeout + at_min ))
5931 }
5932
5933 _wait_osc_import_state() {
5934         local facet=$1
5935         local ost_facet=$2
5936         local expected=$3
5937         local target=$(get_osc_import_name $facet $ost_facet)
5938         local param="osc.${target}.ost_server_uuid"
5939         local params=$param
5940         local i=0
5941
5942         # 1. wait the deadline of client 1st request (it could be skipped)
5943         # 2. wait the deadline of client 2nd request
5944         local maxtime=$(( 2 * $(request_timeout $facet)))
5945
5946         if [[ $facet == client* ]]; then
5947                 # During setup time, the osc might not be setup, it need wait
5948                 # until list_param can return valid value. And also if there
5949                 # are mulitple osc entries we should list all of them before
5950                 # go to wait.
5951                 params=$($LCTL list_param $param 2>/dev/null || true)
5952                 while [ -z "$params" ]; do
5953                         if [ $i -ge $maxtime ]; then
5954                                 echo "can't get $param in $maxtime secs"
5955                                 return 1
5956                         fi
5957                         sleep 1
5958                         i=$((i + 1))
5959                         params=$($LCTL list_param $param 2>/dev/null || true)
5960                 done
5961         fi
5962
5963         if [[ $ost_facet = mds* ]]; then
5964                 # no OSP connection to itself
5965                 if [[ $facet = $ost_facet ]]; then
5966                         return 0
5967                 fi
5968                 param="osp.${target}.mdt_server_uuid"
5969                 params=$param
5970         fi
5971
5972         if ! do_rpc_nodes "$(facet_active_host $facet)" \
5973                         wait_import_state $expected "$params" $maxtime; then
5974                 error "import is not in ${expected} state"
5975                 return 1
5976         fi
5977
5978         return 0
5979 }
5980
5981 wait_osc_import_state() {
5982         local facet=$1
5983         local ost_facet=$2
5984         local expected=$3
5985         local num
5986
5987         if [[ $facet = mds ]]; then
5988                 for num in $(seq $MDSCOUNT); do
5989                         _wait_osc_import_state mds$num "$ost_facet" "$expected"
5990                 done
5991         else
5992                 _wait_osc_import_state "$facet" "$ost_facet" "$expected"
5993         fi
5994 }
5995
5996 _wait_mgc_import_state() {
5997         local facet=$1
5998         local expected=$2
5999         local error_on_failure=${3:-1}
6000         local param="mgc.*.mgs_server_uuid"
6001         local params=$param
6002         local i=0
6003
6004         # 1. wait the deadline of client 1st request (it could be skipped)
6005         # 2. wait the deadline of client 2nd request
6006         local maxtime=$(( 2 * $(request_timeout $facet)))
6007
6008         if [[ $facet == client* ]]; then
6009                 # During setup time, the osc might not be setup, it need wait
6010                 # until list_param can return valid value. And also if there
6011                 # are mulitple osc entries we should list all of them before
6012                 # go to wait.
6013                 params=$($LCTL list_param $param 2>/dev/null || true)
6014                 while [ -z "$params" ]; do
6015                         if [ $i -ge $maxtime ]; then
6016                                 echo "can't get $param in $maxtime secs"
6017                                 return 1
6018                         fi
6019                         sleep 1
6020                         i=$((i + 1))
6021                         params=$($LCTL list_param $param 2>/dev/null || true)
6022                 done
6023         fi
6024         if ! do_rpc_nodes "$(facet_active_host $facet)" \
6025                         wait_import_state $expected "$params" $maxtime \
6026                                           $error_on_failure; then
6027                 if [ $error_on_failure -ne 0 ]; then
6028                     error "import is not in ${expected} state"
6029                 fi
6030                 return 1
6031         fi
6032
6033         return 0
6034 }
6035
6036 wait_mgc_import_state() {
6037         local facet=$1
6038         local expected=$2
6039         local error_on_failure=${3:-1}
6040         local num
6041
6042         if [[ $facet = mds ]]; then
6043                 for num in $(seq $MDSCOUNT); do
6044                         _wait_mgc_import_state mds$num "$expected" \
6045                                                $error_on_failure || return
6046                 done
6047         else
6048                 _wait_mgc_import_state "$facet" "$expected"
6049                                        $error_on_failure || return
6050         fi
6051 }
6052
6053 wait_dne_interconnect() {
6054         local num
6055
6056         if [ $MDSCOUNT -gt 1 ]; then
6057                 for num in $(seq $MDSCOUNT); do
6058                         wait_osc_import_state mds mds$num FULL
6059                 done
6060         fi
6061 }
6062
6063 get_clientmdc_proc_path() {
6064     echo "${1}-mdc-*"
6065 }
6066
6067 get_clientmgc_proc_path() {
6068     echo "*"
6069 }
6070
6071 do_rpc_nodes () {
6072         local list=$1
6073         shift
6074
6075         [ -z "$list" ] && return 0
6076
6077         # Add paths to lustre tests for 32 and 64 bit systems.
6078         local LIBPATH="/usr/lib/lustre/tests:/usr/lib64/lustre/tests:"
6079         local TESTPATH="$RLUSTRE/tests:"
6080         local RPATH="PATH=${TESTPATH}${LIBPATH}${PATH}:/sbin:/bin:/usr/sbin:"
6081         do_nodesv $list "${RPATH} NAME=${NAME} sh rpc.sh $@ "
6082 }
6083
6084 wait_clients_import_state () {
6085         local list=$1
6086         local facet=$2
6087         local expected=$3
6088
6089         local facets=$facet
6090
6091         if [ "$FAILURE_MODE" = HARD ]; then
6092                 facets=$(facets_on_host $(facet_active_host $facet))
6093         fi
6094
6095         for facet in ${facets//,/ }; do
6096                 local label=$(convert_facet2label $facet)
6097                 local proc_path
6098                 case $facet in
6099                 ost* ) proc_path="osc.$(get_clientosc_proc_path \
6100                                   $label).ost_server_uuid" ;;
6101                 mds* ) proc_path="mdc.$(get_clientmdc_proc_path \
6102                                   $label).mds_server_uuid" ;;
6103                 mgs* ) proc_path="mgc.$(get_clientmgc_proc_path \
6104                                   $label).mgs_server_uuid" ;;
6105                 *) error "unknown facet!" ;;
6106                 esac
6107
6108                 local params=$(expand_list $params $proc_path)
6109         done
6110
6111         if ! do_rpc_nodes "$list" wait_import_state_mount $expected $params;
6112         then
6113                 error "import is not in ${expected} state"
6114                 return 1
6115         fi
6116 }
6117
6118 oos_full() {
6119         local -a AVAILA
6120         local -a GRANTA
6121         local -a TOTALA
6122         local OSCFULL=1
6123         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
6124                   $LCTL get_param obdfilter.*.kbytesavail))
6125         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
6126                   $LCTL get_param -n obdfilter.*.tot_granted))
6127         TOTALA=($(do_nodes $(comma_list $(osts_nodes)) \
6128                   $LCTL get_param -n obdfilter.*.kbytestotal))
6129         for ((i=0; i<${#AVAILA[@]}; i++)); do
6130                 local -a AVAIL1=(${AVAILA[$i]//=/ })
6131                 local -a TOTAL=(${TOTALA[$i]//=/ })
6132                 GRANT=$((${GRANTA[$i]}/1024))
6133                 # allow 1% of total space in bavail because of delayed
6134                 # allocation with ZFS which might release some free space after
6135                 # txg commit.  For small devices, we set a mininum of 8MB
6136                 local LIMIT=$((${TOTAL} / 100 + 8000))
6137                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} \
6138                         grnt=$GRANT diff=$((AVAIL1[1] - GRANT)) limit=${LIMIT}
6139                 [ $((AVAIL1[1] - GRANT)) -lt $LIMIT ] && OSCFULL=0 && \
6140                         echo " FULL" || echo
6141         done
6142         return $OSCFULL
6143 }
6144
6145 pool_list () {
6146    do_facet mgs lctl pool_list $1
6147 }
6148
6149 create_pool() {
6150     local fsname=${1%%.*}
6151     local poolname=${1##$fsname.}
6152
6153     do_facet mgs lctl pool_new $1
6154     local RC=$?
6155     # get param should return err unless pool is created
6156     [[ $RC -ne 0 ]] && return $RC
6157
6158     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
6159         2>/dev/null || echo foo" "" || RC=1
6160     if [[ $RC -eq 0 ]]; then
6161         add_pool_to_list $1
6162     else
6163         error "pool_new failed $1"
6164     fi
6165     return $RC
6166 }
6167
6168 add_pool_to_list () {
6169         local fsname=${1%%.*}
6170         local poolname=${1##$fsname.}
6171
6172         local listvar=${fsname}_CREATED_POOLS
6173         local temp=${listvar}=$(expand_list ${!listvar} $poolname)
6174         eval export $temp
6175 }
6176
6177 remove_pool_from_list () {
6178         local fsname=${1%%.*}
6179         local poolname=${1##$fsname.}
6180
6181         local listvar=${fsname}_CREATED_POOLS
6182         local temp=${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
6183         eval export $temp
6184 }
6185
6186 destroy_pool_int() {
6187     local ost
6188     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
6189         awk '$1 !~ /^Pool:/ {print $1}')
6190     for ost in $OSTS; do
6191         do_facet mgs lctl pool_remove $1 $ost
6192     done
6193     do_facet mgs lctl pool_destroy $1
6194 }
6195
6196 # <fsname>.<poolname> or <poolname>
6197 destroy_pool() {
6198     local fsname=${1%%.*}
6199     local poolname=${1##$fsname.}
6200
6201     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
6202
6203     local RC
6204
6205     pool_list $fsname.$poolname || return $?
6206
6207     destroy_pool_int $fsname.$poolname
6208     RC=$?
6209     [[ $RC -ne 0 ]] && return $RC
6210
6211     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
6212       2>/dev/null || echo foo" "foo" || RC=1
6213
6214     if [[ $RC -eq 0 ]]; then
6215         remove_pool_from_list $fsname.$poolname
6216     else
6217         error "destroy pool failed $1"
6218     fi
6219     return $RC
6220 }
6221
6222 destroy_pools () {
6223     local fsname=${1:-$FSNAME}
6224     local poolname
6225     local listvar=${fsname}_CREATED_POOLS
6226
6227     pool_list $fsname
6228
6229     [ x${!listvar} = x ] && return 0
6230
6231     echo destroy the created pools: ${!listvar}
6232     for poolname in ${!listvar//,/ }; do
6233         destroy_pool $fsname.$poolname
6234     done
6235 }
6236
6237 cleanup_pools () {
6238     local fsname=${1:-$FSNAME}
6239     trap 0
6240     destroy_pools $fsname
6241 }
6242
6243 gather_logs () {
6244     local list=$1
6245
6246     local ts=$(date +%s)
6247     local docp=true
6248
6249     if [[ ! -f "$YAML_LOG" ]]; then
6250         # init_logging is not performed before gather_logs,
6251         # so the $LOGDIR needs to be checked here
6252         check_shared_dir $LOGDIR && touch $LOGDIR/shared
6253     fi
6254
6255     [ -f $LOGDIR/shared ] && docp=false
6256
6257     # dump lustre logs, dmesg
6258
6259     prefix="$TESTLOG_PREFIX.$TESTNAME"
6260     suffix="$ts.log"
6261     echo "Dumping lctl log to ${prefix}.*.${suffix}"
6262
6263     if [ "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
6264         echo "Dumping logs only on local client."
6265         $LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}
6266         dmesg > ${prefix}.dmesg.$(hostname -s).${suffix}
6267         return
6268     fi
6269
6270     do_nodesv $list \
6271         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname -s).${suffix};
6272          dmesg > ${prefix}.dmesg.\\\$(hostname -s).${suffix}"
6273     if [ ! -f $LOGDIR/shared ]; then
6274         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
6275     fi
6276 }
6277
6278 do_ls () {
6279     local mntpt_root=$1
6280     local num_mntpts=$2
6281     local dir=$3
6282     local i
6283     local cmd
6284     local pids
6285     local rc=0
6286
6287     for i in $(seq 0 $num_mntpts); do
6288         cmd="ls -laf ${mntpt_root}$i/$dir"
6289         echo + $cmd;
6290         $cmd > /dev/null &
6291         pids="$pids $!"
6292     done
6293     echo pids=$pids
6294     for pid in $pids; do
6295         wait $pid || rc=$?
6296     done
6297
6298     return $rc
6299 }
6300
6301 # check_and_start_recovery_timer()
6302 #       service_time = at_est2timeout(service_time);
6303 #       service_time += 2 * INITIAL_CONNECT_TIMEOUT;
6304 #       service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC);
6305
6306 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN, obd_timeout/20)
6307 #define CONNECTION_SWITCH_MAX min(50, max(CONNECTION_SWITCH_MIN, obd_timeout))
6308 #define CONNECTION_SWITCH_MIN 5
6309 #define CONNECTION_SWITCH_INC 5
6310 max_recovery_time() {
6311         local init_connect_timeout=$((TIMEOUT / 20))
6312         ((init_connect_timeout >= 5)) || init_connect_timeout=5
6313
6314         local service_time=$(($(at_max_get client) * 9 / 4 + 5))
6315         service_time=$((service_time + 2 * (init_connect_timeout + 50 + 5)))
6316
6317         echo -n $service_time
6318 }
6319
6320 recovery_time_min() {
6321         local connection_switch_min=5
6322         local connection_switch_inc=5
6323         local connection_switch_max
6324         local reconnect_delay_max
6325         local initial_connect_timeout
6326         local max
6327         local timout_20
6328
6329         #connection_switch_max=min(50, max($connection_switch_min,$TIMEOUT)
6330         (($connection_switch_min > $TIMEOUT)) &&
6331                 max=$connection_switch_min || max=$TIMEOUT
6332         (($max < 50)) && connection_switch_max=$max || connection_switch_max=50
6333
6334         #initial_connect_timeout = max(connection_switch_min, obd_timeout/20)
6335         timeout_20=$((TIMEOUT/20))
6336         (($connection_switch_min > $timeout_20)) &&
6337                 initial_connect_timeout=$connection_switch_min ||
6338                 initial_connect_timeout=$timeout_20
6339
6340         reconnect_delay_max=$((connection_switch_max + connection_switch_inc + \
6341                                initial_connect_timeout))
6342         echo $((2 * reconnect_delay_max))
6343 }
6344
6345 get_clients_mount_count () {
6346     local clients=${CLIENTS:-`hostname`}
6347
6348     # we need to take into account the clients mounts and
6349     # exclude mds/ost mounts if any;
6350     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
6351 }
6352
6353 # gss functions
6354 PROC_CLI="srpc_info"
6355
6356 combination()
6357 {
6358     local M=$1
6359     local N=$2
6360     local R=1
6361
6362     if [ $M -lt $N ]; then
6363         R=0
6364     else
6365         N=$((N + 1))
6366         while [ $N -lt $M ]; do
6367             R=$((R * N))
6368             N=$((N + 1))
6369         done
6370     fi
6371
6372     echo $R
6373     return 0
6374 }
6375
6376 calc_connection_cnt() {
6377     local dir=$1
6378
6379     # MDT->MDT = 2 * C(M, 2)
6380     # MDT->OST = M * O
6381     # CLI->OST = C * O
6382     # CLI->MDT = C * M
6383     comb_m2=$(combination $MDSCOUNT 2)
6384
6385     local num_clients=$(get_clients_mount_count)
6386
6387     local cnt_mdt2mdt=$((comb_m2 * 2))
6388     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
6389     local cnt_cli2ost=$((num_clients * OSTCOUNT))
6390     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
6391     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
6392     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
6393     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
6394
6395     local var=cnt_$dir
6396     local res=${!var}
6397
6398     echo $res
6399 }
6400
6401 set_rule()
6402 {
6403     local tgt=$1
6404     local net=$2
6405     local dir=$3
6406     local flavor=$4
6407     local cmd="$tgt.srpc.flavor"
6408
6409     if [ $net == "any" ]; then
6410         net="default"
6411     fi
6412     cmd="$cmd.$net"
6413
6414     if [ $dir != "any" ]; then
6415         cmd="$cmd.$dir"
6416     fi
6417
6418     cmd="$cmd=$flavor"
6419     log "Setting sptlrpc rule: $cmd"
6420     do_facet mgs "$LCTL conf_param $cmd"
6421 }
6422
6423 count_flvr()
6424 {
6425     local output=$1
6426     local flavor=$2
6427     local count=0
6428
6429     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
6430     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
6431
6432     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
6433
6434     if [ "x$bulkspec" != "x" ]; then
6435         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
6436
6437         if [ "x$algs" != "x" ]; then
6438             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
6439         else
6440             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
6441             if [ $bulk == "bulkn" ]; then
6442                 bulk_count=`echo "$output" | grep "bulk flavor" \
6443                             | grep "null/null" | wc -l`
6444             elif [ $bulk == "bulki" ]; then
6445                 bulk_count=`echo "$output" | grep "bulk flavor" \
6446                             | grep "/null" | grep -v "null/" | wc -l`
6447             else
6448                 bulk_count=`echo "$output" | grep "bulk flavor" \
6449                             | grep -v "/null" | grep -v "null/" | wc -l`
6450             fi
6451         fi
6452
6453         [ $bulk_count -lt $count ] && count=$bulk_count
6454     fi
6455
6456     echo $count
6457 }
6458
6459 flvr_cnt_cli2mdt()
6460 {
6461     local flavor=$1
6462     local cnt
6463
6464     local clients=${CLIENTS:-`hostname`}
6465
6466     for c in ${clients//,/ }; do
6467         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
6468         tmpcnt=`count_flvr "$output" $flavor`
6469         cnt=$((cnt + tmpcnt))
6470     done
6471     echo $cnt
6472 }
6473
6474 flvr_cnt_cli2ost()
6475 {
6476     local flavor=$1
6477     local cnt
6478
6479     local clients=${CLIENTS:-`hostname`}
6480
6481     for c in ${clients//,/ }; do
6482         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
6483         tmpcnt=`count_flvr "$output" $flavor`
6484         cnt=$((cnt + tmpcnt))
6485     done
6486     echo $cnt
6487 }
6488
6489 flvr_cnt_mdt2mdt()
6490 {
6491     local flavor=$1
6492     local cnt=0
6493
6494     if [ $MDSCOUNT -le 1 ]; then
6495         echo 0
6496         return
6497     fi
6498
6499     for num in `seq $MDSCOUNT`; do
6500         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
6501         tmpcnt=`count_flvr "$output" $flavor`
6502         cnt=$((cnt + tmpcnt))
6503     done
6504     echo $cnt;
6505 }
6506
6507 flvr_cnt_mdt2ost()
6508 {
6509     local flavor=$1
6510     local cnt=0
6511     local mdtosc
6512
6513     for num in `seq $MDSCOUNT`; do
6514         mdtosc=$(get_mdtosc_proc_path mds$num)
6515         mdtosc=${mdtosc/-MDT*/-MDT\*}
6516         output=$(do_facet mds$num lctl get_param -n \
6517             osc.$mdtosc.$PROC_CLI 2>/dev/null)
6518         tmpcnt=`count_flvr "$output" $flavor`
6519         cnt=$((cnt + tmpcnt))
6520     done
6521     echo $cnt;
6522 }
6523
6524 flvr_cnt_mgc2mgs()
6525 {
6526     local flavor=$1
6527
6528     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
6529     count_flvr "$output" $flavor
6530 }
6531
6532 do_check_flavor()
6533 {
6534     local dir=$1        # from to
6535     local flavor=$2     # flavor expected
6536     local res=0
6537
6538     if [ $dir == "cli2mdt" ]; then
6539         res=`flvr_cnt_cli2mdt $flavor`
6540     elif [ $dir == "cli2ost" ]; then
6541         res=`flvr_cnt_cli2ost $flavor`
6542     elif [ $dir == "mdt2mdt" ]; then
6543         res=`flvr_cnt_mdt2mdt $flavor`
6544     elif [ $dir == "mdt2ost" ]; then
6545         res=`flvr_cnt_mdt2ost $flavor`
6546     elif [ $dir == "all2ost" ]; then
6547         res1=`flvr_cnt_mdt2ost $flavor`
6548         res2=`flvr_cnt_cli2ost $flavor`
6549         res=$((res1 + res2))
6550     elif [ $dir == "all2mdt" ]; then
6551         res1=`flvr_cnt_mdt2mdt $flavor`
6552         res2=`flvr_cnt_cli2mdt $flavor`
6553         res=$((res1 + res2))
6554     elif [ $dir == "all2all" ]; then
6555         res1=`flvr_cnt_mdt2ost $flavor`
6556         res2=`flvr_cnt_cli2ost $flavor`
6557         res3=`flvr_cnt_mdt2mdt $flavor`
6558         res4=`flvr_cnt_cli2mdt $flavor`
6559         res=$((res1 + res2 + res3 + res4))
6560     fi
6561
6562     echo $res
6563 }
6564
6565 wait_flavor()
6566 {
6567     local dir=$1        # from to
6568     local flavor=$2     # flavor expected
6569     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
6570
6571     local res=0
6572
6573     for ((i=0;i<20;i++)); do
6574         echo -n "checking $dir..."
6575         res=$(do_check_flavor $dir $flavor)
6576         echo "found $res/$expect $flavor connections"
6577         [ $res -ge $expect ] && return 0
6578         sleep 4
6579     done
6580
6581     echo "Error checking $flavor of $dir: expect $expect, actual $res"
6582     return 1
6583 }
6584
6585 restore_to_default_flavor()
6586 {
6587     local proc="mgs.MGS.live.$FSNAME"
6588
6589     echo "restoring to default flavor..."
6590
6591     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
6592
6593     # remove all existing rules if any
6594     if [ $nrule -ne 0 ]; then
6595         echo "$nrule existing rules"
6596         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
6597             echo "remove rule: $rule"
6598             spec=`echo $rule | awk -F = '{print $1}'`
6599             do_facet mgs "$LCTL conf_param -d $spec"
6600         done
6601     fi
6602
6603     # verify no rules left
6604     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
6605     [ $nrule -ne 0 ] && error "still $nrule rules left"
6606
6607     # wait for default flavor to be applied
6608     # currently default flavor for all connections are 'null'
6609     wait_flavor all2all null
6610     echo "now at default flavor settings"
6611 }
6612
6613 set_flavor_all()
6614 {
6615     local flavor=${1:-null}
6616
6617     echo "setting all flavor to $flavor"
6618
6619     # FIXME need parameter to this fn
6620     # and remove global vars
6621     local cnt_all2all=$(calc_connection_cnt all2all)
6622
6623     local res=$(do_check_flavor all2all $flavor)
6624     if [ $res -eq $cnt_all2all ]; then
6625         echo "already have total $res $flavor connections"
6626         return
6627     fi
6628
6629     echo "found $res $flavor out of total $cnt_all2all connections"
6630     restore_to_default_flavor
6631
6632     [[ $flavor = null ]] && return 0
6633
6634     set_rule $FSNAME any any $flavor
6635     wait_flavor all2all $flavor
6636 }
6637
6638
6639 check_logdir() {
6640     local dir=$1
6641     # Checking for shared logdir
6642     if [ ! -d $dir ]; then
6643         # Not found. Create local logdir
6644         mkdir -p $dir
6645     else
6646         touch $dir/check_file.$(hostname -s)
6647     fi
6648     return 0
6649 }
6650
6651 check_write_access() {
6652         local dir=$1
6653         local list=${2:-$(comma_list $(nodes_list))}
6654         local node
6655         local file
6656
6657         for node in ${list//,/ }; do
6658                 file=$dir/check_file.$(short_nodename $node)
6659                 if [[ ! -f "$file" ]]; then
6660                         # Logdir not accessible/writable from this node.
6661                         return 1
6662                 fi
6663                 rm -f $file || return 1
6664         done
6665         return 0
6666 }
6667
6668 init_logging() {
6669     if [[ -n $YAML_LOG ]]; then
6670         return
6671     fi
6672     local SAVE_UMASK=`umask`
6673     umask 0000
6674
6675     export YAML_LOG=${LOGDIR}/results.yml
6676     mkdir -p $LOGDIR
6677     init_clients_lists
6678
6679     if [ ! -f $YAML_LOG ]; then       # If the yaml log already exists then we will just append to it
6680       if check_shared_dir $LOGDIR; then
6681           touch $LOGDIR/shared
6682           echo "Logging to shared log directory: $LOGDIR"
6683       else
6684           echo "Logging to local directory: $LOGDIR"
6685       fi
6686
6687       yml_nodes_file $LOGDIR >> $YAML_LOG
6688       yml_results_file >> $YAML_LOG
6689     fi
6690
6691     umask $SAVE_UMASK
6692 }
6693
6694 log_test() {
6695     yml_log_test $1 >> $YAML_LOG
6696 }
6697
6698 log_test_status() {
6699      yml_log_test_status $@ >> $YAML_LOG
6700 }
6701
6702 log_sub_test_begin() {
6703     yml_log_sub_test_begin "$@" >> $YAML_LOG
6704 }
6705
6706 log_sub_test_end() {
6707     yml_log_sub_test_end "$@" >> $YAML_LOG
6708 }
6709
6710 run_llverdev()
6711 {
6712         local dev=$1
6713         local llverdev_opts=$2
6714         local devname=$(basename $1)
6715         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
6716         # loop devices aren't in /proc/partitions
6717         [ "x$size" == "x" ] && local size=$(ls -l $dev | awk '{print $5}')
6718
6719         size=$(($size / 1024 / 1024)) # Gb
6720
6721         local partial_arg=""
6722         # Run in partial (fast) mode if the size
6723         # of a partition > 1 GB
6724         [ $size -gt 1 ] && partial_arg="-p"
6725
6726         llverdev --force $partial_arg $llverdev_opts $dev
6727 }
6728
6729 run_llverfs()
6730 {
6731         local dir=$1
6732         local llverfs_opts=$2
6733         local use_partial_arg=$3
6734         local partial_arg=""
6735         local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB
6736
6737         # Run in partial (fast) mode if the size
6738         # of a partition > 1 GB
6739         [ "x$use_partial_arg" != "xno" ] && [ $size -gt 1 ] && partial_arg="-p"
6740
6741         llverfs $partial_arg $llverfs_opts $dir
6742 }
6743
6744 #Remove objects from OST
6745 remove_ost_objects() {
6746         local facet=$1
6747         local ostdev=$2
6748         local group=$3
6749         shift 3
6750         local objids="$@"
6751         local mntpt=$(facet_mntpt $facet)
6752         local opts=$OST_MOUNT_OPTS
6753         local i
6754         local rc
6755
6756         echo "removing objects from $ostdev on $facet: $objids"
6757         if ! test -b $ostdev; then
6758                 opts=$(csa_add "$opts" -o loop)
6759         fi
6760         mount -t $(facet_fstype $facet) $opts $ostdev $mntpt ||
6761                 return $?
6762         rc=0
6763         for i in $objids; do
6764                 rm $mntpt/O/$group/d$((i % 32))/$i || { rc=$?; break; }
6765         done
6766         umount -f $mntpt || return $?
6767         return $rc
6768 }
6769
6770 #Remove files from MDT
6771 remove_mdt_files() {
6772         local facet=$1
6773         local mdtdev=$2
6774         shift 2
6775         local files="$@"
6776         local mntpt=$(facet_mntpt $facet)
6777         local opts=$MDS_MOUNT_OPTS
6778
6779         echo "removing files from $mdtdev on $facet: $files"
6780         if [ $(facet_fstype $facet) == ldiskfs ] &&
6781            ! do_facet $facet test -b $mdtdev; then
6782                 opts=$(csa_add "$opts" -o loop)
6783         fi
6784         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
6785                 return $?
6786         rc=0
6787         for f in $files; do
6788                 rm $mntpt/ROOT/$f || { rc=$?; break; }
6789         done
6790         umount -f $mntpt || return $?
6791         return $rc
6792 }
6793
6794 duplicate_mdt_files() {
6795         local facet=$1
6796         local mdtdev=$2
6797         shift 2
6798         local files="$@"
6799         local mntpt=$(facet_mntpt $facet)
6800         local opts=$MDS_MOUNT_OPTS
6801
6802         echo "duplicating files on $mdtdev on $facet: $files"
6803         mkdir -p $mntpt || return $?
6804         if [ $(facet_fstype $facet) == ldiskfs ] &&
6805            ! do_facet $facet test -b $mdtdev; then
6806                 opts=$(csa_add "$opts" -o loop)
6807         fi
6808         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
6809                 return $?
6810
6811     do_umount() {
6812         trap 0
6813         popd > /dev/null
6814         rm $tmp
6815         umount -f $mntpt
6816     }
6817     trap do_umount EXIT
6818
6819     tmp=$(mktemp $TMP/setfattr.XXXXXXXXXX)
6820     pushd $mntpt/ROOT > /dev/null || return $?
6821     rc=0
6822     for f in $files; do
6823         touch $f.bad || return $?
6824         getfattr -n trusted.lov $f | sed "s#$f#&.bad#" > $tmp
6825         rc=${PIPESTATUS[0]}
6826         [ $rc -eq 0 ] || return $rc
6827         setfattr --restore $tmp || return $?
6828     done
6829     do_umount
6830 }
6831
6832 run_sgpdd () {
6833     local devs=${1//,/ }
6834     shift
6835     local params=$@
6836     local rslt=$TMP/sgpdd_survey
6837
6838     # sgpdd-survey cleanups ${rslt}.* files
6839
6840     local cmd="rslt=$rslt $params scsidevs=\"$devs\" $SGPDDSURVEY"
6841     echo + $cmd
6842     eval $cmd
6843     cat ${rslt}.detail
6844 }
6845
6846 # returns the canonical name for an ldiskfs device
6847 ldiskfs_canon() {
6848         local dev="$1"
6849         local facet="$2"
6850
6851         do_facet $facet "dv=\\\$(lctl get_param -n $dev);
6852 if foo=\\\$(lvdisplay -c \\\$dv 2>/dev/null); then
6853     echo dm-\\\${foo##*:};
6854 else
6855     echo \\\$(basename \\\$dv);
6856 fi;"
6857 }
6858
6859 is_sanity_benchmark() {
6860     local benchmarks="dbench bonnie iozone fsx"
6861     local suite=$1
6862     for b in $benchmarks; do
6863         if [ "$b" == "$suite" ]; then
6864             return 0
6865         fi
6866     done
6867     return 1
6868 }
6869
6870 min_ost_size () {
6871     $LCTL get_param -n osc.*.kbytesavail | sort -n | head -n1
6872 }
6873
6874 #
6875 # Get the available size (KB) of a given obd target.
6876 #
6877 get_obd_size() {
6878         local facet=$1
6879         local obd=$2
6880         local size
6881
6882         [[ $facet != client ]] || return 0
6883
6884         size=$(do_facet $facet $LCTL get_param -n *.$obd.kbytesavail | head -n1)
6885         echo -n $size
6886 }
6887
6888 #
6889 # Get the page size (bytes) on a given facet node.
6890 #
6891 get_page_size() {
6892         local facet=$1
6893         local size
6894
6895         size=$(do_facet $facet getconf PAGE_SIZE)
6896         [[ ${PIPESTATUS[0]} = 0 && -n "$size" ]] || size=4096
6897         echo -n $size
6898 }
6899
6900 #
6901 # Get the block count of the filesystem.
6902 #
6903 get_block_count() {
6904         local facet=$1
6905         local device=$2
6906         local count
6907
6908         count=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
6909                 awk '/^Block count:/ {print $3}')
6910         echo -n $count
6911 }
6912
6913 # Get the block size of the filesystem.
6914 get_block_size() {
6915     local facet=$1
6916     local device=$2
6917     local size
6918
6919     size=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
6920            awk '/^Block size:/ {print $3}')
6921     echo $size
6922 }
6923
6924 # Check whether the "large_xattr" feature is enabled or not.
6925 large_xattr_enabled() {
6926         [[ $(facet_fstype $SINGLEMDS) == zfs ]] && return 0
6927
6928         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
6929
6930         do_facet $SINGLEMDS "$DUMPE2FS -h $mds_dev 2>&1 |
6931                 grep -E -q '(ea_inode|large_xattr)'"
6932         return ${PIPESTATUS[0]}
6933 }
6934
6935 # Get the maximum xattr size supported by the filesystem.
6936 max_xattr_size() {
6937     local size
6938
6939     if large_xattr_enabled; then
6940         # include/linux/limits.h: #define XATTR_SIZE_MAX 65536
6941         size=65536
6942     else
6943         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
6944         local block_size=$(get_block_size $SINGLEMDS $mds_dev)
6945
6946         # maximum xattr size = size of block - size of header -
6947         #                      size of 1 entry - 4 null bytes
6948         size=$((block_size - 32 - 32 - 4))
6949     fi
6950
6951     echo $size
6952 }
6953
6954 # Dump the value of the named xattr from a file.
6955 get_xattr_value() {
6956     local xattr_name=$1
6957     local file=$2
6958
6959     echo "$(getfattr -n $xattr_name --absolute-names --only-values $file)"
6960 }
6961
6962 # Generate a string with size of $size bytes.
6963 generate_string() {
6964     local size=${1:-1024} # in bytes
6965
6966     echo "$(head -c $size < /dev/zero | tr '\0' y)"
6967 }
6968
6969 reformat_external_journal() {
6970         local facet=$1
6971         local var
6972
6973         var=${facet}_JRN
6974         if [ -n "${!var}" ]; then
6975                 local rcmd="do_facet $facet"
6976
6977                 echo "reformat external journal on $facet:${!var}"
6978                 ${rcmd} mke2fs -O journal_dev ${!var} || return 1
6979         fi
6980 }
6981
6982 # MDT file-level backup/restore
6983 mds_backup_restore() {
6984         local facet=$1
6985         local igif=$2
6986         local devname=$(mdsdevname $(facet_number $facet))
6987         local mntpt=$(facet_mntpt brpt)
6988         local rcmd="do_facet $facet"
6989         local metaea=${TMP}/backup_restore.ea
6990         local metadata=${TMP}/backup_restore.tgz
6991         local opts=${MDS_MOUNT_OPTS}
6992         local svc=${facet}_svc
6993
6994         if ! ${rcmd} test -b ${devname}; then
6995                 opts=$(csa_add "$opts" -o loop)
6996         fi
6997
6998         echo "file-level backup/restore on $facet:${devname}"
6999
7000         # step 1: build mount point
7001         ${rcmd} mkdir -p $mntpt
7002         # step 2: cleanup old backup
7003         ${rcmd} rm -f $metaea $metadata
7004         # step 3: mount dev
7005         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
7006         if [ ! -z $igif ]; then
7007                 # step 3.5: rm .lustre
7008                 ${rcmd} rm -rf $mntpt/ROOT/.lustre || return 1
7009         fi
7010         # step 4: backup metaea
7011         echo "backup EA"
7012         ${rcmd} "cd $mntpt && getfattr -R -d -m '.*' -P . > $metaea && cd -" ||
7013                 return 2
7014         # step 5: backup metadata
7015         echo "backup data"
7016         ${rcmd} tar zcf $metadata -C $mntpt/ . > /dev/null 2>&1 || return 3
7017         # step 6: umount
7018         ${rcmd} $UMOUNT $mntpt || return 4
7019         # step 8: reformat dev
7020         echo "reformat new device"
7021         format_mdt $(facet_number $facet)
7022         # step 9: mount dev
7023         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 7
7024         # step 10: restore metadata
7025         echo "restore data"
7026         ${rcmd} tar zxfp $metadata -C $mntpt > /dev/null 2>&1 || return 8
7027         # step 11: restore metaea
7028         echo "restore EA"
7029         ${rcmd} "cd $mntpt && setfattr --restore=$metaea && cd - " || return 9
7030         # step 12: remove recovery logs
7031         echo "remove recovery logs"
7032         ${rcmd} rm -fv $mntpt/OBJECTS/* $mntpt/CATALOGS
7033         # step 13: umount dev
7034         ${rcmd} $UMOUNT $mntpt || return 10
7035         # step 14: cleanup tmp backup
7036         ${rcmd} rm -f $metaea $metadata
7037         # step 15: reset device label - it's not virgin on
7038         ${rcmd} e2label $devname ${!svc}
7039 }
7040
7041 # remove OI files
7042 mds_remove_ois() {
7043         local facet=$1
7044         local idx=$2
7045         local devname=$(mdsdevname $(facet_number $facet))
7046         local mntpt=$(facet_mntpt brpt)
7047         local rcmd="do_facet $facet"
7048         local opts=${MDS_MOUNT_OPTS}
7049
7050         if ! ${rcmd} test -b ${devname}; then
7051                 opts=$(csa_add "$opts" -o loop)
7052         fi
7053
7054         echo "removing OI files on $facet: idx=${idx}"
7055
7056         # step 1: build mount point
7057         ${rcmd} mkdir -p $mntpt
7058         # step 2: mount dev
7059         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
7060         if [ -z $idx ]; then
7061                 # step 3: remove all OI files
7062                 ${rcmd} rm -fv $mntpt/oi.16*
7063         elif [ $idx -lt 2 ]; then
7064                 ${rcmd} rm -fv $mntpt/oi.16.${idx}
7065         else
7066                 local i
7067
7068                 # others, rm oi.16.[idx, idx * idx, idx ** ...]
7069                 for ((i=${idx}; i<64; i=$((i * idx)))); do
7070                         ${rcmd} rm -fv $mntpt/oi.16.${i}
7071                 done
7072         fi
7073         # step 4: umount
7074         ${rcmd} $UMOUNT $mntpt || return 2
7075         # OI files will be recreated when mounted as lustre next time.
7076 }
7077
7078 # generate maloo upload-able log file name
7079 # \param logname specify unique part of file name
7080 generate_logname() {
7081         local logname=${1:-"default_logname"}
7082
7083         echo "$TESTLOG_PREFIX.$TESTNAME.$logname.$(hostname -s).log"
7084 }
7085
7086 # make directory on different MDTs
7087 test_mkdir() {
7088         local path
7089         local p_option
7090         local stripe_count=2
7091         local stripe_index=-1
7092         local OPTIND=1
7093
7094         while getopts "c:i:p" opt; do
7095                 case $opt in
7096                         c) stripe_count=$OPTARG;;
7097                         i) stripe_index=$OPTARG;;
7098                         p) p_option="-p";;
7099                         \?) error "only support -i -c -p";;
7100                 esac
7101         done
7102
7103         shift $((OPTIND - 1))
7104         [ $# -eq 1 ] || error "Only creating single directory is supported"
7105         path="$*"
7106
7107         if [ "$p_option" == "-p" ]; then
7108                 local parent=$(dirname $path)
7109
7110                 [ -d $path ] && return 0
7111                 [ ! -d ${parent} ] && mkdir -p ${parent}
7112         fi
7113
7114         if [ $MDSCOUNT -le 1 ]; then
7115                 mkdir $path
7116         else
7117                 local test_num=$(echo $testnum | sed -e 's/[^0-9]*//g')
7118                 local mdt_index
7119
7120                 if [ $stripe_index -eq -1 ]; then
7121                         mdt_index=$((test_num % MDSCOUNT))
7122                 else
7123                         mdt_index=$stripe_index
7124                 fi
7125                 echo "striped dir -i$mdt_index -c$stripe_count $path"
7126                 $LFS setdirstripe -i$mdt_index -c$stripe_count $path
7127         fi
7128 }
7129
7130 # find the smallest and not in use file descriptor
7131 free_fd()
7132 {
7133         local max_fd=$(ulimit -n)
7134         local fd=3
7135         while [[ $fd -le $max_fd && -e /proc/self/fd/$fd ]]; do
7136                 ((++fd))
7137         done
7138         [ $fd -lt $max_fd ] || error "finding free file descriptor failed"
7139         echo $fd
7140 }
7141
7142 check_mount_and_prep()
7143 {
7144         is_mounted $MOUNT || setupall
7145
7146         rm -rf $DIR/[df][0-9]* || error "Fail to cleanup the env!"
7147         mkdir $DIR/$tdir || error "Fail to mkdir $DIR/$tdir."
7148         for idx in $(seq $MDSCOUNT); do
7149                 local name="MDT$(printf '%04x' $((idx - 1)))"
7150                 rm -rf $MOUNT/.lustre/lost+found/$name/*
7151         done
7152 }
7153
7154 # calcule how many ost-objects to be created.
7155 precreated_ost_obj_count()
7156 {
7157         local mdt_idx=$1
7158         local ost_idx=$2
7159         local mdt_name="MDT$(printf '%04x' $mdt_idx)"
7160         local ost_name="OST$(printf '%04x' $ost_idx)"
7161         local proc_path="${FSNAME}-${ost_name}-osc-${mdt_name}"
7162         local last_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \
7163                         osp.$proc_path.prealloc_last_id)
7164         local next_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \
7165                         osp.$proc_path.prealloc_next_id)
7166         echo $((last_id - next_id + 1))
7167 }
7168
7169 check_file_in_pool()
7170 {
7171         local file=$1
7172         local pool=$2
7173         local tlist="$3"
7174         local res=$($GETSTRIPE $file | grep 0x | cut -f2)
7175         for i in $res
7176         do
7177                 for t in $tlist ; do
7178                         [ "$i" -eq "$t" ] && continue 2
7179                 done
7180
7181                 echo "pool list: $tlist"
7182                 echo "striping: $res"
7183                 error_noexit "$file not allocated in $pool"
7184                 return 1
7185         done
7186         return 0
7187 }
7188
7189 pool_add() {
7190         echo "Creating new pool"
7191         local pool=$1
7192
7193         create_pool $FSNAME.$pool ||
7194                 { error_noexit "No pool created, result code $?"; return 1; }
7195         [ $($LFS pool_list $FSNAME | grep -c "$FSNAME.${pool}\$") -eq 1 ] ||
7196                 { error_noexit "$pool not in lfs pool_list"; return 2; }
7197 }
7198
7199 pool_add_targets() {
7200         echo "Adding targets to pool"
7201         local pool=$1
7202         local first=$2
7203         local last=$3
7204         local step=${4:-1}
7205
7206         local list=$(seq $first $step $last)
7207
7208         local t=$(for i in $list; do printf "$FSNAME-OST%04x_UUID " $i; done)
7209         do_facet mgs $LCTL pool_add \
7210                         $FSNAME.$pool $FSNAME-OST[$first-$last/$step]
7211         wait_update $HOSTNAME "lctl get_param -n lov.$FSNAME-*.pools.$pool \
7212                         | sort -u | tr '\n' ' ' " "$t" || {
7213                 error_noexit "Add to pool failed"
7214                 return 1
7215         }
7216         local lfscount=$($LFS pool_list $FSNAME.$pool | grep -c "\-OST")
7217         local addcount=$(((last - first) / step + 1))
7218         [ $lfscount -eq $addcount ] || {
7219                 error_noexit "lfs pool_list bad ost count" \
7220                                                 "$lfscount != $addcount"
7221                 return 2
7222         }
7223 }
7224
7225 pool_set_dir() {
7226         local pool=$1
7227         local tdir=$2
7228         echo "Setting pool on directory $tdir"
7229
7230         $SETSTRIPE -c 2 -p $pool $tdir && return 0
7231
7232         error_noexit "Cannot set pool $pool to $tdir"
7233         return 1
7234 }
7235
7236 pool_check_dir() {
7237         local pool=$1
7238         local tdir=$2
7239         echo "Checking pool on directory $tdir"
7240
7241         local res=$($GETSTRIPE --pool $tdir | sed "s/\s*$//")
7242         [ "$res" = "$pool" ] && return 0
7243
7244         error_noexit "Pool on '$tdir' is '$res', not '$pool'"
7245         return 1
7246 }
7247
7248 pool_dir_rel_path() {
7249         echo "Testing relative path works well"
7250         local pool=$1
7251         local tdir=$2
7252         local root=$3
7253
7254         mkdir -p $root/$tdir/$tdir
7255         cd $root/$tdir
7256         pool_set_dir $pool $tdir          || return 1
7257         pool_set_dir $pool ./$tdir        || return 2
7258         pool_set_dir $pool ../$tdir       || return 3
7259         pool_set_dir $pool ../$tdir/$tdir || return 4
7260         rm -rf $tdir; cd - > /dev/null
7261 }
7262
7263 pool_alloc_files() {
7264         echo "Checking files allocation from directory pool"
7265         local pool=$1
7266         local tdir=$2
7267         local count=$3
7268         local tlist="$4"
7269
7270         local failed=0
7271         for i in $(seq -w 1 $count)
7272         do
7273                 local file=$tdir/file-$i
7274                 touch $file
7275                 check_file_in_pool $file $pool "$tlist" || \
7276                         failed=$((failed + 1))
7277         done
7278         [ "$failed" = 0 ] && return 0
7279
7280         error_noexit "$failed files not allocated in $pool"
7281         return 1
7282 }
7283
7284 pool_create_files() {
7285         echo "Creating files in pool"
7286         local pool=$1
7287         local tdir=$2
7288         local count=$3
7289         local tlist="$4"
7290
7291         mkdir -p $tdir
7292         local failed=0
7293         for i in $(seq -w 1 $count)
7294         do
7295                 local file=$tdir/spoo-$i
7296                 $SETSTRIPE -p $pool $file
7297                 check_file_in_pool $file $pool "$tlist" || \
7298                         failed=$((failed + 1))
7299         done
7300         [ "$failed" = 0 ] && return 0
7301
7302         error_noexit "$failed files not allocated in $pool"
7303         return 1
7304 }
7305
7306 pool_lfs_df() {
7307         echo "Checking 'lfs df' output"
7308         local pool=$1
7309
7310         local t=$($LCTL get_param -n lov.$FSNAME-clilov-*.pools.$pool |
7311                         tr '\n' ' ')
7312         local res=$($LFS df --pool $FSNAME.$pool |
7313                         awk '{print $1}' |
7314                         grep "$FSNAME-OST" |
7315                         tr '\n' ' ')
7316         [ "$res" = "$t" ] && return 0
7317
7318         error_noexit "Pools OSTs '$t' is not '$res' that lfs df reports"
7319         return 1
7320 }
7321
7322 pool_file_rel_path() {
7323         echo "Creating files in a pool with relative pathname"
7324         local pool=$1
7325         local tdir=$2
7326
7327         mkdir -p $tdir ||
7328                 { error_noexit "unable to create $tdir"; return 1 ; }
7329         local file="/..$tdir/$tfile-1"
7330         $SETSTRIPE -p $pool $file ||
7331                 { error_noexit "unable to create $file" ; return 2 ; }
7332
7333         cd $tdir
7334         $SETSTRIPE -p $pool $tfile-2 || {
7335                 error_noexit "unable to create $tfile-2 in $tdir"
7336                 return 3
7337         }
7338 }
7339
7340 pool_remove_first_target() {
7341         echo "Removing first target from a pool"
7342         local pool=$1
7343
7344         local pname="lov.$FSNAME-*.pools.$pool"
7345         local t=$($LCTL get_param -n $pname | head -1)
7346         do_facet mgs $LCTL pool_remove $FSNAME.$pool $t
7347         wait_update $HOSTNAME "lctl get_param -n $pname | grep $t" "" || {
7348                 error_noexit "$t not removed from $FSNAME.$pool"
7349                 return 1
7350         }
7351 }
7352
7353 pool_remove_all_targets() {
7354         echo "Removing all targets from pool"
7355         local pool=$1
7356         local file=$2
7357         local pname="lov.$FSNAME-*.pools.$pool"
7358         for t in $($LCTL get_param -n $pname | sort -u)
7359         do
7360                 do_facet mgs $LCTL pool_remove $FSNAME.$pool $t
7361         done
7362         wait_update $HOSTNAME "lctl get_param -n $pname" "" || {
7363                 error_noexit "Pool $FSNAME.$pool cannot be drained"
7364                 return 1
7365         }
7366         # striping on an empty/nonexistant pool should fall back
7367         # to "pool of everything"
7368         touch $file || {
7369                 error_noexit "failed to use fallback striping for empty pool"
7370                 return 2
7371         }
7372         # setstripe on an empty pool should fail
7373         $SETSTRIPE -p $pool $file 2>/dev/null && {
7374                 error_noexit "expected failure when creating file" \
7375                                                         "with empty pool"
7376                 return 3
7377         }
7378         return 0
7379 }
7380
7381 pool_remove() {
7382         echo "Destroying pool"
7383         local pool=$1
7384         local file=$2
7385
7386         do_facet mgs $LCTL pool_destroy $FSNAME.$pool
7387
7388         sleep 2
7389         # striping on an empty/nonexistant pool should fall back
7390         # to "pool of everything"
7391         touch $file || {
7392                 error_noexit "failed to use fallback striping for missing pool"
7393                 return 1
7394         }
7395         # setstripe on an empty pool should fail
7396         $SETSTRIPE -p $pool $file 2>/dev/null && {
7397                 error_noexit "expected failure when creating file" \
7398                                                         "with missing pool"
7399                 return 2
7400         }
7401
7402         # get param should return err once pool is gone
7403         if wait_update $HOSTNAME "lctl get_param -n \
7404                 lov.$FSNAME-*.pools.$pool 2>/dev/null || echo foo" "foo"
7405         then
7406                 remove_pool_from_list $FSNAME.$pool
7407                 return 0
7408         fi
7409         error_noexit "Pool $FSNAME.$pool is not destroyed"
7410         return 3
7411 }
7412
7413 # Get and check the actual stripe count of one file.
7414 # Usage: check_stripe_count <file> <expected_stripe_count>
7415 check_stripe_count() {
7416         local file=$1
7417         local expected=$2
7418         local actual
7419
7420         [[ -z "$file" || -z "$expected" ]] &&
7421                 error "check_stripe_count: invalid argument"
7422
7423         local cmd="$GETSTRIPE -c $file"
7424         actual=$($cmd) || error "$cmd failed"
7425         actual=${actual%% *}
7426
7427         if [[ $actual -ne $expected ]]; then
7428                 [[ $expected -eq -1 ]] ||
7429                         error "$cmd wrong: found $actual, expected $expected"
7430                 [[ $actual -eq $OSTCOUNT ]] ||
7431                         error "$cmd wrong: found $actual, expected $OSTCOUNT"
7432         fi
7433 }
7434
7435 # Get and check the actual list of OST indices on one file.
7436 # Usage: check_obdidx <file> <expected_comma_separated_list_of_ost_indices>
7437 check_obdidx() {
7438         local file=$1
7439         local expected=$2
7440         local obdidx
7441
7442         [[ -z "$file" || -z "$expected" ]] &&
7443                 error "check_obdidx: invalid argument!"
7444
7445         obdidx=$(comma_list $($GETSTRIPE $file | grep -A $OSTCOUNT obdidx |
7446                               grep -v obdidx | awk '{print $1}' | xargs))
7447
7448         [[ $obdidx = $expected ]] ||
7449                 error "list of OST indices on $file is $obdidx," \
7450                       "should be $expected"
7451 }
7452
7453 # Get and check the actual OST index of the first stripe on one file.
7454 # Usage: check_start_ost_idx <file> <expected_start_ost_idx>
7455 check_start_ost_idx() {
7456         local file=$1
7457         local expected=$2
7458         local start_ost_idx
7459
7460         [[ -z "$file" || -z "$expected" ]] &&
7461                 error "check_start_ost_idx: invalid argument!"
7462
7463         start_ost_idx=$($GETSTRIPE $file | grep -A 1 obdidx | grep -v obdidx |
7464                         awk '{print $1}')
7465
7466         [[ $start_ost_idx = $expected ]] ||
7467                 error "OST index of the first stripe on $file is" \
7468                       "$start_ost_idx, should be $expected"
7469 }
7470
7471 killall_process () {
7472         local clients=${1:-$(hostname)}
7473         local name=$2
7474         local signal=$3
7475         local rc=0
7476
7477         do_nodes $clients "killall $signal $name"
7478 }