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