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