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