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