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