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