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