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