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