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