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