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