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