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