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