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