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