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