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