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