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