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