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