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