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