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