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