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