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