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