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