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