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