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