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