Whamcloud - gitweb
LU-8922 lod: check master stripes properly
[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                     begin=${range%-*}
2847                     end=${range#*-}
2848
2849                     # Number of leading zeros
2850                     padlen=${#begin}
2851                     padlen2=${#end}
2852                     end=$(echo $end | sed 's/0*//')
2853                     [[ -z "$end" ]] && end=0
2854                     [[ $padlen2 -gt $padlen ]] && {
2855                         [[ $padlen2 -eq ${#end} ]] && padlen2=0
2856                         padlen=$padlen2
2857                     }
2858                     begin=$(echo $begin | sed 's/0*//')
2859                     [ -z $begin ] && begin=0
2860
2861                     for num in $(seq -f "%0${padlen}g" $begin $end); do
2862                         value="${name#*,}${num}${back}"
2863                         [ "$value" != "${value/\[/}" ] && {
2864                             value=$(hostlist_expand "$value")
2865                         }
2866                         myList="$myList $value"
2867                     done
2868                 done
2869             fi
2870         } else {
2871             myList="$myList $item"
2872         } fi
2873     done
2874     myList=${myList//,/ }
2875     myList=${myList:1} # Remove first character which is a space
2876
2877     # Filter any duplicates without sorting
2878     list="$myList "
2879     myList="${list%% *}"
2880
2881     while [[ "$list" != ${myList##* } ]]; do
2882         local tlist=" $list"
2883         list=${tlist// ${list%% *} / }
2884         list=${list:1}
2885         myList="$myList ${list%% *}"
2886     done
2887     myList="${myList%* }";
2888
2889     # We can select an object at an offset in the list
2890     [ $# -eq 2 ] && {
2891         cnt=0
2892         for item in $myList; do
2893             let cnt=cnt+1
2894             [ $cnt -eq $offset ] && {
2895                 myList=$item
2896             }
2897         done
2898         [ $(get_node_count $myList) -ne 1 ] && myList=""
2899     }
2900     echo $myList
2901 }
2902
2903 facet_host() {
2904         local facet=$1
2905         local varname
2906
2907         [ "$facet" == client ] && echo -n $HOSTNAME && return
2908         varname=${facet}_HOST
2909         if [ -z "${!varname}" ]; then
2910                 if [ "${facet:0:3}" == "ost" ]; then
2911                         local fh=${facet%failover}_HOST
2912                         eval export ${facet}_HOST=${!fh}
2913                         if [ -z "${!varname}" ]; then
2914                                 eval export ${facet}_HOST=${ost_HOST}
2915                         fi
2916                 elif [ "${facet:0:3}" == "mdt" -o \
2917                         "${facet:0:3}" == "mds" -o \
2918                         "${facet:0:3}" == "mgs" ]; then
2919                         eval export ${facet}_HOST=${mds_HOST}
2920                 fi
2921         fi
2922         echo -n ${!varname}
2923 }
2924
2925 facet_failover_host() {
2926         local facet=$1
2927         local varname
2928
2929         var=${facet}failover_HOST
2930         if [ -n "${!var}" ]; then
2931                 echo ${!var}
2932                 return
2933         fi
2934
2935         if [ "${facet:0:3}" == "mdt" -o "${facet:0:3}" == "mds" -o \
2936              "${facet:0:3}" == "mgs" ]; then
2937
2938                 eval export ${facet}failover_host=${mds_HOST}
2939                 echo ${mds_HOST}
2940                 return
2941         fi
2942
2943         if [[ $facet == ost* ]]; then
2944                 eval export ${facet}failover_host=${ost_HOST}
2945                 echo ${ost_HOST}
2946                 return
2947         fi
2948 }
2949
2950 facet_active() {
2951     local facet=$1
2952     local activevar=${facet}active
2953
2954     if [ -f $TMP/${facet}active ] ; then
2955         source $TMP/${facet}active
2956     fi
2957
2958     active=${!activevar}
2959     if [ -z "$active" ] ; then
2960         echo -n ${facet}
2961     else
2962         echo -n ${active}
2963     fi
2964 }
2965
2966 facet_active_host() {
2967         facet_host $(facet_active $1)
2968 }
2969
2970 # Get the passive failover partner host of facet.
2971 facet_passive_host() {
2972         local facet=$1
2973         [[ $facet = client ]] && return
2974
2975         local host=${facet}_HOST
2976         local failover_host=${facet}failover_HOST
2977         local active_host=$(facet_active_host $facet)
2978
2979         [[ -z ${!failover_host} || ${!failover_host} = ${!host} ]] && return
2980
2981         if [[ $active_host = ${!host} ]]; then
2982                 echo -n ${!failover_host}
2983         else
2984                 echo -n ${!host}
2985         fi
2986 }
2987
2988 change_active() {
2989     local facetlist=$1
2990     local facet
2991
2992     facetlist=$(exclude_items_from_list $facetlist mgs)
2993
2994     for facet in ${facetlist//,/ }; do
2995     local failover=${facet}failover
2996     local host=`facet_host $failover`
2997     [ -z "$host" ] && return
2998
2999     local curactive=`facet_active $facet`
3000     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
3001         eval export ${facet}active=$facet
3002     else
3003         eval export ${facet}active=$failover
3004     fi
3005     # save the active host for this facet
3006     local activevar=${facet}active
3007     echo "$activevar=${!activevar}" > $TMP/$activevar
3008     [[ $facet = mds1 ]] && combined_mgs_mds && \
3009         echo "mgsactive=${!activevar}" > $TMP/mgsactive
3010     local TO=`facet_active_host $facet`
3011     echo "Failover $facet to $TO"
3012     done
3013 }
3014
3015 do_node() {
3016     local verbose=false
3017     # do not stripe off hostname if verbose, bug 19215
3018     if [ x$1 = x--verbose ]; then
3019         shift
3020         verbose=true
3021     fi
3022
3023     local HOST=$1
3024     shift
3025     local myPDSH=$PDSH
3026     if [ "$HOST" = "$HOSTNAME" ]; then
3027         myPDSH="no_dsh"
3028     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
3029         echo "cannot run remote command on $HOST with $myPDSH"
3030         return 128
3031     fi
3032     if $VERBOSE; then
3033         echo "CMD: $HOST $@" >&2
3034         $myPDSH $HOST "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
3035     fi
3036
3037     if [ "$myPDSH" = "rsh" ]; then
3038 # we need this because rsh does not return exit code of an executed command
3039         local command_status="$TMP/cs"
3040         rsh $HOST ":> $command_status"
3041         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
3042                     cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
3043                     echo command failed >$command_status"
3044         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
3045         return 0
3046     fi
3047
3048     if $verbose ; then
3049         # print HOSTNAME for myPDSH="no_dsh"
3050         if [[ $myPDSH = no_dsh ]]; then
3051             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
3052         else
3053             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
3054         fi
3055     else
3056         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
3057     fi
3058     return ${PIPESTATUS[0]}
3059 }
3060
3061 do_nodev() {
3062     do_node --verbose "$@"
3063 }
3064
3065 single_local_node () {
3066    [ "$1" = "$HOSTNAME" ]
3067 }
3068
3069 # Outputs environment variable assignments that should be passed to remote nodes
3070 get_env_vars() {
3071         local var
3072         local value
3073         local facets=$(get_facets)
3074         local facet
3075
3076         for var in ${!MODOPTS_*}; do
3077                 value=${!var//\"/\\\"}
3078                 echo -n " ${var}=\"$value\""
3079         done
3080
3081         for facet in ${facets//,/ }; do
3082                 var=${facet}_FSTYPE
3083                 if [ -n "${!var}" ]; then
3084                         echo -n " $var=${!var}"
3085                 fi
3086         done
3087
3088         for var in MGSFSTYPE MDSFSTYPE OSTFSTYPE; do
3089                 if [ -n "${!var}" ]; then
3090                         echo -n " $var=${!var}"
3091                 fi
3092         done
3093
3094         for var in VERBOSE; do
3095                 if [ -n "${!var}" ]; then
3096                         echo -n " $var=${!var}"
3097                 fi
3098         done
3099
3100         if [ -n "$FSTYPE" ]; then
3101                 echo -n " FSTYPE=$FSTYPE"
3102         fi
3103
3104         for var in LNETLND NETTYPE; do
3105                 if [ -n "${!var}" ]; then
3106                         echo -n " $var=${!var}"
3107                 fi
3108         done
3109 }
3110
3111 do_nodes() {
3112     local verbose=false
3113     # do not stripe off hostname if verbose, bug 19215
3114     if [ x$1 = x--verbose ]; then
3115         shift
3116         verbose=true
3117     fi
3118
3119     local rnodes=$1
3120     shift
3121
3122     if single_local_node $rnodes; then
3123         if $verbose; then
3124            do_nodev $rnodes "$@"
3125         else
3126            do_node $rnodes "$@"
3127         fi
3128         return $?
3129     fi
3130
3131     # This is part from do_node
3132     local myPDSH=$PDSH
3133
3134     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
3135         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
3136
3137     export FANOUT=$(get_node_count "${rnodes//,/ }")
3138     if $VERBOSE; then
3139         echo "CMD: $rnodes $@" >&2
3140         $myPDSH $rnodes "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
3141     fi
3142
3143     # do not replace anything from pdsh output if -N is used
3144     # -N     Disable hostname: prefix on lines of output.
3145     if $verbose || [[ $myPDSH = *-N* ]]; then
3146         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")"
3147     else
3148         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")" | sed -re "s/^[^:]*: //g"
3149     fi
3150     return ${PIPESTATUS[0]}
3151 }
3152
3153 ##
3154 # Execute commands on a single service's host
3155 #
3156 # The \a facet (service) may be on a local or remote node, which is
3157 # determined at the time the command is run.
3158 #
3159 # usage: do_facet $facet command [arg ...]
3160 do_facet() {
3161         local facet=$1
3162         shift
3163         local HOST=$(facet_active_host $facet)
3164         [ -z $HOST ] && echo "No host defined for facet ${facet}" && exit 1
3165         do_node $HOST "$@"
3166 }
3167
3168 # Function: do_facet_random_file $FACET $FILE $SIZE
3169 # Creates FILE with random content on the given FACET of given SIZE
3170
3171 do_facet_random_file() {
3172         local facet="$1"
3173         local fpath="$2"
3174         local fsize="$3"
3175         local cmd="dd if=/dev/urandom of='$fpath' bs=$fsize count=1"
3176         do_facet $facet "$cmd 2>/dev/null"
3177 }
3178
3179 do_facet_create_file() {
3180         local facet="$1"
3181         local fpath="$2"
3182         local fsize="$3"
3183         local cmd="dd if=/dev/zero of='$fpath' bs=$fsize count=1"
3184         do_facet $facet "$cmd 2>/dev/null"
3185 }
3186
3187 do_nodesv() {
3188     do_nodes --verbose "$@"
3189 }
3190
3191 add() {
3192         local facet=$1
3193         shift
3194         # make sure its not already running
3195         stop ${facet} -f
3196         rm -f $TMP/${facet}active
3197         [[ $facet = mds1 ]] && combined_mgs_mds && rm -f $TMP/mgsactive
3198         do_facet ${facet} $MKFS $* || return ${PIPESTATUS[0]}
3199
3200         if [[ $(facet_fstype $facet) == zfs ]]; then
3201                 #
3202                 # After formatting a ZFS target, "cachefile=none" property will
3203                 # be set on the ZFS storage pool so that the pool is not
3204                 # automatically imported on system startup. And then the pool
3205                 # will be exported so as to leave the importing and exporting
3206                 # operations handled by mount_facet() and stop() separately.
3207                 #
3208                 refresh_partition_table $facet $(facet_vdevice $facet)
3209                 disable_zpool_cache $facet
3210                 export_zpool $facet
3211         fi
3212 }
3213
3214 # Device formatted as ost
3215 ostdevname() {
3216         local num=$1
3217         local DEVNAME=OSTDEV$num
3218
3219         local fstype=$(facet_fstype ost$num)
3220
3221         case $fstype in
3222                 ldiskfs )
3223                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
3224                         eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
3225                 zfs )
3226                         #try $OSTZFSDEVn - independent of vdev
3227                         DEVNAME=OSTZFSDEV$num
3228                         eval DEVPTR=${!DEVNAME:=${FSNAME}-ost${num}/ost${num}};;
3229                 * )
3230                         error "unknown fstype!";;
3231         esac
3232
3233     echo -n $DEVPTR
3234 }
3235
3236 # Physical device location of data
3237 ostvdevname() {
3238         local num=$1
3239         local DEVNAME
3240         local VDEVPTR
3241
3242         local fstype=$(facet_fstype ost$num)
3243
3244         case $fstype in
3245                 ldiskfs )
3246                         # vdevs are not supported by ldiskfs
3247                         eval VDEVPTR="";;
3248                 zfs )
3249                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE{n}
3250                         # Device formatted by zfs
3251                         DEVNAME=OSTDEV$num
3252                         eval VDEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
3253                 * )
3254                         error "unknown fstype!";;
3255         esac
3256
3257         echo -n $VDEVPTR
3258 }
3259
3260 # Logical device formatted for lustre
3261 mdsdevname() {
3262         local num=$1
3263         local DEVNAME=MDSDEV$num
3264
3265         local fstype=$(facet_fstype mds$num)
3266
3267         case $fstype in
3268                 ldiskfs )
3269                         #if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
3270                         eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
3271                 zfs )
3272                         # try $MDSZFSDEVn - independent of vdev
3273                         DEVNAME=MDSZFSDEV$num
3274                         eval DEVPTR=${!DEVNAME:=${FSNAME}-mdt${num}/mdt${num}};;
3275                 * )
3276                         error "unknown fstype!";;
3277         esac
3278
3279         echo -n $DEVPTR
3280 }
3281
3282 # Physical location of data
3283 mdsvdevname() {
3284         local VDEVPTR=""
3285         local num=$1
3286         local fstype=$(facet_fstype mds$num)
3287
3288         case $fstype in
3289                 ldiskfs )
3290                         # vdevs are not supported by ldiskfs
3291                         eval VDEVPTR="";;
3292                 zfs )
3293                         # if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
3294                         # Device formatted by ZFS
3295                         local DEVNAME=MDSDEV$num
3296                         eval VDEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
3297                 * )
3298                         error "unknown fstype!";;
3299         esac
3300
3301         echo -n $VDEVPTR
3302 }
3303
3304 mgsdevname() {
3305         local DEVPTR
3306         local fstype=$(facet_fstype mgs)
3307
3308         case $fstype in
3309         ldiskfs )
3310                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3311                    ( [ -z "$MGSDEV" ] || [ $MGSDEV = $(mdsdevname 1) ] ); then
3312                         DEVPTR=$(mdsdevname 1)
3313                 else
3314                         DEVPTR=$MGSDEV
3315                 fi;;
3316         zfs )
3317                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3318                     ( [ -z "$MGSZFSDEV" ] &&
3319                         [ -z "$MGSDEV" -o "$MGSDEV" = $(mdsvdevname 1) ] ); then
3320                         DEVPTR=$(mdsdevname 1)
3321                 else
3322                         DEVPTR=${MGSZFSDEV:-${FSNAME}-mgs/mgs}
3323                 fi;;
3324         * )
3325                 error "unknown fstype!";;
3326         esac
3327
3328         echo -n $DEVPTR
3329 }
3330
3331 mgsvdevname() {
3332         local VDEVPTR=""
3333
3334         local fstype=$(facet_fstype mgs)
3335
3336         case $fstype in
3337         ldiskfs )
3338                 # vdevs are not supported by ldiskfs
3339                 ;;
3340         zfs )
3341                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3342                    ( [ -z "$MGSDEV" ] &&
3343                        [ -z "$MGSZFSDEV" -o "$MGSZFSDEV" = $(mdsdevname 1) ]); then
3344                         VDEVPTR=$(mdsvdevname 1)
3345                 elif [ -n "$MGSDEV" ]; then
3346                         VDEVPTR=$MGSDEV
3347                 fi;;
3348         * )
3349                 error "unknown fstype!";;
3350         esac
3351
3352         echo -n $VDEVPTR
3353 }
3354
3355 facet_mntpt () {
3356     local facet=$1
3357     [[ $facet = mgs ]] && combined_mgs_mds && facet="mds1"
3358
3359     local var=${facet}_MOUNT
3360     eval mntpt=${!var:-${MOUNT}-$facet}
3361
3362     echo -n $mntpt
3363 }
3364
3365 mount_ldiskfs() {
3366         local facet=$1
3367         local dev=$(facet_device $facet)
3368         local mnt=${2:-$(facet_mntpt $facet)}
3369         local opts
3370
3371         if ! do_facet $facet test -b $dev; then
3372                 opts="-o loop"
3373         fi
3374         do_facet $facet mount -t ldiskfs $opts $dev $mnt
3375 }
3376
3377 unmount_ldiskfs() {
3378         local facet=$1
3379         local dev=$(facet_device $facet)
3380         local mnt=${2:-$(facet_mntpt $facet)}
3381
3382         do_facet $facet $UMOUNT $mnt
3383 }
3384
3385 var_name() {
3386         echo -n "$1" | tr -c '[:alnum:]\n' '_'
3387 }
3388
3389 mount_zfs() {
3390         local facet=$1
3391         local ds=$(facet_device $facet)
3392         local mnt=${2:-$(facet_mntpt $facet)}
3393         local canmnt
3394         local mntpt
3395
3396         import_zpool $facet
3397         canmnt=$(do_facet $facet $ZFS get -H -o value canmount $ds)
3398         mntpt=$(do_facet $facet $ZFS get -H -o value mountpoint $ds)
3399         do_facet $facet $ZFS set canmount=noauto $ds
3400         #
3401         # The "legacy" mount method is used here because "zfs unmount $mnt"
3402         # calls stat(2) on $mnt/../*, which may include $MOUNT.  If certain
3403         # targets are not available at the time, the stat(2) on $MOUNT will
3404         # hang.
3405         #
3406         do_facet $facet $ZFS set mountpoint=legacy $ds
3407         do_facet $facet mount -t zfs $ds $mnt
3408         eval export mz_$(var_name ${facet}_$ds)_canmount=$canmnt
3409         eval export mz_$(var_name ${facet}_$ds)_mountpoint=$mntpt
3410 }
3411
3412 unmount_zfs() {
3413         local facet=$1
3414         local ds=$(facet_device $facet)
3415         local mnt=${2:-$(facet_mntpt $facet)}
3416         local var_mntpt=mz_$(var_name ${facet}_$ds)_mountpoint
3417         local var_canmnt=mz_$(var_name ${facet}_$ds)_canmount
3418         local mntpt=${!var_mntpt}
3419         local canmnt=${!var_canmnt}
3420
3421         unset $var_mntpt
3422         unset $var_canmnt
3423         do_facet $facet umount $mnt
3424         do_facet $facet $ZFS set mountpoint=$mntpt $ds
3425         do_facet $facet $ZFS set canmount=$canmnt $ds
3426         export_zpool $facet
3427 }
3428
3429 mount_fstype() {
3430         local facet=$1
3431         local mnt=$2
3432         local fstype=$(facet_fstype $facet)
3433
3434         mount_$fstype $facet $mnt
3435 }
3436
3437 unmount_fstype() {
3438         local facet=$1
3439         local mnt=$2
3440         local fstype=$(facet_fstype $facet)
3441
3442         unmount_$fstype $facet $mnt
3443 }
3444
3445 ########
3446 ## MountConf setup
3447
3448 stopall() {
3449     # make sure we are using the primary server, so test-framework will
3450     # be able to clean up properly.
3451     activemds=`facet_active mds1`
3452     if [ $activemds != "mds1" ]; then
3453         fail mds1
3454     fi
3455
3456     local clients=$CLIENTS
3457     [ -z $clients ] && clients=$(hostname)
3458
3459     zconf_umount_clients $clients $MOUNT "$*" || true
3460     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
3461
3462     [ -n "$CLIENTONLY" ] && return
3463
3464     # The add fn does rm ${facet}active file, this would be enough
3465     # if we use do_facet <facet> only after the facet added, but
3466     # currently we use do_facet mds in local.sh
3467     for num in `seq $MDSCOUNT`; do
3468         stop mds$num -f
3469         rm -f ${TMP}/mds${num}active
3470     done
3471     combined_mgs_mds && rm -f $TMP/mgsactive
3472
3473     for num in `seq $OSTCOUNT`; do
3474         stop ost$num -f
3475         rm -f $TMP/ost${num}active
3476     done
3477
3478     if ! combined_mgs_mds ; then
3479         stop mgs
3480     fi
3481
3482     return 0
3483 }
3484
3485 cleanup_echo_devs () {
3486         trap 0
3487         local dev
3488         local devs=$($LCTL dl | grep echo | awk '{print $4}')
3489
3490         for dev in $devs; do
3491                 $LCTL --device $dev cleanup
3492                 $LCTL --device $dev detach
3493         done
3494 }
3495
3496 cleanupall() {
3497     nfs_client_mode && return
3498         cifs_client_mode && return
3499
3500     stopall $*
3501     cleanup_echo_devs
3502
3503     unload_modules
3504     cleanup_gss
3505 }
3506
3507 combined_mgs_mds () {
3508         [[ "$(mdsdevname 1)" = "$(mgsdevname)" ]] &&
3509                 [[ "$(facet_host mds1)" = "$(facet_host mgs)" ]]
3510 }
3511
3512 lower() {
3513         echo -n "$1" | tr '[:upper:]' '[:lower:]'
3514 }
3515
3516 upper() {
3517         echo -n "$1" | tr '[:lower:]' '[:upper:]'
3518 }
3519
3520 mkfs_opts() {
3521         local facet=$1
3522         local dev=$2
3523         local fsname=${3:-"$FSNAME"}
3524         local type=$(facet_type $facet)
3525         local index=$(facet_index $facet)
3526         local fstype=$(facet_fstype $facet)
3527         local host=$(facet_host $facet)
3528         local opts
3529         local fs_mkfs_opts
3530         local var
3531
3532         if [ $type == MGS ] || ( [ $type == MDS ] &&
3533                                  [ "$dev" == $(mgsdevname) ] &&
3534                                  [ "$host" == "$(facet_host mgs)" ] ); then
3535                 opts="--mgs"
3536         else
3537                 opts="--mgsnode=$MGSNID"
3538         fi
3539
3540         if [ $type != MGS ]; then
3541                 opts+=" --fsname=$fsname --$(lower ${type/MDS/MDT}) \
3542                         --index=$index"
3543         fi
3544
3545         var=${facet}failover_HOST
3546         if [ -n "${!var}" ] && [ ${!var} != $(facet_host $facet) ]; then
3547                 opts+=" --failnode=$(h2$NETTYPE ${!var})"
3548         fi
3549
3550         opts+=${TIMEOUT:+" --param=sys.timeout=$TIMEOUT"}
3551         opts+=${LDLM_TIMEOUT:+" --param=sys.ldlm_timeout=$LDLM_TIMEOUT"}
3552
3553         if [ $type == MDS ]; then
3554                 opts+=${MDSCAPA:+" --param-mdt.capa=$MDSCAPA"}
3555                 opts+=${STRIPE_BYTES:+" --param=lov.stripesize=$STRIPE_BYTES"}
3556                 opts+=${STRIPES_PER_OBJ:+" --param=lov.stripecount=$STRIPES_PER_OBJ"}
3557                 opts+=${L_GETIDENTITY:+" --param=mdt.identity_upcall=$L_GETIDENTITY"}
3558
3559                 if [ $fstype == ldiskfs ]; then
3560                         # Check for wide striping
3561                         if [ $OSTCOUNT -gt 160 ]; then
3562                                 MDSJOURNALSIZE=${MDSJOURNALSIZE:-4096}
3563                                 fs_mkfs_opts+="-O large_xattr"
3564                         fi
3565
3566                         var=${facet}_JRN
3567                         if [ -n "${!var}" ]; then
3568                                 fs_mkfs_opts+=" -J device=${!var}"
3569                         else
3570                                 fs_mkfs_opts+=${MDSJOURNALSIZE:+" -J size=$MDSJOURNALSIZE"}
3571                         fi
3572                         fs_mkfs_opts+=${MDSISIZE:+" -i $MDSISIZE"}
3573                 fi
3574         fi
3575
3576         if [ $type == OST ]; then
3577                 opts+=${OSSCAPA:+" --param=ost.capa=$OSSCAPA"}
3578
3579                 if [ $fstype == ldiskfs ]; then
3580                         var=${facet}_JRN
3581                         if [ -n "${!var}" ]; then
3582                                 fs_mkfs_opts+=" -J device=${!var}"
3583                         else
3584                                 fs_mkfs_opts+=${OSTJOURNALSIZE:+" -J size=$OSTJOURNALSIZE"}
3585                         fi
3586                 fi
3587         fi
3588
3589         opts+=" --backfstype=$fstype"
3590
3591         var=${type}SIZE
3592         if [ -n "${!var}" ]; then
3593                 opts+=" --device-size=${!var}"
3594         fi
3595
3596         var=$(upper $fstype)_MKFS_OPTS
3597         fs_mkfs_opts+=${!var:+" ${!var}"}
3598
3599         var=${type}_FS_MKFS_OPTS
3600         fs_mkfs_opts+=${!var:+" ${!var}"}
3601
3602         if [ -n "${fs_mkfs_opts## }" ]; then
3603                 opts+=" --mkfsoptions=\\\"${fs_mkfs_opts## }\\\""
3604         fi
3605
3606         var=${type}OPT
3607         opts+=${!var:+" ${!var}"}
3608
3609         echo -n "$opts"
3610 }
3611
3612 check_ost_indices() {
3613         local index_count=${#OST_INDICES[@]}
3614         [[ $index_count -eq 0 || $OSTCOUNT -le $index_count ]] && return 0
3615
3616         # OST count is greater than the index count in $OST_INDEX_LIST.
3617         # We need check whether there are duplicate indices.
3618         local i
3619         local j
3620         local index
3621         for i in $(seq $((index_count + 1)) $OSTCOUNT); do
3622                 index=$(facet_index ost$i)
3623                 for j in $(seq 0 $((index_count - 1))); do
3624                         [[ $index -ne ${OST_INDICES[j]} ]] ||
3625                         error "ost$i has the same index $index as ost$((j+1))"
3626                 done
3627         done
3628 }
3629
3630 format_mgs() {
3631         local quiet
3632
3633         if ! $VERBOSE; then
3634                 quiet=yes
3635         fi
3636         echo "Format mgs: $(mgsdevname)"
3637         reformat_external_journal mgs
3638         add mgs $(mkfs_opts mgs $(mgsdevname)) --reformat \
3639                 $(mgsdevname) $(mgsvdevname) ${quiet:+>/dev/null} || exit 10
3640 }
3641
3642 format_mdt() {
3643         local num=$1
3644         local quiet
3645
3646         if ! $VERBOSE; then
3647                 quiet=yes
3648         fi
3649         echo "Format mds$num: $(mdsdevname $num)"
3650         reformat_external_journal mds$num
3651         add mds$num $(mkfs_opts mds$num $(mdsdevname ${num})) \
3652                 --reformat $(mdsdevname $num) $(mdsvdevname $num) \
3653                 ${quiet:+>/dev/null} || exit 10
3654 }
3655
3656 format_ost() {
3657         local num=$1
3658
3659         if ! $VERBOSE; then
3660                 quiet=yes
3661         fi
3662         echo "Format ost$num: $(ostdevname $num)"
3663         reformat_external_journal ost$num
3664         add ost$num $(mkfs_opts ost$num $(ostdevname ${num})) \
3665                 --reformat $(ostdevname $num) $(ostvdevname ${num}) \
3666                 ${quiet:+>/dev/null} || exit 10
3667 }
3668
3669 formatall() {
3670         stopall
3671         # Set hostid for ZFS/SPL zpool import protection
3672         # (Assumes MDS version is also OSS version)
3673         if [ $(lustre_version_code $SINGLEMDS) -ge $(version_code 2.8.54) ];
3674         then
3675             do_rpc_nodes "$(comma_list $(remote_nodes_list))" set_hostid
3676         fi
3677
3678         # We need ldiskfs here, may as well load them all
3679         load_modules
3680         [ -n "$CLIENTONLY" ] && return
3681         echo Formatting mgs, mds, osts
3682         if ! combined_mgs_mds ; then
3683                 format_mgs
3684         fi
3685
3686         for num in $(seq $MDSCOUNT); do
3687                 format_mdt $num
3688         done
3689
3690         export OST_INDICES=($(hostlist_expand "$OST_INDEX_LIST"))
3691         check_ost_indices
3692         for num in $(seq $OSTCOUNT); do
3693                 format_ost $num
3694         done
3695 }
3696
3697 mount_client() {
3698     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
3699 }
3700
3701 umount_client() {
3702     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
3703 }
3704
3705 # return value:
3706 # 0: success, the old identity set already.
3707 # 1: success, the old identity does not set.
3708 # 2: fail.
3709 switch_identity() {
3710     local num=$1
3711     local switch=$2
3712     local j=`expr $num - 1`
3713     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
3714
3715     if [ -z "$MDT" ]; then
3716         return 2
3717     fi
3718
3719     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
3720
3721     if $switch; then
3722         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
3723     else
3724         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
3725     fi
3726
3727     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush=-1"
3728
3729     if [ $old = "NONE" ]; then
3730         return 1
3731     else
3732         return 0
3733     fi
3734 }
3735
3736 remount_client()
3737 {
3738         zconf_umount `hostname` $1 || error "umount failed"
3739         zconf_mount `hostname` $1 || error "mount failed"
3740 }
3741
3742 writeconf_facet() {
3743         local facet=$1
3744         local dev=$2
3745
3746         stop ${facet} -f
3747         rm -f $TMP/${facet}active
3748         do_facet ${facet} "$TUNEFS --quiet --writeconf $dev" || return 1
3749         return 0
3750 }
3751
3752 writeconf_all () {
3753         local mdt_count=${1:-$MDSCOUNT}
3754         local ost_count=${2:-$OSTCOUNT}
3755         local rc=0
3756
3757         for num in $(seq $mdt_count); do
3758                 DEVNAME=$(mdsdevname $num)
3759                 writeconf_facet mds$num $DEVNAME || rc=$?
3760         done
3761
3762         for num in $(seq $ost_count); do
3763                 DEVNAME=$(ostdevname $num)
3764                 writeconf_facet ost$num $DEVNAME || rc=$?
3765         done
3766         return $rc
3767 }
3768
3769 setupall() {
3770         local arg1=$1
3771
3772         nfs_client_mode && return
3773         cifs_client_mode && return
3774
3775         sanity_mount_check || error "environments are insane!"
3776
3777         load_modules
3778
3779         if [ -z "$CLIENTONLY" ]; then
3780                 echo Setup mgs, mdt, osts
3781                 echo $WRITECONF | grep -q "writeconf" && writeconf_all
3782                 if ! combined_mgs_mds ; then
3783                         start mgs $(mgsdevname) $MGS_MOUNT_OPTS
3784                 fi
3785
3786         for num in `seq $MDSCOUNT`; do
3787             DEVNAME=$(mdsdevname $num)
3788             start mds$num $DEVNAME $MDS_MOUNT_OPTS
3789
3790             # We started mds, now we should set failover variables properly.
3791             # Set mds${num}failover_HOST if it is not set (the default failnode).
3792             local varname=mds${num}failover_HOST
3793             if [ -z "${!varname}" ]; then
3794                 eval mds${num}failover_HOST=$(facet_host mds$num)
3795             fi
3796
3797             if [ $IDENTITY_UPCALL != "default" ]; then
3798                 switch_identity $num $IDENTITY_UPCALL
3799             fi
3800         done
3801         for num in `seq $OSTCOUNT`; do
3802             DEVNAME=$(ostdevname $num)
3803             start ost$num $DEVNAME $OST_MOUNT_OPTS
3804
3805             # We started ost$num, now we should set ost${num}failover variable properly.
3806             # Set ost${num}failover_HOST if it is not set (the default failnode).
3807             varname=ost${num}failover_HOST
3808             if [ -z "${!varname}" ]; then
3809                 eval ost${num}failover_HOST=$(facet_host ost${num})
3810             fi
3811
3812         done
3813     fi
3814
3815     init_gss
3816
3817     # wait a while to allow sptlrpc configuration be propogated to targets,
3818     # only needed when mounting new target devices.
3819     if $GSS; then
3820         sleep 10
3821     fi
3822
3823     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
3824
3825         if [ ! -z $arg1 ]; then
3826                 [ "$arg1" = "server_only" ] && return
3827         fi
3828
3829     mount_client $MOUNT
3830     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
3831     clients_up
3832
3833     if [ "$MOUNT_2" ]; then
3834         mount_client $MOUNT2
3835         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
3836     fi
3837
3838     init_param_vars
3839
3840     # by remounting mdt before ost, initial connect from mdt to ost might
3841     # timeout because ost is not ready yet. wait some time to its fully
3842     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
3843     # by a context negotiation rpc with $TIMEOUT.
3844     # FIXME better by monitoring import status.
3845     if $GSS; then
3846         set_flavor_all $SEC
3847         sleep $((TIMEOUT + 5))
3848     else
3849         sleep 5
3850     fi
3851 }
3852
3853 mounted_lustre_filesystems() {
3854         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
3855 }
3856
3857 init_facet_vars () {
3858         [ -n "$CLIENTONLY" ] && return 0
3859         local facet=$1
3860         shift
3861         local device=$1
3862
3863         shift
3864
3865         eval export ${facet}_dev=${device}
3866         eval export ${facet}_opt=\"$@\"
3867
3868         local dev=${facet}_dev
3869
3870         # We need to loop for the label
3871         # in case its not initialized yet.
3872         for wait_time in {0,1,3,5,10}; do
3873
3874                 if [ $wait_time -gt 0 ]; then
3875                         echo "${!dev} not yet initialized,"\
3876                                 "waiting ${wait_time} seconds."
3877                         sleep $wait_time
3878                 fi
3879
3880                 local label=$(devicelabel ${facet} ${!dev})
3881
3882                 # Check to make sure the label does
3883                 # not include ffff at the end of the label.
3884                 # This indicates it has not been initialized yet.
3885
3886                 if [[ $label =~ [f|F]{4}$ ]]; then
3887                         # label is not initialized, unset the result
3888                         # and either try again or fail
3889                         unset label
3890                 else
3891                         break
3892                 fi
3893         done
3894
3895         [ -z "$label" ] && echo no label for ${!dev} && exit 1
3896
3897         eval export ${facet}_svc=${label}
3898
3899         local varname=${facet}failover_HOST
3900         if [ -z "${!varname}" ]; then
3901                 eval export $varname=$(facet_host $facet)
3902         fi
3903
3904         varname=${facet}_HOST
3905         if [ -z "${!varname}" ]; then
3906                 eval export $varname=$(facet_host $facet)
3907         fi
3908
3909         # ${facet}failover_dev is set in cfg file
3910         varname=${facet}failover_dev
3911         if [ -n "${!varname}" ] ; then
3912                 eval export ${facet}failover_dev=${!varname}
3913         else
3914                 eval export ${facet}failover_dev=$device
3915         fi
3916
3917         # get mount point of already mounted device
3918         # is facet_dev is already mounted then use the real
3919         #  mount point of this facet; otherwise use $(facet_mntpt $facet)
3920         # i.e. ${facet}_MOUNT if specified by user or default
3921         local mntpt=$(do_facet ${facet} cat /proc/mounts | \
3922                         awk '"'${!dev}'" == $1 && $3 == "lustre" { print $2 }')
3923         if [ -z $mntpt ]; then
3924                 mntpt=$(facet_mntpt $facet)
3925         fi
3926         eval export ${facet}_MOUNT=$mntpt
3927 }
3928
3929 init_facets_vars () {
3930         local DEVNAME
3931
3932         if ! remote_mds_nodsh; then
3933                 for num in $(seq $MDSCOUNT); do
3934                         DEVNAME=`mdsdevname $num`
3935                         init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
3936                 done
3937         fi
3938
3939         combined_mgs_mds || init_facet_vars mgs $(mgsdevname) $MGS_MOUNT_OPTS
3940
3941         if ! remote_ost_nodsh; then
3942                 for num in $(seq $OSTCOUNT); do
3943                         DEVNAME=$(ostdevname $num)
3944                         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
3945                 done
3946         fi
3947 }
3948
3949 osc_ensure_active () {
3950     local facet=$1
3951     local timeout=$2
3952     local period=0
3953
3954     while [ $period -lt $timeout ]; do
3955         count=$(do_facet $facet "lctl dl | grep ' IN osc ' 2>/dev/null | wc -l")
3956         if [ $count -eq 0 ]; then
3957             break
3958         fi
3959
3960         echo "There are $count OST are inactive, wait $period seconds, and try again"
3961         sleep 3
3962         period=$((period+3))
3963     done
3964
3965     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
3966 }
3967
3968 set_conf_param_and_check() {
3969         local myfacet=$1
3970         local TEST=$2
3971         local PARAM=$3
3972         local ORIG=$(do_facet $myfacet "$TEST")
3973         if [ $# -gt 3 ]; then
3974                 local FINAL=$4
3975         else
3976                 local -i FINAL
3977                 FINAL=$((ORIG + 5))
3978         fi
3979         echo "Setting $PARAM from $ORIG to $FINAL"
3980         do_facet mgs "$LCTL conf_param $PARAM='$FINAL'" ||
3981                 error "conf_param $PARAM failed"
3982
3983         wait_update_facet $myfacet "$TEST" "$FINAL" ||
3984                 error "check $PARAM failed!"
3985 }
3986
3987 init_param_vars () {
3988         TIMEOUT=$(lctl get_param -n timeout)
3989         TIMEOUT=${TIMEOUT:-20}
3990
3991         remote_mds_nodsh && log "Using TIMEOUT=$TIMEOUT" && return 0
3992
3993         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
3994         log "Using TIMEOUT=$TIMEOUT"
3995
3996         osc_ensure_active $SINGLEMDS $TIMEOUT
3997         osc_ensure_active client $TIMEOUT
3998
3999         if [ -n "$(lctl get_param -n mdc.*.connect_flags|grep jobstats)" ]; then
4000                 local current_jobid_var=$($LCTL get_param -n jobid_var)
4001
4002                 if [ $JOBID_VAR = "existing" ]; then
4003                         echo "keeping jobstats as $current_jobid_var"
4004                 elif [ $current_jobid_var != $JOBID_VAR ]; then
4005                         echo "seting jobstats to $JOBID_VAR"
4006
4007                         set_conf_param_and_check client                 \
4008                                 "$LCTL get_param -n jobid_var"          \
4009                                 "$FSNAME.sys.jobid_var" $JOBID_VAR
4010                 fi
4011         else
4012                 echo "jobstats not supported by server"
4013         fi
4014
4015         if [ $QUOTA_AUTO -ne 0 ]; then
4016                 if [ "$ENABLE_QUOTA" ]; then
4017                         echo "enable quota as required"
4018                         setup_quota $MOUNT || return 2
4019                 else
4020                         echo "disable quota as required"
4021                         # $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
4022                 fi
4023         fi
4024         return 0
4025 }
4026
4027 nfs_client_mode () {
4028     if [ "$NFSCLIENT" ]; then
4029         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
4030         local clients=$CLIENTS
4031         [ -z $clients ] && clients=$(hostname)
4032
4033         # FIXME: remove hostname when 19215 fixed
4034         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
4035         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
4036         if [[ ${#nfsexport[@]} -eq 0 ]]; then
4037                 error_exit NFSCLIENT=$NFSCLIENT mode, but no NFS export found!
4038         fi
4039         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
4040         return
4041     fi
4042     return 1
4043 }
4044
4045 cifs_client_mode () {
4046         [ x$CIFSCLIENT = xyes ] &&
4047                 echo "CIFSCLIENT=$CIFSCLIENT mode: setup, cleanup, check config skipped"
4048 }
4049
4050 check_config_client () {
4051     local mntpt=$1
4052
4053     local mounted=$(mount | grep " $mntpt ")
4054     if [ -n "$CLIENTONLY" ]; then
4055         # bug 18021
4056         # CLIENTONLY should not depend on *_HOST settings
4057         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
4058         # in theory someone could create a new,
4059         # client-only config file that assumed lustre was already
4060         # configured and didn't set the MGSNID. If MGSNID is not set,
4061         # then we should use the mgs nid currently being used
4062         # as the default value. bug 18021
4063         [[ x$MGSNID = x ]] &&
4064             MGSNID=${mgc//MGC/}
4065
4066         if [[ x$mgc != xMGC$MGSNID ]]; then
4067             if [ "$mgs_HOST" ]; then
4068                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
4069 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
4070 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
4071             fi
4072         fi
4073         return 0
4074     fi
4075
4076     local myMGS_host=$mgs_HOST
4077     if [ "$NETTYPE" = "ptl" ]; then
4078         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//)
4079     fi
4080
4081     echo Checking config lustre mounted on $mntpt
4082     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
4083     mgshost=$(echo $mgshost | awk -F: '{print $1}')
4084
4085 #    if [ "$mgshost" != "$myMGS_host" ]; then
4086 #            log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
4087 #                   Please use correct config or set mds_HOST correctly!"
4088 #    fi
4089
4090 }
4091
4092 check_config_clients () {
4093         local clients=${CLIENTS:-$HOSTNAME}
4094         local mntpt=$1
4095
4096         nfs_client_mode && return
4097         cifs_client_mode && return
4098
4099         do_rpc_nodes "$clients" check_config_client $mntpt
4100
4101         sanity_mount_check || error "environments are insane!"
4102 }
4103
4104 check_timeout () {
4105     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
4106     local cltimeout=$(lctl get_param -n timeout)
4107     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
4108         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
4109         return 1
4110     fi
4111 }
4112
4113 is_mounted () {
4114     local mntpt=$1
4115     [ -z $mntpt ] && return 1
4116     local mounted=$(mounted_lustre_filesystems)
4117
4118     echo $mounted' ' | grep -w -q $mntpt' '
4119 }
4120
4121 is_empty_dir() {
4122         [ $(find $1 -maxdepth 1 -print | wc -l) = 1 ] && return 0
4123         return 1
4124 }
4125
4126 # empty lustre filesystem may have empty directories lost+found and .lustre
4127 is_empty_fs() {
4128         # exclude .lustre & lost+found
4129         [ $(find $1 -maxdepth 1 -name lost+found -o -name .lustre -prune -o \
4130                 -print | wc -l) = 1 ] || return 1
4131         [ ! -d $1/lost+found ] || is_empty_dir $1/lost+found || return 1
4132         if [ $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.4.0) ]; then
4133                 # exclude .lustre/fid (LU-2780)
4134                 [ $(find $1/.lustre -maxdepth 1 -name fid -prune -o \
4135                         -print | wc -l) = 1 ] || return 1
4136         else
4137                 [ ! -d $1/.lustre ] || is_empty_dir $1/.lustre || return 1
4138         fi
4139         return 0
4140 }
4141
4142 check_and_setup_lustre() {
4143         sanitize_parameters
4144         nfs_client_mode && return
4145         cifs_client_mode && return
4146
4147         local MOUNTED=$(mounted_lustre_filesystems)
4148
4149         local do_check=true
4150         # 1.
4151         # both MOUNT and MOUNT2 are not mounted
4152         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
4153                 [ "$REFORMAT" = "yes" ] && formatall
4154                 # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
4155                 setupall
4156                 is_mounted $MOUNT || error "NAME=$NAME not mounted"
4157                 export I_MOUNTED=yes
4158                 do_check=false
4159     # 2.
4160     # MOUNT2 is mounted
4161     elif is_mounted $MOUNT2; then
4162             # 3.
4163             # MOUNT2 is mounted, while MOUNT_2 is not set
4164             if ! [ "$MOUNT_2" ]; then
4165                 cleanup_mount $MOUNT2
4166                 export I_UMOUNTED2=yes
4167
4168             # 4.
4169             # MOUNT2 is mounted, MOUNT_2 is set
4170             else
4171                 # FIXME: what to do if check_config failed?
4172                 # i.e. if:
4173                 # 1) remote client has mounted other Lustre fs ?
4174                 # 2) it has insane env ?
4175                 # let's try umount MOUNT2 on all clients and mount it again:
4176                 if ! check_config_clients $MOUNT2; then
4177                     cleanup_mount $MOUNT2
4178                     restore_mount $MOUNT2
4179                     export I_MOUNTED2=yes
4180                 fi
4181             fi
4182
4183     # 5.
4184     # MOUNT is mounted MOUNT2 is not mounted
4185     elif [ "$MOUNT_2" ]; then
4186         restore_mount $MOUNT2
4187         export I_MOUNTED2=yes
4188     fi
4189
4190     if $do_check; then
4191         # FIXME: what to do if check_config failed?
4192         # i.e. if:
4193         # 1) remote client has mounted other Lustre fs?
4194         # 2) lustre is mounted on remote_clients atall ?
4195         check_config_clients $MOUNT
4196         init_facets_vars
4197         init_param_vars
4198
4199         set_default_debug_nodes $(comma_list $(nodes_list))
4200     fi
4201
4202         if [ -z "$CLIENTONLY" -a $(lower $OSD_TRACK_DECLARES_LBUG) == 'yes' ]; then
4203                 local facets=""
4204                 [ "$(facet_fstype ost1)" = "ldiskfs" ] &&
4205                         facets="$(get_facets OST)"
4206                 [ "$(facet_fstype mds1)" = "ldiskfs" ] &&
4207                         facets="$facets,$(get_facets MDS)"
4208                 [ "$(facet_fstype mgs)" = "ldiskfs" ] &&
4209                         facets="$facets,mgs"
4210                 local nodes="$(facets_hosts ${facets})"
4211                 if [ -n "$nodes" ] ; then
4212                         do_nodes $nodes "$LCTL set_param \
4213                                  osd-ldiskfs.track_declares_assert=1 || true"
4214                 fi
4215         fi
4216
4217         init_gss
4218         if $GSS; then
4219                 set_flavor_all $SEC
4220         fi
4221
4222         if [ -z "$CLIENTONLY" ]; then
4223                 # Enable remote MDT create for testing
4224                 for num in $(seq $MDSCOUNT); do
4225                         do_facet mds$num \
4226                                 lctl set_param -n mdt.${FSNAME}*.enable_remote_dir=1 \
4227                                         2>/dev/null
4228                 done
4229         fi
4230
4231         if [ "$ONLY" == "setup" ]; then
4232                 exit 0
4233         fi
4234 }
4235
4236 restore_mount () {
4237    local clients=${CLIENTS:-$HOSTNAME}
4238    local mntpt=$1
4239
4240    zconf_mount_clients $clients $mntpt
4241 }
4242
4243 cleanup_mount () {
4244         local clients=${CLIENTS:-$HOSTNAME}
4245         local mntpt=$1
4246
4247         zconf_umount_clients $clients $mntpt
4248 }
4249
4250 cleanup_and_setup_lustre() {
4251     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
4252         lctl set_param debug=0 || true
4253         cleanupall
4254         if [ "$ONLY" == "cleanup" ]; then
4255             exit 0
4256         fi
4257     fi
4258     check_and_setup_lustre
4259 }
4260
4261 # Get all of the server target devices from a given server node and type.
4262 get_mnt_devs() {
4263         local node=$1
4264         local type=$2
4265         local devs
4266         local dev
4267
4268         if [ "$type" == ost ]; then
4269                 devs=$(get_osd_param $node "" mntdev)
4270         else
4271                 devs=$(do_node $node $LCTL get_param -n osd-*.$FSNAME-M*.mntdev)
4272         fi
4273         for dev in $devs; do
4274                 case $dev in
4275                 *loop*) do_node $node "losetup $dev" | \
4276                                 sed -e "s/.*(//" -e "s/).*//" ;;
4277                 *) echo $dev ;;
4278                 esac
4279         done
4280 }
4281
4282 # Get all of the server target devices.
4283 get_svr_devs() {
4284         local node
4285         local i
4286
4287         # Master MDS parameters used by lfsck
4288         MDTNODE=$(facet_active_host $SINGLEMDS)
4289         MDTDEV=$(echo $(get_mnt_devs $MDTNODE mdt) | awk '{print $1}')
4290
4291         # MDT devices
4292         i=0
4293         for node in $(mdts_nodes); do
4294                 MDTDEVS[i]=$(get_mnt_devs $node mdt)
4295                 i=$((i + 1))
4296         done
4297
4298         # OST devices
4299         i=0
4300         for node in $(osts_nodes); do
4301                 OSTDEVS[i]=$(get_mnt_devs $node ost)
4302                 i=$((i + 1))
4303         done
4304 }
4305
4306 # Run e2fsck on MDT or OST device.
4307 run_e2fsck() {
4308         local node=$1
4309         local target_dev=$2
4310         local extra_opts=$3
4311         local cmd="$E2FSCK -d -v -t -t -f $extra_opts $target_dev"
4312         local log=$TMP/e2fsck.log
4313         local rc=0
4314
4315         echo $cmd
4316         do_node $node $cmd 2>&1 | tee $log
4317         rc=${PIPESTATUS[0]}
4318         if [ -n "$(grep "DNE mode isn't supported" $log)" ]; then
4319                 rm -f $log
4320                 if [ $MDSCOUNT -gt 1 ]; then
4321                         skip "DNE mode isn't supported!"
4322                         cleanupall
4323                         exit_status
4324                 else
4325                         error "It's not DNE mode."
4326                 fi
4327         fi
4328         rm -f $log
4329
4330         [ $rc -le $FSCK_MAX_ERR ] ||
4331                 error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
4332
4333         return 0
4334 }
4335
4336 #
4337 # Run resize2fs on MDT or OST device.
4338 #
4339 run_resize2fs() {
4340         local facet=$1
4341         local device=$2
4342         local size=$3
4343         shift 3
4344         local opts="$@"
4345
4346         do_facet $facet "$RESIZE2FS $opts $device $size"
4347 }
4348
4349 # verify a directory is shared among nodes.
4350 check_shared_dir() {
4351         local dir=$1
4352         local list=${2:-$(comma_list $(nodes_list))}
4353
4354         [ -z "$dir" ] && return 1
4355         do_rpc_nodes "$list" check_logdir $dir
4356         check_write_access $dir "$list" || return 1
4357         return 0
4358 }
4359
4360 run_lfsck() {
4361         do_nodes $(comma_list $(mdts_nodes) $(osts_nodes)) \
4362                 $LCTL set_param printk=+lfsck
4363         do_facet $SINGLEMDS "$LCTL lfsck_start -M $FSNAME-MDT0000 -r -A -t all"
4364
4365         for k in $(seq $MDSCOUNT); do
4366                 # wait up to 10+1 minutes for LFSCK to complete
4367                 wait_update_facet --verbose mds${k} "$LCTL get_param -n \
4368                         mdd.$(facet_svc mds${k}).lfsck_layout |
4369                         awk '/^status/ { print \\\$2 }'" "completed" 600 ||
4370                         error "MDS${k} layout isn't the expected 'completed'"
4371                 wait_update_facet --verbose mds${k} "$LCTL get_param -n \
4372                         mdd.$(facet_svc mds${k}).lfsck_namespace |
4373                         awk '/^status/ { print \\\$2 }'" "completed" 60 ||
4374                         error "MDS${k} namespace isn't the expected 'completed'"
4375         done
4376         local rep_mdt=$(do_nodes $(comma_list $(mdts_nodes)) \
4377                         $LCTL get_param -n mdd.$FSNAME-*.lfsck_* |
4378                         awk '/repaired/ { print $2 }' | calc_sum)
4379         local rep_ost=$(do_nodes $(comma_list $(osts_nodes)) \
4380                         $LCTL get_param -n obdfilter.$FSNAME-*.lfsck_* |
4381                         awk '/repaired/ { print $2 }' | calc_sum)
4382         local repaired=$((rep_mdt + rep_ost))
4383         [ $repaired -eq 0 ] ||
4384                 error "lfsck repaired $rep_mdt MDT and $rep_ost OST errors"
4385 }
4386
4387 dump_file_contents() {
4388         local nodes=$1
4389         local dir=$2
4390         local logname=$3
4391         local node
4392
4393         if [ -z "$nodes" -o -z "$dir" -o -z "$logname" ]; then
4394                 error_noexit false \
4395                         "Invalid parameters for dump_file_contents()"
4396                 return 1
4397         fi
4398         for node in ${nodes}; do
4399                 do_node $node "for i in \\\$(find $dir -type f); do
4400                                 echo ====\\\${i}=======================;
4401                                 cat \\\${i};
4402                                 done" >> ${logname}.${node}.log
4403         done
4404 }
4405
4406 dump_command_output() {
4407         local nodes=$1
4408         local cmd=$2
4409         local logname=$3
4410         local node
4411
4412         if [ -z "$nodes" -o -z "$cmd" -o -z "$logname" ]; then
4413                 error_noexit false \
4414                         "Invalid parameters for dump_command_output()"
4415                 return 1
4416         fi
4417
4418         for node in ${nodes}; do
4419                 do_node $node "echo ====${cmd}=======================;
4420                                 $cmd" >> ${logname}.${node}.log
4421         done
4422 }
4423
4424 log_zfs_info() {
4425         local logname=$1
4426
4427         # dump file contents from /proc/spl in case of zfs test
4428         if [ "$(facet_fstype ost1)" = "zfs" ]; then
4429                 dump_file_contents "$(osts_nodes)" "/proc/spl" "${logname}"
4430                 dump_command_output \
4431                         "$(osts_nodes)" "zpool events -v" "${logname}"
4432         fi
4433
4434         if [ "$(facet_fstype $SINGLEMDS)" = "zfs" ]; then
4435                 dump_file_contents "$(mdts_nodes)" "/proc/spl" "${logname}"
4436                 dump_command_output \
4437                         "$(mdts_nodes)" "zpool events -v" "${logname}"
4438         fi
4439 }
4440
4441 check_and_cleanup_lustre() {
4442         if [ "$LFSCK_ALWAYS" = "yes" -a "$TESTSUITE" != "sanity-lfsck" -a \
4443              "$TESTSUITE" != "sanity-scrub" ]; then
4444                 run_lfsck
4445         fi
4446
4447         if is_mounted $MOUNT; then
4448                 if $DO_CLEANUP; then
4449                         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]* ||
4450                                 error "remove sub-test dirs failed"
4451                 else
4452                         echo "skip cleanup"
4453                 fi
4454                 [ "$ENABLE_QUOTA" ] && restore_quota || true
4455         fi
4456
4457         if [ "$I_UMOUNTED2" = "yes" ]; then
4458                 restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
4459         fi
4460
4461         if [ "$I_MOUNTED2" = "yes" ]; then
4462                 cleanup_mount $MOUNT2
4463         fi
4464
4465         if [ "$I_MOUNTED" = "yes" ]; then
4466                 cleanupall -f || error "cleanup failed"
4467                 unset I_MOUNTED
4468         fi
4469 }
4470
4471 #######
4472 # General functions
4473
4474 wait_for_function () {
4475     local quiet=""
4476
4477     # suppress fn both stderr and stdout
4478     if [ "$1" = "--quiet" ]; then
4479         shift
4480         quiet=" > /dev/null 2>&1"
4481
4482     fi
4483
4484     local fn=$1
4485     local max=${2:-900}
4486     local sleep=${3:-5}
4487
4488     local wait=0
4489
4490     while true; do
4491
4492         eval $fn $quiet && return 0
4493
4494         wait=$((wait + sleep))
4495         [ $wait -lt $max ] || return 1
4496         echo waiting $fn, $((max - wait)) secs left ...
4497         sleep $sleep
4498     done
4499 }
4500
4501 check_network() {
4502     local host=$1
4503     local max=$2
4504     local sleep=${3:-5}
4505
4506     echo `date +"%H:%M:%S (%s)"` waiting for $host network $max secs ...
4507     if ! wait_for_function --quiet "ping -c 1 -w 3 $host" $max $sleep ; then
4508         echo "Network not available!"
4509         exit 1
4510     fi
4511
4512     echo `date +"%H:%M:%S (%s)"` network interface is UP
4513 }
4514
4515 no_dsh() {
4516     shift
4517     eval $@
4518 }
4519
4520 # Convert a space-delimited list to a comma-delimited list.  If the input is
4521 # only whitespace, ensure the output is empty (i.e. "") so [ -n $list ] works
4522 comma_list() {
4523         # echo is used to convert newlines to spaces, since it doesn't
4524         # introduce a trailing space as using "tr '\n' ' '" does
4525         echo $(tr -s " " "\n" <<< $* | sort -b -u) | tr ' ' ','
4526 }
4527
4528 list_member () {
4529     local list=$1
4530     local item=$2
4531     echo $list | grep -qw $item
4532 }
4533
4534 # list, excluded are the comma separated lists
4535 exclude_items_from_list () {
4536     local list=$1
4537     local excluded=$2
4538     local item
4539
4540     list=${list//,/ }
4541     for item in ${excluded//,/ }; do
4542         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
4543     done
4544     echo $(comma_list $list)
4545 }
4546
4547 # list, expand  are the comma separated lists
4548 expand_list () {
4549     local list=${1//,/ }
4550     local expand=${2//,/ }
4551     local expanded=
4552
4553     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
4554     echo $(comma_list $expanded)
4555 }
4556
4557 testslist_filter () {
4558     local script=$LUSTRE/tests/${TESTSUITE}.sh
4559
4560     [ -f $script ] || return 0
4561
4562     local start_at=$START_AT
4563     local stop_at=$STOP_AT
4564
4565     local var=${TESTSUITE//-/_}_START_AT
4566     [ x"${!var}" != x ] && start_at=${!var}
4567     var=${TESTSUITE//-/_}_STOP_AT
4568     [ x"${!var}" != x ] && stop_at=${!var}
4569
4570     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
4571         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
4572             /^'${start_at}'$/ {flag = 0}
4573             {if (flag == 1) print $0}
4574             /^'${stop_at}'$/ { flag = 1 }'
4575 }
4576
4577 absolute_path() {
4578     (cd `dirname $1`; echo $PWD/`basename $1`)
4579 }
4580
4581 get_facets () {
4582     local types=${1:-"OST MDS MGS"}
4583
4584     local list=""
4585
4586     for entry in $types; do
4587         local name=$(echo $entry | tr "[:upper:]" "[:lower:]")
4588         local type=$(echo $entry | tr "[:lower:]" "[:upper:]")
4589
4590         case $type in
4591                 MGS ) list="$list $name";;
4592             MDS|OST|AGT ) local count=${type}COUNT
4593                        for ((i=1; i<=${!count}; i++)) do
4594                           list="$list ${name}$i"
4595                       done;;
4596                   * ) error "Invalid facet type"
4597                  exit 1;;
4598         esac
4599     done
4600     echo $(comma_list $list)
4601 }
4602
4603 ##################################
4604 # Adaptive Timeouts funcs
4605
4606 at_is_enabled() {
4607     # only check mds, we assume at_max is the same on all nodes
4608     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
4609     if [ $at_max -eq 0 ]; then
4610         return 1
4611     else
4612         return 0
4613     fi
4614 }
4615
4616 at_get() {
4617     local facet=$1
4618     local at=$2
4619
4620     # suppose that all ost-s have the same $at value set
4621     [ $facet != "ost" ] || facet=ost1
4622
4623     do_facet $facet "lctl get_param -n $at"
4624 }
4625
4626 at_max_get() {
4627     at_get $1 at_max
4628 }
4629
4630 at_min_get() {
4631         at_get $1 at_min
4632 }
4633
4634 at_max_set() {
4635     local at_max=$1
4636     shift
4637
4638     local facet
4639     local hosts
4640     for facet in $@; do
4641         if [ $facet == "ost" ]; then
4642             facet=$(get_facets OST)
4643         elif [ $facet == "mds" ]; then
4644             facet=$(get_facets MDS)
4645         fi
4646         hosts=$(expand_list $hosts $(facets_hosts $facet))
4647     done
4648
4649     do_nodes $hosts lctl set_param at_max=$at_max
4650 }
4651
4652 ##################################
4653 # OBD_FAIL funcs
4654
4655 drop_request() {
4656 # OBD_FAIL_MDS_ALL_REQUEST_NET
4657     RC=0
4658     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
4659     do_facet client "$1" || RC=$?
4660     do_facet $SINGLEMDS lctl set_param fail_loc=0
4661     return $RC
4662 }
4663
4664 drop_reply() {
4665 # OBD_FAIL_MDS_ALL_REPLY_NET
4666         RC=0
4667         do_facet $SINGLEMDS $LCTL set_param fail_loc=0x122
4668         eval "$@" || RC=$?
4669         do_facet $SINGLEMDS $LCTL set_param fail_loc=0
4670         return $RC
4671 }
4672
4673 drop_reint_reply() {
4674 # OBD_FAIL_MDS_REINT_NET_REP
4675         RC=0
4676         do_facet $SINGLEMDS $LCTL set_param fail_loc=0x119
4677         eval "$@" || RC=$?
4678         do_facet $SINGLEMDS $LCTL set_param fail_loc=0
4679         return $RC
4680 }
4681
4682 drop_update_reply() {
4683 # OBD_FAIL_OUT_UPDATE_NET_REP
4684         local index=$1
4685         shift 1
4686         RC=0
4687         do_facet mds${index} lctl set_param fail_loc=0x1701
4688         do_facet client "$@" || RC=$?
4689         do_facet mds${index} lctl set_param fail_loc=0
4690         return $RC
4691 }
4692
4693 pause_bulk() {
4694 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
4695         RC=0
4696
4697         local timeout=${2:-0}
4698         # default is (obd_timeout / 4) if unspecified
4699         echo "timeout is $timeout/$2"
4700         do_facet ost1 lctl set_param fail_val=$timeout fail_loc=0x80000214
4701         do_facet client "$1" || RC=$?
4702         do_facet client "sync"
4703         do_facet ost1 lctl set_param fail_loc=0
4704         return $RC
4705 }
4706
4707 drop_ldlm_cancel() {
4708 #define OBD_FAIL_LDLM_CANCEL_NET                        0x304
4709         local RC=0
4710         local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4711         do_nodes $list lctl set_param fail_loc=0x304
4712
4713         do_facet client "$@" || RC=$?
4714
4715         do_nodes $list lctl set_param fail_loc=0
4716         return $RC
4717 }
4718
4719 drop_bl_callback_once() {
4720         local rc=0
4721         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0
4722 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
4723         do_facet client lctl set_param fail_loc=0x80000305
4724         do_facet client "$@" || rc=$?
4725         do_facet client lctl set_param fail_loc=0
4726         do_facet client lctl set_param fail_val=0
4727         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1
4728         return $rc
4729 }
4730
4731 drop_bl_callback() {
4732         rc=0
4733         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0
4734 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
4735         do_facet client lctl set_param fail_loc=0x305
4736         do_facet client "$@" || rc=$?
4737         do_facet client lctl set_param fail_loc=0
4738         do_facet client lctl set_param fail_val=0
4739         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1
4740         return $rc
4741 }
4742
4743 drop_ldlm_reply() {
4744 #define OBD_FAIL_LDLM_REPLY              0x30c
4745     RC=0
4746     local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4747     do_nodes $list lctl set_param fail_loc=0x30c
4748
4749     do_facet client "$@" || RC=$?
4750
4751     do_nodes $list lctl set_param fail_loc=0
4752     return $RC
4753 }
4754
4755 drop_ldlm_reply_once() {
4756 #define OBD_FAIL_LDLM_REPLY              0x30c
4757     RC=0
4758     local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4759     do_nodes $list lctl set_param fail_loc=0x8000030c
4760
4761     do_facet client "$@" || RC=$?
4762
4763     do_nodes $list lctl set_param fail_loc=0
4764     return $RC
4765 }
4766
4767 clear_failloc() {
4768     facet=$1
4769     pause=$2
4770     sleep $pause
4771     echo "clearing fail_loc on $facet"
4772     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
4773 }
4774
4775 set_nodes_failloc () {
4776         local fv=${3:-0}
4777         do_nodes $(comma_list $1)  lctl set_param fail_val=$fv fail_loc=$2
4778 }
4779
4780 cancel_lru_locks() {
4781         #$LCTL mark "cancel_lru_locks $1 start"
4782         $LCTL set_param -n ldlm.namespaces.*$1*.lru_size=clear
4783         $LCTL get_param ldlm.namespaces.*$1*.lock_unused_count | grep -v '=0'
4784         #$LCTL mark "cancel_lru_locks $1 stop"
4785 }
4786
4787 default_lru_size()
4788 {
4789         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
4790         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
4791         echo "$DEFAULT_LRU_SIZE"
4792 }
4793
4794 lru_resize_enable()
4795 {
4796     lctl set_param ldlm.namespaces.*$1*.lru_size=0
4797 }
4798
4799 lru_resize_disable()
4800 {
4801     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
4802 }
4803
4804 flock_is_enabled()
4805 {
4806         local RC=0
4807         [ -z "$(mount | grep "$MOUNT.*flock" | grep -v noflock)" ] && RC=1
4808         return $RC
4809 }
4810
4811 pgcache_empty() {
4812     local FILE
4813     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
4814         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
4815             echo there is still data in page cache $FILE ?
4816             lctl get_param -n $FILE
4817             return 1
4818         fi
4819     done
4820     return 0
4821 }
4822
4823 debugsave() {
4824         DEBUGSAVE="$(lctl get_param -n debug)"
4825         DEBUGSAVE_SERVER=$(do_facet $SINGLEMDS "$LCTL get_param -n debug")
4826 }
4827
4828 debugrestore() {
4829         [ -n "$DEBUGSAVE" ] &&
4830                 do_nodes $CLIENTS "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\""||
4831                 true
4832         DEBUGSAVE=""
4833
4834         [ -n "$DEBUGSAVE_SERVER" ] &&
4835                 do_nodes $(comma_list $(all_server_nodes)) \
4836                          "$LCTL set_param debug=\\\"${DEBUGSAVE_SERVER}\\\"" ||
4837                          true
4838         DEBUGSAVE_SERVER=""
4839 }
4840
4841 debug_size_save() {
4842     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
4843 }
4844
4845 debug_size_restore() {
4846     [ -n "$DEBUG_SIZE_SAVED" ] && \
4847         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
4848     DEBUG_SIZE_SAVED=""
4849 }
4850
4851 start_full_debug_logging() {
4852     debugsave
4853     debug_size_save
4854
4855     local FULLDEBUG=-1
4856     local DEBUG_SIZE=150
4857
4858     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
4859     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
4860 }
4861
4862 stop_full_debug_logging() {
4863     debug_size_restore
4864     debugrestore
4865 }
4866
4867 # prints bash call stack
4868 print_stack_trace() {
4869         local skip=${1:-1}
4870         echo "  Trace dump:"
4871         for (( i=$skip; i < ${#BASH_LINENO[*]} ; i++ )) ; do
4872                 local src=${BASH_SOURCE[$i]}
4873                 local lineno=${BASH_LINENO[$i-1]}
4874                 local funcname=${FUNCNAME[$i]}
4875                 echo "  = $src:$lineno:$funcname()"
4876         done
4877 }
4878
4879 report_error() {
4880         local TYPE=${TYPE:-"FAIL"}
4881
4882         local dump=true
4883         # do not dump logs if $1=false
4884         if [ "x$1" = "xfalse" ]; then
4885                 shift
4886                 dump=false
4887         fi
4888
4889         log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
4890         (print_stack_trace 2) >&2
4891         mkdir -p $LOGDIR
4892         # We need to dump the logs on all nodes
4893         if $dump; then
4894                 gather_logs $(comma_list $(nodes_list))
4895         fi
4896
4897         debugrestore
4898         [ "$TESTSUITELOG" ] &&
4899                 echo "$TESTSUITE: $TYPE: $TESTNAME $@" >> $TESTSUITELOG
4900         if [ -z "$*" ]; then
4901                 echo "error() without useful message, please fix" > $LOGDIR/err
4902         else
4903                 if [[ `echo $TYPE | grep ^IGNORE` ]]; then
4904                         echo "$@" > $LOGDIR/ignore
4905                 else
4906                         echo "$@" > $LOGDIR/err
4907                 fi
4908         fi
4909
4910         # cleanup the env for failed tests
4911         reset_fail_loc
4912 }
4913
4914 ##################################
4915 # Test interface
4916 ##################################
4917
4918 error_noexit() {
4919         report_error "$@"
4920 }
4921
4922 exit_status () {
4923         local status=0
4924         local log=$TESTSUITELOG
4925
4926         [ -f "$log" ] && grep -q FAIL $log && status=1
4927         exit $status
4928 }
4929
4930 error() {
4931         report_error "$@"
4932         exit 1
4933 }
4934
4935 error_exit() {
4936         report_error "$@"
4937         exit 1
4938 }
4939
4940 # use only if we are ignoring failures for this test, bugno required.
4941 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
4942 # e.g. error_ignore bz5494 "your message" or
4943 # error_ignore LU-5494 "your message"
4944 error_ignore() {
4945         local TYPE="IGNORE ($1)"
4946         shift
4947         report_error "$@"
4948 }
4949
4950 error_and_remount() {
4951         report_error "$@"
4952         remount_client $MOUNT
4953         exit 1
4954 }
4955
4956 # Throw an error if it's not running in vm - usually for performance
4957 # verification
4958 error_not_in_vm() {
4959         local virt=$(running_in_vm)
4960         if [[ -n "$virt" ]]; then
4961                 echo "running in VM '$virt', ignore error"
4962                 error_ignore env=$virt "$@"
4963         else
4964                 error "$@"
4965         fi
4966 }
4967
4968 skip_env () {
4969         $FAIL_ON_SKIP_ENV && error false $@ || skip $@
4970 }
4971
4972 skip() {
4973         echo
4974         log " SKIP: $TESTSUITE $TESTNAME $@"
4975
4976         if [[ -n "$ALWAYS_SKIPPED" ]]; then
4977                 skip_logged $TESTNAME "$@"
4978         else
4979                 mkdir -p $LOGDIR
4980                 echo "$@" > $LOGDIR/skip
4981         fi
4982
4983         [[ -n "$TESTSUITELOG" ]] &&
4984                 echo "$TESTSUITE: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
4985 }
4986
4987 build_test_filter() {
4988     EXCEPT="$EXCEPT $(testslist_filter)"
4989
4990         for O in $ONLY; do
4991                 if [[ $O = [0-9]*-[0-9]* ]]; then
4992                         for num in $(seq $(echo $O | tr '-' ' ')); do
4993                                 eval ONLY_$num=true
4994                         done
4995                 else
4996                         eval ONLY_${O}=true
4997                 fi
4998         done
4999
5000     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
5001         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
5002     [ "$EXCEPT_SLOW" ] && \
5003         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
5004     for E in $EXCEPT; do
5005         eval EXCEPT_${E}=true
5006     done
5007     for E in $ALWAYS_EXCEPT; do
5008         eval EXCEPT_ALWAYS_${E}=true
5009     done
5010     for E in $EXCEPT_SLOW; do
5011         eval EXCEPT_SLOW_${E}=true
5012     done
5013     for G in $GRANT_CHECK_LIST; do
5014         eval GCHECK_ONLY_${G}=true
5015         done
5016 }
5017
5018 basetest() {
5019     if [[ $1 = [a-z]* ]]; then
5020         echo $1
5021     else
5022         echo ${1%%[a-z]*}
5023     fi
5024 }
5025
5026 # print a newline if the last test was skipped
5027 export LAST_SKIPPED=
5028 export ALWAYS_SKIPPED=
5029 #
5030 # Main entry into test-framework. This is called with the name and
5031 # description of a test. The name is used to find the function to run
5032 # the test using "test_$name".
5033 #
5034 # This supports a variety of methods of specifying specific test to
5035 # run or not run.  These need to be documented...
5036 #
5037 run_test() {
5038         assert_DIR
5039
5040         export base=$(basetest $1)
5041         if [ -n "$ONLY" ]; then
5042                 testname=ONLY_$1
5043                 if [ ${!testname}x != x ]; then
5044                         [ -n "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
5045                         run_one_logged $1 "$2"
5046                         return $?
5047                 fi
5048                 testname=ONLY_$base
5049                 if [ ${!testname}x != x ]; then
5050                         [ -n "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
5051                         run_one_logged $1 "$2"
5052                         return $?
5053                 fi
5054                 LAST_SKIPPED="y"
5055                 return 0
5056         fi
5057
5058         LAST_SKIPPED="y"
5059         ALWAYS_SKIPPED="y"
5060         testname=EXCEPT_$1
5061         if [ ${!testname}x != x ]; then
5062                 TESTNAME=test_$1 skip "skipping excluded test $1"
5063                 return 0
5064         fi
5065         testname=EXCEPT_$base
5066         if [ ${!testname}x != x ]; then
5067                 TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
5068                 return 0
5069         fi
5070         testname=EXCEPT_ALWAYS_$1
5071         if [ ${!testname}x != x ]; then
5072                 TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1"
5073                 return 0
5074         fi
5075         testname=EXCEPT_ALWAYS_$base
5076         if [ ${!testname}x != x ]; then
5077                 TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1 (base $base)"
5078                 return 0
5079         fi
5080         testname=EXCEPT_SLOW_$1
5081         if [ ${!testname}x != x ]; then
5082                 TESTNAME=test_$1 skip "skipping SLOW test $1"
5083                 return 0
5084         fi
5085         testname=EXCEPT_SLOW_$base
5086         if [ ${!testname}x != x ]; then
5087                 TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
5088                 return 0
5089         fi
5090
5091         LAST_SKIPPED=
5092         ALWAYS_SKIPPED=
5093         run_one_logged $1 "$2"
5094
5095         return $?
5096 }
5097
5098 log() {
5099         echo "$*" >&2
5100         load_module ../libcfs/libcfs/libcfs
5101
5102     local MSG="$*"
5103     # Get rid of '
5104     MSG=${MSG//\'/\\\'}
5105     MSG=${MSG//\(/\\\(}
5106     MSG=${MSG//\)/\\\)}
5107     MSG=${MSG//\;/\\\;}
5108     MSG=${MSG//\|/\\\|}
5109     MSG=${MSG//\>/\\\>}
5110     MSG=${MSG//\</\\\<}
5111     MSG=${MSG//\//\\\/}
5112     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
5113 }
5114
5115 trace() {
5116         log "STARTING: $*"
5117         strace -o $TMP/$1.strace -ttt $*
5118         RC=$?
5119         log "FINISHED: $*: rc $RC"
5120         return 1
5121 }
5122
5123 complete () {
5124     local duration=$1
5125
5126     banner test complete, duration $duration sec
5127     [ -f "$TESTSUITELOG" ] && egrep .FAIL $TESTSUITELOG || true
5128     echo duration $duration >>$TESTSUITELOG
5129 }
5130
5131 pass() {
5132         # Set TEST_STATUS here. It will be used for logging the result.
5133         TEST_STATUS="PASS"
5134
5135         if [[ -f $LOGDIR/err ]]; then
5136                 TEST_STATUS="FAIL"
5137         elif [[ -f $LOGDIR/skip ]]; then
5138                 TEST_STATUS="SKIP"
5139         fi
5140         echo "$TEST_STATUS $@" 2>&1 | tee -a $TESTSUITELOG
5141 }
5142
5143 check_mds() {
5144     local FFREE=$(do_node $SINGLEMDS \
5145         lctl get_param -n osd*.*MDT*.filesfree | calc_sum)
5146     local FTOTAL=$(do_node $SINGLEMDS \
5147         lctl get_param -n osd*.*MDT*.filestotal | calc_sum)
5148
5149     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
5150 }
5151
5152 reset_fail_loc () {
5153         echo -n "Resetting fail_loc on all nodes..."
5154         do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 \
5155             fail_val=0 2>/dev/null" || true
5156         echo done.
5157 }
5158
5159
5160 #
5161 # Log a message (on all nodes) padded with "=" before and after.
5162 # Also appends a timestamp and prepends the testsuite name.
5163 #
5164
5165 EQUALS="===================================================================================================="
5166 banner() {
5167     msg="== ${TESTSUITE} $*"
5168     last=${msg: -1:1}
5169     [[ $last != "=" && $last != " " ]] && msg="$msg "
5170     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
5171     # always include at least == after the message
5172     log "$msg== $(date +"%H:%M:%S (%s)")"
5173 }
5174
5175 check_dmesg_for_errors() {
5176         local res
5177         local errors="VFS: Busy inodes after unmount of\|\
5178 ldiskfs_check_descriptors: Checksum for group 0 failed\|\
5179 group descriptors corrupted"
5180
5181         res=$(do_nodes $(comma_list $(nodes_list)) "dmesg" | grep "$errors")
5182         [ -z "$res" ] && return 0
5183         echo "Kernel error detected: $res"
5184         return 1
5185 }
5186
5187 #
5188 # Run a single test function and cleanup after it.
5189 #
5190 # This function should be run in a subshell so the test func can
5191 # exit() without stopping the whole script.
5192 #
5193 run_one() {
5194         local testnum=$1
5195         local message=$2
5196         export tfile=f${testnum}.${TESTSUITE}
5197         export tdir=d${testnum}.${TESTSUITE}
5198         export TESTNAME=test_$testnum
5199         local SAVE_UMASK=`umask`
5200         umask 0022
5201
5202         if ! grep -q $DIR /proc/mounts; then
5203                 $SETUP
5204         fi
5205
5206         banner "test $testnum: $message"
5207         test_${testnum} || error "test_$testnum failed with $?"
5208         cd $SAVE_PWD
5209         reset_fail_loc
5210         check_grant ${testnum} || error "check_grant $testnum failed with $?"
5211         check_node_health
5212         check_dmesg_for_errors || error "Error in dmesg detected"
5213         if [ "$PARALLEL" != "yes" ]; then
5214                 ps auxww | grep -v grep | grep -q multiop &&
5215                                         error "multiop still running"
5216         fi
5217         unset TESTNAME
5218         unset tdir
5219         unset tfile
5220         umask $SAVE_UMASK
5221         $CLEANUP
5222         return 0
5223 }
5224
5225 #
5226 # Wrapper around run_one to ensure:
5227 #  - test runs in subshell
5228 #  - output of test is saved to separate log file for error reporting
5229 #  - test result is saved to data file
5230 #
5231 run_one_logged() {
5232         local BEFORE=$(date +%s)
5233         local TEST_ERROR
5234         local name=${TESTSUITE}.test_${1}.test_log.$(hostname -s).log
5235         local test_log=$LOGDIR/$name
5236         local zfs_log_name=${TESTSUITE}.test_${1}.zfs_log
5237         local zfs_debug_log=$LOGDIR/$zfs_log_name
5238         rm -rf $LOGDIR/err
5239         rm -rf $LOGDIR/ignore
5240         rm -rf $LOGDIR/skip
5241         local SAVE_UMASK=$(umask)
5242         umask 0022
5243
5244         echo
5245         log_sub_test_begin test_${1}
5246         (run_one $1 "$2") 2>&1 | tee -i $test_log
5247         local RC=${PIPESTATUS[0]}
5248
5249         [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] &&
5250                 echo "test_$1 returned $RC" | tee $LOGDIR/err
5251
5252         duration=$(($(date +%s) - $BEFORE))
5253         pass "$1" "(${duration}s)"
5254
5255         if [[ -f $LOGDIR/err ]]; then
5256                 TEST_ERROR=$(cat $LOGDIR/err)
5257         elif [[ -f $LOGDIR/ignore ]]; then
5258                 TEST_ERROR=$(cat $LOGDIR/ignore)
5259         elif [[ -f $LOGDIR/skip ]]; then
5260                 TEST_ERROR=$(cat $LOGDIR/skip)
5261         fi
5262         log_sub_test_end $TEST_STATUS $duration "$RC" "$TEST_ERROR"
5263
5264         if [[ "$TEST_STATUS" != "SKIP" ]] && [[ -f $TF_SKIP ]]; then
5265                 rm -f $TF_SKIP
5266         fi
5267
5268         if [ -f $LOGDIR/err ]; then
5269                 log_zfs_info "$zfs_debug_log"
5270                 $FAIL_ON_ERROR && exit $RC
5271         fi
5272
5273         umask $SAVE_UMASK
5274
5275         return 0
5276 }
5277
5278 #
5279 # Print information of skipped tests to result.yml
5280 #
5281 skip_logged(){
5282         log_sub_test_begin $1
5283         shift
5284         log_sub_test_end "SKIP" "0" "0" "$@"
5285 }
5286
5287 canonical_path() {
5288         (cd $(dirname $1); echo $PWD/$(basename $1))
5289 }
5290
5291
5292 check_grant() {
5293         export base=$(basetest $1)
5294         [ "$CHECK_GRANT" == "no" ] && return 0
5295
5296         testname=GCHECK_ONLY_${base}
5297         [ ${!testname}x == x ] && return 0
5298
5299         echo -n "checking grant......"
5300
5301         local clients=$CLIENTS
5302         [ -z "$clients" ] && clients=$(hostname)
5303
5304         # sync all the data and make sure no pending data on server
5305         do_nodes $clients sync
5306
5307         # get client grant
5308         client_grant=$(do_nodes $clients \
5309                 "$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes" |
5310                 awk '{ total += $1 } END { printf("%0.0f", total) }')
5311
5312         # get server grant
5313         server_grant=$(do_nodes $(comma_list $(osts_nodes)) \
5314                 "$LCTL get_param -n obdfilter.${FSNAME}-OST*.tot_granted" |
5315                 awk '{ total += $1 } END { printf("%0.0f", total) }')
5316
5317         # check whether client grant == server grant
5318         if [[ $client_grant -ne $server_grant ]]; then
5319                 echo "failed: client:${client_grant} server: ${server_grant}."
5320                 do_nodes $(comma_list $(osts_nodes)) \
5321                         "$LCTL get_param obdfilter.${FSNAME}-OST*.tot*"
5322                 do_nodes $clients "$LCTL get_param osc.${FSNAME}-*.cur_*_bytes"
5323                 return 1
5324         else
5325                 echo "pass: client:${client_grant} server: ${server_grant}"
5326         fi
5327 }
5328
5329 ########################
5330 # helper functions
5331
5332 osc_to_ost()
5333 {
5334     osc=$1
5335     ost=`echo $1 | awk -F_ '{print $3}'`
5336     if [ -z $ost ]; then
5337         ost=`echo $1 | sed 's/-osc.*//'`
5338     fi
5339     echo $ost
5340 }
5341
5342 ostuuid_from_index()
5343 {
5344     $LFS osts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
5345 }
5346
5347 ostname_from_index() {
5348     local uuid=$(ostuuid_from_index $1)
5349     echo ${uuid/_UUID/}
5350 }
5351
5352 index_from_ostuuid()
5353 {
5354     $LFS osts $2 | sed -ne "/${1}/s/\(.*\): .* .*$/\1/p"
5355 }
5356
5357 mdtuuid_from_index()
5358 {
5359     $LFS mdts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
5360 }
5361
5362 # Description:
5363 #   Return unique identifier for given hostname
5364 host_id() {
5365         local host_name=$1
5366         echo $host_name | md5sum | cut -d' ' -f1
5367 }
5368
5369 # Description:
5370 #   Returns list of ip addresses for each interface
5371 local_addr_list() {
5372         ip addr | awk '/inet\ / {print $2}' | awk -F\/ '{print $1}'
5373 }
5374
5375 is_local_addr() {
5376         local addr=$1
5377         # Cache address list to avoid mutiple execution of local_addr_list
5378         LOCAL_ADDR_LIST=${LOCAL_ADDR_LIST:-$(local_addr_list)}
5379         local i
5380         for i in $LOCAL_ADDR_LIST ; do
5381                 [[ "$i" == "$addr" ]] && return 0
5382         done
5383         return 1
5384 }
5385
5386 local_node() {
5387         local host_name=$1
5388         local is_local="IS_LOCAL_$(host_id $host_name)"
5389         if [ -z "${!is_local-}" ] ; then
5390                 eval $is_local=0
5391                 local host_ip=$($LUSTRE/tests/resolveip $host_name)
5392                 is_local_addr "$host_ip" && eval $is_local=1
5393         fi
5394         [[ "${!is_local}" == "1" ]]
5395 }
5396
5397 remote_node () {
5398         local node=$1
5399         local_node $node && return 1
5400         return 0
5401 }
5402
5403 remote_mds ()
5404 {
5405     local node
5406     for node in $(mdts_nodes); do
5407         remote_node $node && return 0
5408     done
5409     return 1
5410 }
5411
5412 remote_mds_nodsh()
5413 {
5414         [ -n "$CLIENTONLY" ] && return 0 || true
5415         remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
5416 }
5417
5418 require_dsh_mds()
5419 {
5420         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" &&
5421                 MSKIPPED=1 && return 1
5422         return 0
5423 }
5424
5425 remote_ost ()
5426 {
5427     local node
5428     for node in $(osts_nodes) ; do
5429         remote_node $node && return 0
5430     done
5431     return 1
5432 }
5433
5434 remote_ost_nodsh()
5435 {
5436         [ -n "$CLIENTONLY" ] && return 0 || true
5437         remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
5438 }
5439
5440 require_dsh_ost()
5441 {
5442         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
5443             OSKIPPED=1 && return 1
5444         return 0
5445 }
5446
5447 remote_mgs_nodsh()
5448 {
5449         [ -n "$CLIENTONLY" ] && return 0 || true
5450         local MGS
5451         MGS=$(facet_host mgs)
5452         remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
5453 }
5454
5455 local_mode ()
5456 {
5457     remote_mds_nodsh || remote_ost_nodsh || \
5458         $(single_local_node $(comma_list $(nodes_list)))
5459 }
5460
5461 remote_servers () {
5462     remote_ost && remote_mds
5463 }
5464
5465 # Get the active nodes for facets.
5466 facets_nodes () {
5467         local facets=$1
5468         local facet
5469         local nodes
5470         local nodes_sort
5471         local i
5472
5473         for facet in ${facets//,/ }; do
5474                 nodes="$nodes $(facet_active_host $facet)"
5475         done
5476
5477         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5478         echo -n $nodes_sort
5479 }
5480
5481 # Get all of the active MDS nodes.
5482 mdts_nodes () {
5483         echo -n $(facets_nodes $(get_facets MDS))
5484 }
5485
5486 # Get all of the active OSS nodes.
5487 osts_nodes () {
5488         echo -n $(facets_nodes $(get_facets OST))
5489 }
5490
5491 # Get all of the active AGT (HSM agent) nodes.
5492 agts_nodes () {
5493         echo -n $(facets_nodes $(get_facets AGT))
5494 }
5495
5496 # Get all of the client nodes and active server nodes.
5497 nodes_list () {
5498         local nodes=$HOSTNAME
5499         local nodes_sort
5500         local i
5501
5502         # CLIENTS (if specified) contains the local client
5503         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
5504
5505         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
5506                 nodes="$nodes $(facets_nodes $(get_facets))"
5507         fi
5508
5509         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5510         echo -n $nodes_sort
5511 }
5512
5513 # Get all of the remote client nodes and remote active server nodes.
5514 remote_nodes_list () {
5515         echo -n $(nodes_list) | sed -re "s/\<$HOSTNAME\>//g"
5516 }
5517
5518 # Get all of the MDS nodes, including active and passive nodes.
5519 all_mdts_nodes () {
5520         local host
5521         local failover_host
5522         local nodes
5523         local nodes_sort
5524         local i
5525
5526         for i in $(seq $MDSCOUNT); do
5527                 host=mds${i}_HOST
5528                 failover_host=mds${i}failover_HOST
5529                 nodes="$nodes ${!host} ${!failover_host}"
5530         done
5531
5532         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5533         echo -n $nodes_sort
5534 }
5535
5536 # Get all of the OSS nodes, including active and passive nodes.
5537 all_osts_nodes () {
5538         local host
5539         local failover_host
5540         local nodes
5541         local nodes_sort
5542         local i
5543
5544         for i in $(seq $OSTCOUNT); do
5545                 host=ost${i}_HOST
5546                 failover_host=ost${i}failover_HOST
5547                 nodes="$nodes ${!host} ${!failover_host}"
5548         done
5549
5550         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5551         echo -n $nodes_sort
5552 }
5553
5554 # Get all of the server nodes, including active and passive nodes.
5555 all_server_nodes () {
5556         local nodes
5557         local nodes_sort
5558         local i
5559
5560         nodes="$mgs_HOST $mgsfailover_HOST $(all_mdts_nodes) $(all_osts_nodes)"
5561
5562         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5563         echo -n $nodes_sort
5564 }
5565
5566 # Get all of the client and server nodes, including active and passive nodes.
5567 all_nodes () {
5568         local nodes=$HOSTNAME
5569         local nodes_sort
5570         local i
5571
5572         # CLIENTS (if specified) contains the local client
5573         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
5574
5575         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
5576                 nodes="$nodes $(all_server_nodes)"
5577         fi
5578
5579         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5580         echo -n $nodes_sort
5581 }
5582
5583 init_clients_lists () {
5584     # Sanity check: exclude the local client from RCLIENTS
5585     local clients=$(hostlist_expand "$RCLIENTS")
5586     local rclients=$(exclude_items_from_list "$clients" $HOSTNAME)
5587
5588     # Sanity check: exclude the dup entries
5589     RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)
5590
5591     clients="$SINGLECLIENT $HOSTNAME $RCLIENTS"
5592
5593     # Sanity check: exclude the dup entries from CLIENTS
5594     # for those configs which has SINGLCLIENT set to local client
5595     clients=$(for i in $clients; do echo $i; done | sort -u)
5596
5597     CLIENTS=$(comma_list $clients)
5598     local -a remoteclients=($RCLIENTS)
5599     for ((i=0; $i<${#remoteclients[@]}; i++)); do
5600             varname=CLIENT$((i + 2))
5601             eval $varname=${remoteclients[i]}
5602     done
5603
5604     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
5605 }
5606
5607 get_random_entry () {
5608     local rnodes=$1
5609
5610     rnodes=${rnodes//,/ }
5611
5612     local -a nodes=($rnodes)
5613     local num=${#nodes[@]}
5614     local i=$((RANDOM * num * 2 / 65536))
5615
5616     echo ${nodes[i]}
5617 }
5618
5619 client_only () {
5620         [ -n "$CLIENTONLY" ] || [ "x$CLIENTMODSONLY" = "xyes" ]
5621 }
5622
5623 check_versions () {
5624     [ "$(lustre_version_code client)" = "$(lustre_version_code $SINGLEMDS)" -a \
5625       "$(lustre_version_code client)" = "$(lustre_version_code ost1)" ]
5626 }
5627
5628 get_node_count() {
5629     local nodes="$@"
5630     echo $nodes | wc -w || true
5631 }
5632
5633 mixed_ost_devs () {
5634     local nodes=$(osts_nodes)
5635     local osscount=$(get_node_count "$nodes")
5636     [ ! "$OSTCOUNT" = "$osscount" ]
5637 }
5638
5639 mixed_mdt_devs () {
5640     local nodes=$(mdts_nodes)
5641     local mdtcount=$(get_node_count "$nodes")
5642     [ ! "$MDSCOUNT" = "$mdtcount" ]
5643 }
5644
5645 generate_machine_file() {
5646     local nodes=${1//,/ }
5647     local machinefile=$2
5648     rm -f $machinefile
5649     for node in $nodes; do
5650         echo $node >>$machinefile || \
5651             { echo "can not generate machinefile $machinefile" && return 1; }
5652     done
5653 }
5654
5655 get_stripe () {
5656         local file=$1/stripe
5657
5658         touch $file
5659         $LFS getstripe -v $file || error "getstripe $file failed"
5660         rm -f $file
5661 }
5662
5663 setstripe_nfsserver () {
5664         local dir=$1
5665
5666         local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
5667                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -n1)
5668
5669         [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
5670
5671         do_nodev $nfsserver lfs setstripe "$@"
5672 }
5673
5674 # Check and add a test group.
5675 add_group() {
5676         local group_id=$1
5677         local group_name=$2
5678         local rc=0
5679
5680         local gid=$(getent group $group_name | cut -d: -f3)
5681         if [[ -n "$gid" ]]; then
5682                 [[ "$gid" -eq "$group_id" ]] || {
5683                         error_noexit "inconsistent group ID:" \
5684                                      "new: $group_id, old: $gid"
5685                         rc=1
5686                 }
5687         else
5688                 groupadd -g $group_id $group_name
5689                 rc=${PIPESTATUS[0]}
5690         fi
5691
5692         return $rc
5693 }
5694
5695 # Check and add a test user.
5696 add_user() {
5697         local user_id=$1
5698         shift
5699         local user_name=$1
5700         shift
5701         local group_name=$1
5702         shift
5703         local home=$1
5704         shift
5705         local opts="$@"
5706         local rc=0
5707
5708         local uid=$(getent passwd $user_name | cut -d: -f3)
5709         if [[ -n "$uid" ]]; then
5710                 if [[ "$uid" -eq "$user_id" ]]; then
5711                         local dir=$(getent passwd $user_name | cut -d: -f6)
5712                         if [[ "$dir" != "$home" ]]; then
5713                                 mkdir -p $home
5714                                 usermod -d $home $user_name
5715                                 rc=${PIPESTATUS[0]}
5716                         fi
5717                 else
5718                         error_noexit "inconsistent user ID:" \
5719                                      "new: $user_id, old: $uid"
5720                         rc=1
5721                 fi
5722         else
5723                 mkdir -p $home
5724                 useradd -M -u $user_id -d $home -g $group_name $opts $user_name
5725                 rc=${PIPESTATUS[0]}
5726         fi
5727
5728         return $rc
5729 }
5730
5731 check_runas_id_ret() {
5732     local myRC=0
5733     local myRUNAS_UID=$1
5734     local myRUNAS_GID=$2
5735     shift 2
5736     local myRUNAS=$@
5737     if [ -z "$myRUNAS" ]; then
5738         error_exit "myRUNAS command must be specified for check_runas_id"
5739     fi
5740     if $GSS_KRB5; then
5741         $myRUNAS krb5_login.sh || \
5742             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
5743     fi
5744     mkdir $DIR/d0_runas_test
5745     chmod 0755 $DIR
5746     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
5747     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
5748     rm -rf $DIR/d0_runas_test
5749     return $myRC
5750 }
5751
5752 check_runas_id() {
5753     local myRUNAS_UID=$1
5754     local myRUNAS_GID=$2
5755     shift 2
5756     local myRUNAS=$@
5757     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
5758         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
5759         Please set RUNAS_ID to some UID which exists on MDS and client or
5760         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
5761 }
5762
5763 # obtain the UID/GID for MPI_USER
5764 get_mpiuser_id() {
5765     local mpi_user=$1
5766
5767     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
5768 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
5769
5770     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
5771 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
5772 }
5773
5774 # obtain and cache Kerberos ticket-granting ticket
5775 refresh_krb5_tgt() {
5776     local myRUNAS_UID=$1
5777     local myRUNAS_GID=$2
5778     shift 2
5779     local myRUNAS=$@
5780     if [ -z "$myRUNAS" ]; then
5781         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
5782     fi
5783
5784     CLIENTS=${CLIENTS:-$HOSTNAME}
5785     do_nodes $CLIENTS "set -x
5786 if ! $myRUNAS krb5_login.sh; then
5787     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
5788     exit 1
5789 fi"
5790 }
5791
5792 # Run multiop in the background, but wait for it to print
5793 # "PAUSING" to its stdout before returning from this function.
5794 multiop_bg_pause() {
5795     MULTIOP_PROG=${MULTIOP_PROG:-$MULTIOP}
5796     FILE=$1
5797     ARGS=$2
5798
5799     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
5800     mkfifo $TMPPIPE
5801
5802     echo "$MULTIOP_PROG $FILE v$ARGS"
5803     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
5804
5805     echo "TMPPIPE=${TMPPIPE}"
5806     read -t 60 multiop_output < $TMPPIPE
5807     if [ $? -ne 0 ]; then
5808         rm -f $TMPPIPE
5809         return 1
5810     fi
5811     rm -f $TMPPIPE
5812     if [ "$multiop_output" != "PAUSING" ]; then
5813         echo "Incorrect multiop output: $multiop_output"
5814         kill -9 $PID
5815         return 1
5816     fi
5817
5818     return 0
5819 }
5820
5821 do_and_time () {
5822     local cmd=$1
5823     local rc
5824
5825     SECONDS=0
5826     eval '$cmd'
5827
5828     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
5829
5830     echo $SECONDS
5831     return $rc
5832 }
5833
5834 inodes_available () {
5835         local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{ print $4 }' |
5836                 sort -un | head -n1) || return 1
5837         echo $((IFree))
5838 }
5839
5840 mdsrate_inodes_available () {
5841     local min_inodes=$(inodes_available)
5842     echo $((min_inodes * 99 / 100))
5843 }
5844
5845 # reset llite stat counters
5846 clear_llite_stats(){
5847         lctl set_param -n llite.*.stats 0
5848 }
5849
5850 # sum llite stat items
5851 calc_llite_stats() {
5852         local res=$(lctl get_param -n llite.*.stats |
5853                 awk '/^'"$1"'/ {sum += $2} END { printf("%0.0f", sum) }')
5854         echo $((res))
5855 }
5856
5857 # reset osc stat counters
5858 clear_osc_stats(){
5859         lctl set_param -n osc.*.osc_stats 0
5860 }
5861
5862 # sum osc stat items
5863 calc_osc_stats() {
5864         local res=$(lctl get_param -n osc.*.osc_stats |
5865                 awk '/^'"$1"'/ {sum += $2} END { printf("%0.0f", sum) }')
5866         echo $((res))
5867 }
5868
5869 calc_sum () {
5870         awk '{sum += $1} END { printf("%0.0f", sum) }'
5871 }
5872
5873 calc_osc_kbytes () {
5874         df $MOUNT > /dev/null
5875         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
5876 }
5877
5878 # save_lustre_params(comma separated facet list, parameter_mask)
5879 # generate a stream of formatted strings (<facet> <param name>=<param value>)
5880 save_lustre_params() {
5881         local facets=$1
5882         local facet
5883         local nodes
5884         local node
5885
5886         for facet in ${facets//,/ }; do
5887                 node=$(facet_active_host $facet)
5888                 [[ *\ $node\ * = " $nodes " ]] && continue
5889                 nodes="$nodes $node"
5890
5891                 do_node $node "$LCTL get_param $2 |
5892                         while read s; do echo $facet \\\$s; done"
5893         done
5894 }
5895
5896 # restore lustre parameters from input stream, produces by save_lustre_params
5897 restore_lustre_params() {
5898         local facet
5899         local name
5900         local val
5901
5902         while IFS=" =" read facet name val; do
5903                 do_facet $facet "$LCTL set_param -n $name $val"
5904         done
5905 }
5906
5907 check_node_health() {
5908         local nodes=${1:-$(comma_list $(nodes_list))}
5909
5910         for node in ${nodes//,/ }; do
5911                 check_network "$node" 5
5912                 if [ $? -eq 0 ]; then
5913                         do_node $node "rc=0;
5914                         val=\\\$($LCTL get_param -n catastrophe 2>&1);
5915                         if [[ \\\$? -eq 0 && \\\$val -ne 0 ]]; then
5916                                 echo \\\$(hostname -s): \\\$val;
5917                                 rc=\\\$val;
5918                         fi;
5919                         exit \\\$rc" || error "$node:LBUG/LASSERT detected"
5920                 fi
5921         done
5922 }
5923
5924 mdsrate_cleanup () {
5925         if [ -d $4 ]; then
5926                 mpi_run ${MACHINEFILE_OPTION} $2 -np $1 ${MDSRATE} --unlink \
5927                         --nfiles $3 --dir $4 --filefmt $5 $6
5928                 rmdir $4
5929         fi
5930 }
5931
5932 delayed_recovery_enabled () {
5933     local var=${SINGLEMDS}_svc
5934     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
5935 }
5936
5937 ########################
5938
5939 convert_facet2label() {
5940     local facet=$1
5941
5942     if [ x$facet = xost ]; then
5943        facet=ost1
5944     fi
5945
5946     local varsvc=${facet}_svc
5947
5948     if [ -n ${!varsvc} ]; then
5949         echo ${!varsvc}
5950     else
5951         error "No lablel for $facet!"
5952     fi
5953 }
5954
5955 get_clientosc_proc_path() {
5956         echo "${1}-osc-*"
5957 }
5958
5959 # If the 2.0 MDS was mounted on 1.8 device, then the OSC and LOV names
5960 # used by MDT would not be changed.
5961 # mdt lov: fsname-mdtlov
5962 # mdt osc: fsname-OSTXXXX-osc
5963 mds_on_old_device() {
5964     local mds=${1:-"$SINGLEMDS"}
5965
5966     if [ $(lustre_version_code $mds) -gt $(version_code 1.9.0) ]; then
5967         do_facet $mds "lctl list_param osc.$FSNAME-OST*-osc \
5968             > /dev/null 2>&1" && return 0
5969     fi
5970     return 1
5971 }
5972
5973 get_mdtosc_proc_path() {
5974         local mds_facet=$1
5975         local ost_label=${2:-"*OST*"}
5976
5977         [ "$mds_facet" = "mds" ] && mds_facet=$SINGLEMDS
5978         local mdt_label=$(convert_facet2label $mds_facet)
5979         local mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')
5980
5981         if [ $(lustre_version_code $mds_facet) -le $(version_code 1.8.0) ] ||
5982            mds_on_old_device $mds_facet; then
5983                 echo "${ost_label}-osc"
5984         elif [[ $ost_label = *OST* ]]; then
5985                 echo "${ost_label}-osc-${mdt_index}"
5986         else
5987                 echo "${ost_label}-osp-${mdt_index}"
5988         fi
5989 }
5990
5991 get_osc_import_name() {
5992     local facet=$1
5993     local ost=$2
5994     local label=$(convert_facet2label $ost)
5995
5996     if [ "${facet:0:3}" = "mds" ]; then
5997         get_mdtosc_proc_path $facet $label
5998         return 0
5999     fi
6000
6001     get_clientosc_proc_path $label
6002     return 0
6003 }
6004
6005 _wait_import_state () {
6006     local expected=$1
6007     local CONN_PROC=$2
6008     local maxtime=${3:-$(max_recovery_time)}
6009     local error_on_failure=${4:-1}
6010     local CONN_STATE
6011     local i=0
6012
6013         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
6014     while [ "${CONN_STATE}" != "${expected}" ]; do
6015         if [ "${expected}" == "DISCONN" ]; then
6016             # for disconn we can check after proc entry is removed
6017             [ "x${CONN_STATE}" == "x" ] && return 0
6018             #  with AT enabled, we can have connect request timeout near of
6019             # reconnect timeout and test can't see real disconnect
6020             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
6021         fi
6022         if [ $i -ge $maxtime ]; then
6023             [ $error_on_failure -ne 0 ] && \
6024                 error "can't put import for $CONN_PROC into ${expected}" \
6025                       "state after $i sec, have ${CONN_STATE}"
6026             return 1
6027         fi
6028         sleep 1
6029         # Add uniq for multi-mount case
6030         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
6031         i=$(($i + 1))
6032     done
6033
6034     log "$CONN_PROC in ${CONN_STATE} state after $i sec"
6035     return 0
6036 }
6037
6038 wait_import_state() {
6039     local state=$1
6040     local params=$2
6041     local maxtime=${3:-$(max_recovery_time)}
6042     local error_on_failure=${4:-1}
6043     local param
6044
6045     for param in ${params//,/ }; do
6046         _wait_import_state $state $param $maxtime $error_on_failure || return
6047     done
6048 }
6049
6050 wait_import_state_mount() {
6051         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
6052                 return 0
6053         fi
6054
6055         wait_import_state $*
6056 }
6057
6058 # One client request could be timed out because server was not ready
6059 # when request was sent by client.
6060 # The request timeout calculation details :
6061 # ptl_send_rpc ()
6062 #      /* We give the server rq_timeout secs to process the req, and
6063 #      add the network latency for our local timeout. */
6064 #      request->rq_deadline = request->rq_sent + request->rq_timeout +
6065 #           ptlrpc_at_get_net_latency(request) ;
6066 #
6067 # ptlrpc_connect_import ()
6068 #      request->rq_timeout = INITIAL_CONNECT_TIMEOUT
6069 #
6070 # init_imp_at () ->
6071 #   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0
6072 # ptlrpc_at_get_net_latency(request) ->
6073 #       at_get (max (iat_net_latency=0, at_min)) = at_min
6074 #
6075 # i.e.:
6076 # request->rq_timeout + ptlrpc_at_get_net_latency(request) =
6077 # INITIAL_CONNECT_TIMEOUT + at_min
6078 #
6079 # We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT
6080 # because we can not get this value in runtime,
6081 # the value depends on configure options, and it is not stored in /proc.
6082 # obd_support.h:
6083 # #define CONNECTION_SWITCH_MIN 5U
6084 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
6085
6086 request_timeout () {
6087     local facet=$1
6088
6089     # request->rq_timeout = INITIAL_CONNECT_TIMEOUT
6090     local init_connect_timeout=$TIMEOUT
6091     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
6092
6093     local at_min=$(at_get $facet at_min)
6094
6095     echo $(( init_connect_timeout + at_min ))
6096 }
6097
6098 _wait_osc_import_state() {
6099         local facet=$1
6100         local ost_facet=$2
6101         local expected=$3
6102         local target=$(get_osc_import_name $facet $ost_facet)
6103         local param="osc.${target}.ost_server_uuid"
6104         local params=$param
6105         local i=0
6106
6107         # 1. wait the deadline of client 1st request (it could be skipped)
6108         # 2. wait the deadline of client 2nd request
6109         local maxtime=$(( 2 * $(request_timeout $facet)))
6110
6111         if [[ $facet == client* ]]; then
6112                 # During setup time, the osc might not be setup, it need wait
6113                 # until list_param can return valid value.
6114                 param="osc.${ost%?}[^mM]*.ost_server_uuid"
6115                 params=$($LCTL list_param $param 2>/dev/null || true)
6116                 while [ -z "$params" ]; do
6117                         if [ $i -ge $maxtime ]; then
6118                                 echo "can't get $param in $maxtime secs"
6119                                 return 1
6120                         fi
6121                         sleep 1
6122                         i=$((i + 1))
6123                         params=$($LCTL list_param $param 2>/dev/null || true)
6124                 done
6125         fi
6126
6127         if [[ $ost_facet = mds* ]]; then
6128                 # no OSP connection to itself
6129                 if [[ $facet = $ost_facet ]]; then
6130                         return 0
6131                 fi
6132                 param="osp.${target}.mdt_server_uuid"
6133                 params=$param
6134         fi
6135
6136         if ! do_rpc_nodes "$(facet_active_host $facet)" \
6137                         wait_import_state $expected "$params" $maxtime; then
6138                 error "$facet: import is not in $expected state after $maxtime"
6139                 return 1
6140         fi
6141
6142         return 0
6143 }
6144
6145 wait_osc_import_state() {
6146         local facet=$1
6147         local ost_facet=$2
6148         local expected=$3
6149         local num
6150
6151         if [[ $facet = mds ]]; then
6152                 for num in $(seq $MDSCOUNT); do
6153                         _wait_osc_import_state mds$num "$ost_facet" "$expected"
6154                 done
6155         else
6156                 _wait_osc_import_state "$facet" "$ost_facet" "$expected"
6157         fi
6158 }
6159
6160 _wait_mgc_import_state() {
6161         local facet=$1
6162         local expected=$2
6163         local error_on_failure=${3:-1}
6164         local param="mgc.*.mgs_server_uuid"
6165         local params=$param
6166         local i=0
6167
6168         # 1. wait the deadline of client 1st request (it could be skipped)
6169         # 2. wait the deadline of client 2nd request
6170         local maxtime=$(( 2 * $(request_timeout $facet)))
6171
6172         if [[ $facet == client* ]]; then
6173                 # During setup time, the osc might not be setup, it need wait
6174                 # until list_param can return valid value. And also if there
6175                 # are mulitple osc entries we should list all of them before
6176                 # go to wait.
6177                 params=$($LCTL list_param $param 2>/dev/null || true)
6178                 while [ -z "$params" ]; do
6179                         if [ $i -ge $maxtime ]; then
6180                                 echo "can't get $param in $maxtime secs"
6181                                 return 1
6182                         fi
6183                         sleep 1
6184                         i=$((i + 1))
6185                         params=$($LCTL list_param $param 2>/dev/null || true)
6186                 done
6187         fi
6188         if ! do_rpc_nodes "$(facet_active_host $facet)" \
6189                         wait_import_state $expected "$params" $maxtime \
6190                                           $error_on_failure; then
6191                 if [ $error_on_failure -ne 0 ]; then
6192                     error "import is not in ${expected} state"
6193                 fi
6194                 return 1
6195         fi
6196
6197         return 0
6198 }
6199
6200 wait_mgc_import_state() {
6201         local facet=$1
6202         local expected=$2
6203         local error_on_failure=${3:-1}
6204         local num
6205
6206         if [[ $facet = mds ]]; then
6207                 for num in $(seq $MDSCOUNT); do
6208                         _wait_mgc_import_state mds$num "$expected" \
6209                                                $error_on_failure || return
6210                 done
6211         else
6212                 _wait_mgc_import_state "$facet" "$expected"
6213                                        $error_on_failure || return
6214         fi
6215 }
6216
6217 wait_dne_interconnect() {
6218         local num
6219
6220         if [ $MDSCOUNT -gt 1 ]; then
6221                 for num in $(seq $MDSCOUNT); do
6222                         wait_osc_import_state mds mds$num FULL
6223                 done
6224         fi
6225 }
6226
6227 get_clientmdc_proc_path() {
6228     echo "${1}-mdc-*"
6229 }
6230
6231 get_clientmgc_proc_path() {
6232     echo "*"
6233 }
6234
6235 do_rpc_nodes () {
6236         local list=$1
6237         shift
6238
6239         [ -z "$list" ] && return 0
6240
6241         # Add paths to lustre tests for 32 and 64 bit systems.
6242         local LIBPATH="/usr/lib/lustre/tests:/usr/lib64/lustre/tests:"
6243         local TESTPATH="$RLUSTRE/tests:"
6244         local RPATH="PATH=${TESTPATH}${LIBPATH}${PATH}:/sbin:/bin:/usr/sbin:"
6245         do_nodesv $list "${RPATH} NAME=${NAME} sh rpc.sh $@ "
6246 }
6247
6248 wait_clients_import_state () {
6249         local list=$1
6250         local facet=$2
6251         local expected=$3
6252
6253         local facets=$facet
6254
6255         if [ "$FAILURE_MODE" = HARD ]; then
6256                 facets=$(facets_on_host $(facet_active_host $facet))
6257         fi
6258
6259         for facet in ${facets//,/ }; do
6260                 local label=$(convert_facet2label $facet)
6261                 local proc_path
6262                 case $facet in
6263                 ost* ) proc_path="osc.$(get_clientosc_proc_path \
6264                                   $label).ost_server_uuid" ;;
6265                 mds* ) proc_path="mdc.$(get_clientmdc_proc_path \
6266                                   $label).mds_server_uuid" ;;
6267                 mgs* ) proc_path="mgc.$(get_clientmgc_proc_path \
6268                                   $label).mgs_server_uuid" ;;
6269                 *) error "unknown facet!" ;;
6270                 esac
6271
6272                 local params=$(expand_list $params $proc_path)
6273         done
6274
6275         if ! do_rpc_nodes "$list" wait_import_state_mount $expected $params;
6276         then
6277                 error "import is not in ${expected} state"
6278                 return 1
6279         fi
6280 }
6281
6282 wait_osp_active() {
6283         local facet=$1
6284         local tgt_name=$2
6285         local tgt_idx=$3
6286         local expected=$4
6287         local num
6288
6289         # wait until all MDTs are in the expected state
6290         for ((num = 1; num <= $MDSCOUNT; num++)); do
6291                 local mdtosp=$(get_mdtosc_proc_path mds${num} ${tgt_name})
6292                 local mproc
6293
6294                 if [ $facet = "mds" ]; then
6295                         mproc="osp.$mdtosp.active"
6296                         [ $num -eq $((tgt_idx + 1)) ] && continue
6297                 else
6298                         mproc="osc.$mdtosp.active"
6299                 fi
6300
6301                 echo "check $mproc"
6302                 while [ 1 ]; do
6303                         sleep 5
6304                         local result=$(do_facet mds${num} "$LCTL get_param -n $mproc")
6305                         local max=30
6306                         local wait=0
6307
6308                         [ ${PIPESTATUS[0]} = 0 ] || error "Can't read $mproc"
6309                         if [ $result -eq $expected ]; then
6310                                 echo -n "target updated after"
6311                                 echo "$wait sec (got $result)"
6312                                 break
6313                         fi
6314                         wait=$((wait + 5))
6315                         if [ $wait -eq $max ]; then
6316                                 error "$tgt_name: wanted $expected got $result"
6317                         fi
6318                         echo "Waiting $((max - wait)) secs for $tgt_name"
6319                 done
6320         done
6321 }
6322
6323 oos_full() {
6324         local -a AVAILA
6325         local -a GRANTA
6326         local -a TOTALA
6327         local OSCFULL=1
6328         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
6329                   $LCTL get_param obdfilter.*.kbytesavail))
6330         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
6331                   $LCTL get_param -n obdfilter.*.tot_granted))
6332         TOTALA=($(do_nodes $(comma_list $(osts_nodes)) \
6333                   $LCTL get_param -n obdfilter.*.kbytestotal))
6334         for ((i=0; i<${#AVAILA[@]}; i++)); do
6335                 local -a AVAIL1=(${AVAILA[$i]//=/ })
6336                 local -a TOTAL=(${TOTALA[$i]//=/ })
6337                 GRANT=$((${GRANTA[$i]}/1024))
6338                 # allow 1% of total space in bavail because of delayed
6339                 # allocation with ZFS which might release some free space after
6340                 # txg commit.  For small devices, we set a mininum of 8MB
6341                 local LIMIT=$((${TOTAL} / 100 + 8000))
6342                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} \
6343                         grnt=$GRANT diff=$((AVAIL1[1] - GRANT)) limit=${LIMIT}
6344                 [ $((AVAIL1[1] - GRANT)) -lt $LIMIT ] && OSCFULL=0 && \
6345                         echo " FULL" || echo
6346         done
6347         return $OSCFULL
6348 }
6349
6350 list_pool() {
6351         echo -e "$(do_facet $SINGLEMDS $LCTL pool_list $1 | sed '1d')"
6352 }
6353
6354 check_pool_not_exist() {
6355         local fsname=${1%%.*}
6356         local poolname=${1##$fsname.}
6357         [[ $# -ne 1 ]] && return 0
6358         [[ x$poolname = x ]] &&  return 0
6359         list_pool $fsname | grep -w $1 && return 1
6360         return 0
6361 }
6362
6363 create_pool() {
6364         local fsname=${1%%.*}
6365         local poolname=${1##$fsname.}
6366
6367         trap "destroy_test_pools $fsname" EXIT
6368         do_facet mgs lctl pool_new $1
6369         local RC=$?
6370         # get param should return err unless pool is created
6371         [[ $RC -ne 0 ]] && return $RC
6372
6373         for mds_id in $(seq $MDSCOUNT); do
6374                 local mdt_id=$((mds_id-1))
6375                 local lodname=$fsname-MDT$(printf "%04x" $mdt_id)-mdtlov
6376                 wait_update_facet mds$mds_id \
6377                         "lctl get_param -n lod.$lodname.pools.$poolname \
6378                                 2>/dev/null || echo foo" "" ||
6379                         error "mds$mds_id: pool_new failed $1"
6380         done
6381         wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
6382                 2>/dev/null || echo foo" "" || error "pool_new failed $1"
6383
6384         add_pool_to_list $1
6385         return $RC
6386 }
6387
6388 add_pool_to_list () {
6389         local fsname=${1%%.*}
6390         local poolname=${1##$fsname.}
6391
6392         local listvar=${fsname}_CREATED_POOLS
6393         local temp=${listvar}=$(expand_list ${!listvar} $poolname)
6394         eval export $temp
6395 }
6396
6397 remove_pool_from_list () {
6398         local fsname=${1%%.*}
6399         local poolname=${1##$fsname.}
6400
6401         local listvar=${fsname}_CREATED_POOLS
6402         local temp=${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
6403         eval export $temp
6404 }
6405
6406 destroy_pool_int() {
6407         local ost
6408         local OSTS=$(list_pool $1)
6409         for ost in $OSTS; do
6410                 do_facet mgs lctl pool_remove $1 $ost
6411         done
6412         do_facet mgs lctl pool_destroy $1
6413 }
6414
6415 # <fsname>.<poolname> or <poolname>
6416 destroy_pool() {
6417         local fsname=${1%%.*}
6418         local poolname=${1##$fsname.}
6419
6420         [[ x$fsname = x$poolname ]] && fsname=$FSNAME
6421
6422         local RC
6423
6424         check_pool_not_exist $fsname.$poolname
6425         [[ $? -eq 0 ]] && return 0
6426
6427         destroy_pool_int $fsname.$poolname
6428         RC=$?
6429         [[ $RC -ne 0 ]] && return $RC
6430         for mds_id in $(seq $MDSCOUNT); do
6431                 local mdt_id=$((mds_id-1))
6432                 local lodname=$fsname-MDT$(printf "%04x" $mdt_id)-mdtlov
6433                 wait_update_facet mds$mds_id \
6434                         "lctl get_param -n lod.$lodname.pools.$poolname \
6435                                 2>/dev/null || echo foo" "foo" ||
6436                         error "mds$mds_id: destroy pool failed $1"
6437         done
6438         wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
6439                 2>/dev/null || echo foo" "foo" || error "destroy pool failed $1"
6440
6441         remove_pool_from_list $fsname.$poolname
6442
6443         return $RC
6444 }
6445
6446 destroy_pools () {
6447         local fsname=${1:-$FSNAME}
6448         local poolname
6449         local listvar=${fsname}_CREATED_POOLS
6450
6451         [ x${!listvar} = x ] && return 0
6452
6453         echo "Destroy the created pools: ${!listvar}"
6454         for poolname in ${!listvar//,/ }; do
6455                 destroy_pool $fsname.$poolname
6456         done
6457 }
6458
6459 destroy_test_pools () {
6460         trap 0
6461         local fsname=${1:-$FSNAME}
6462         destroy_pools $fsname || true
6463 }
6464
6465 gather_logs () {
6466     local list=$1
6467
6468     local ts=$(date +%s)
6469     local docp=true
6470
6471     if [[ ! -f "$YAML_LOG" ]]; then
6472         # init_logging is not performed before gather_logs,
6473         # so the $LOGDIR needs to be checked here
6474         check_shared_dir $LOGDIR && touch $LOGDIR/shared
6475     fi
6476
6477     [ -f $LOGDIR/shared ] && docp=false
6478
6479     # dump lustre logs, dmesg
6480
6481     prefix="$TESTLOG_PREFIX.$TESTNAME"
6482     suffix="$ts.log"
6483     echo "Dumping lctl log to ${prefix}.*.${suffix}"
6484
6485     if [ -n "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
6486         echo "Dumping logs only on local client."
6487         $LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}
6488         dmesg > ${prefix}.dmesg.$(hostname -s).${suffix}
6489         return
6490     fi
6491
6492     do_nodesv $list \
6493         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname -s).${suffix};
6494          dmesg > ${prefix}.dmesg.\\\$(hostname -s).${suffix}"
6495     if [ ! -f $LOGDIR/shared ]; then
6496         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
6497     fi
6498 }
6499
6500 do_ls () {
6501     local mntpt_root=$1
6502     local num_mntpts=$2
6503     local dir=$3
6504     local i
6505     local cmd
6506     local pids
6507     local rc=0
6508
6509     for i in $(seq 0 $num_mntpts); do
6510         cmd="ls -laf ${mntpt_root}$i/$dir"
6511         echo + $cmd;
6512         $cmd > /dev/null &
6513         pids="$pids $!"
6514     done
6515     echo pids=$pids
6516     for pid in $pids; do
6517         wait $pid || rc=$?
6518     done
6519
6520     return $rc
6521 }
6522
6523 # check_and_start_recovery_timer()
6524 #       service_time = at_est2timeout(service_time);
6525 #       service_time += 2 * INITIAL_CONNECT_TIMEOUT;
6526 #       service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC);
6527
6528 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN, obd_timeout/20)
6529 #define CONNECTION_SWITCH_MAX min(50, max(CONNECTION_SWITCH_MIN, obd_timeout))
6530 #define CONNECTION_SWITCH_MIN 5
6531 #define CONNECTION_SWITCH_INC 5
6532 max_recovery_time() {
6533         local init_connect_timeout=$((TIMEOUT / 20))
6534         ((init_connect_timeout >= 5)) || init_connect_timeout=5
6535
6536         local service_time=$(($(at_max_get client) * 9 / 4 + 5))
6537         service_time=$((service_time + 2 * (init_connect_timeout + 50 + 5)))
6538
6539         echo -n $service_time
6540 }
6541
6542 recovery_time_min() {
6543         local connection_switch_min=5
6544         local connection_switch_inc=5
6545         local connection_switch_max
6546         local reconnect_delay_max
6547         local initial_connect_timeout
6548         local max
6549         local timout_20
6550
6551         #connection_switch_max=min(50, max($connection_switch_min,$TIMEOUT)
6552         (($connection_switch_min > $TIMEOUT)) &&
6553                 max=$connection_switch_min || max=$TIMEOUT
6554         (($max < 50)) && connection_switch_max=$max || connection_switch_max=50
6555
6556         #initial_connect_timeout = max(connection_switch_min, obd_timeout/20)
6557         timeout_20=$((TIMEOUT/20))
6558         (($connection_switch_min > $timeout_20)) &&
6559                 initial_connect_timeout=$connection_switch_min ||
6560                 initial_connect_timeout=$timeout_20
6561
6562         reconnect_delay_max=$((connection_switch_max + connection_switch_inc + \
6563                                initial_connect_timeout))
6564         echo $((2 * reconnect_delay_max))
6565 }
6566
6567 get_clients_mount_count () {
6568     local clients=${CLIENTS:-`hostname`}
6569
6570     # we need to take into account the clients mounts and
6571     # exclude mds/ost mounts if any;
6572     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
6573 }
6574
6575 # gss functions
6576 PROC_CLI="srpc_info"
6577
6578 combination()
6579 {
6580     local M=$1
6581     local N=$2
6582     local R=1
6583
6584     if [ $M -lt $N ]; then
6585         R=0
6586     else
6587         N=$((N + 1))
6588         while [ $N -lt $M ]; do
6589             R=$((R * N))
6590             N=$((N + 1))
6591         done
6592     fi
6593
6594     echo $R
6595     return 0
6596 }
6597
6598 calc_connection_cnt() {
6599     local dir=$1
6600
6601     # MDT->MDT = 2 * C(M, 2)
6602     # MDT->OST = M * O
6603     # CLI->OST = C * O
6604     # CLI->MDT = C * M
6605     comb_m2=$(combination $MDSCOUNT 2)
6606
6607     local num_clients=$(get_clients_mount_count)
6608
6609     local cnt_mdt2mdt=$((comb_m2 * 2))
6610     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
6611     local cnt_cli2ost=$((num_clients * OSTCOUNT))
6612     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
6613     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
6614     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
6615     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
6616
6617     local var=cnt_$dir
6618     local res=${!var}
6619
6620     echo $res
6621 }
6622
6623 set_rule()
6624 {
6625     local tgt=$1
6626     local net=$2
6627     local dir=$3
6628     local flavor=$4
6629     local cmd="$tgt.srpc.flavor"
6630
6631     if [ $net == "any" ]; then
6632         net="default"
6633     fi
6634     cmd="$cmd.$net"
6635
6636     if [ $dir != "any" ]; then
6637         cmd="$cmd.$dir"
6638     fi
6639
6640     cmd="$cmd=$flavor"
6641     log "Setting sptlrpc rule: $cmd"
6642     do_facet mgs "$LCTL conf_param $cmd"
6643 }
6644
6645 count_flvr()
6646 {
6647     local output=$1
6648     local flavor=$2
6649     local count=0
6650
6651     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
6652     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
6653
6654     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
6655
6656     if [ "x$bulkspec" != "x" ]; then
6657         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
6658
6659         if [ "x$algs" != "x" ]; then
6660             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
6661         else
6662             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
6663             if [ $bulk == "bulkn" ]; then
6664                 bulk_count=`echo "$output" | grep "bulk flavor" \
6665                             | grep "null/null" | wc -l`
6666             elif [ $bulk == "bulki" ]; then
6667                 bulk_count=`echo "$output" | grep "bulk flavor" \
6668                             | grep "/null" | grep -v "null/" | wc -l`
6669             else
6670                 bulk_count=`echo "$output" | grep "bulk flavor" \
6671                             | grep -v "/null" | grep -v "null/" | wc -l`
6672             fi
6673         fi
6674
6675         [ $bulk_count -lt $count ] && count=$bulk_count
6676     fi
6677
6678     echo $count
6679 }
6680
6681 flvr_cnt_cli2mdt()
6682 {
6683     local flavor=$1
6684     local cnt
6685
6686     local clients=${CLIENTS:-`hostname`}
6687
6688     for c in ${clients//,/ }; do
6689         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
6690         tmpcnt=`count_flvr "$output" $flavor`
6691         cnt=$((cnt + tmpcnt))
6692     done
6693     echo $cnt
6694 }
6695
6696 flvr_cnt_cli2ost()
6697 {
6698     local flavor=$1
6699     local cnt
6700
6701     local clients=${CLIENTS:-`hostname`}
6702
6703     for c in ${clients//,/ }; do
6704         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
6705         tmpcnt=`count_flvr "$output" $flavor`
6706         cnt=$((cnt + tmpcnt))
6707     done
6708     echo $cnt
6709 }
6710
6711 flvr_cnt_mdt2mdt()
6712 {
6713     local flavor=$1
6714     local cnt=0
6715
6716     if [ $MDSCOUNT -le 1 ]; then
6717         echo 0
6718         return
6719     fi
6720
6721     for num in `seq $MDSCOUNT`; do
6722         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
6723         tmpcnt=`count_flvr "$output" $flavor`
6724         cnt=$((cnt + tmpcnt))
6725     done
6726     echo $cnt;
6727 }
6728
6729 flvr_cnt_mdt2ost()
6730 {
6731     local flavor=$1
6732     local cnt=0
6733     local mdtosc
6734
6735     for num in `seq $MDSCOUNT`; do
6736         mdtosc=$(get_mdtosc_proc_path mds$num)
6737         mdtosc=${mdtosc/-MDT*/-MDT\*}
6738         output=$(do_facet mds$num lctl get_param -n \
6739             osc.$mdtosc.$PROC_CLI 2>/dev/null)
6740         tmpcnt=`count_flvr "$output" $flavor`
6741         cnt=$((cnt + tmpcnt))
6742     done
6743     echo $cnt;
6744 }
6745
6746 flvr_cnt_mgc2mgs()
6747 {
6748     local flavor=$1
6749
6750     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
6751     count_flvr "$output" $flavor
6752 }
6753
6754 do_check_flavor()
6755 {
6756     local dir=$1        # from to
6757     local flavor=$2     # flavor expected
6758     local res=0
6759
6760     if [ $dir == "cli2mdt" ]; then
6761         res=`flvr_cnt_cli2mdt $flavor`
6762     elif [ $dir == "cli2ost" ]; then
6763         res=`flvr_cnt_cli2ost $flavor`
6764     elif [ $dir == "mdt2mdt" ]; then
6765         res=`flvr_cnt_mdt2mdt $flavor`
6766     elif [ $dir == "mdt2ost" ]; then
6767         res=`flvr_cnt_mdt2ost $flavor`
6768     elif [ $dir == "all2ost" ]; then
6769         res1=`flvr_cnt_mdt2ost $flavor`
6770         res2=`flvr_cnt_cli2ost $flavor`
6771         res=$((res1 + res2))
6772     elif [ $dir == "all2mdt" ]; then
6773         res1=`flvr_cnt_mdt2mdt $flavor`
6774         res2=`flvr_cnt_cli2mdt $flavor`
6775         res=$((res1 + res2))
6776     elif [ $dir == "all2all" ]; then
6777         res1=`flvr_cnt_mdt2ost $flavor`
6778         res2=`flvr_cnt_cli2ost $flavor`
6779         res3=`flvr_cnt_mdt2mdt $flavor`
6780         res4=`flvr_cnt_cli2mdt $flavor`
6781         res=$((res1 + res2 + res3 + res4))
6782     fi
6783
6784     echo $res
6785 }
6786
6787 wait_flavor()
6788 {
6789     local dir=$1        # from to
6790     local flavor=$2     # flavor expected
6791     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
6792
6793     local res=0
6794
6795     for ((i=0;i<20;i++)); do
6796         echo -n "checking $dir..."
6797         res=$(do_check_flavor $dir $flavor)
6798         echo "found $res/$expect $flavor connections"
6799         [ $res -ge $expect ] && return 0
6800         sleep 4
6801     done
6802
6803     echo "Error checking $flavor of $dir: expect $expect, actual $res"
6804     return 1
6805 }
6806
6807 restore_to_default_flavor()
6808 {
6809     local proc="mgs.MGS.live.$FSNAME"
6810
6811     echo "restoring to default flavor..."
6812
6813     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
6814
6815     # remove all existing rules if any
6816     if [ $nrule -ne 0 ]; then
6817         echo "$nrule existing rules"
6818         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
6819             echo "remove rule: $rule"
6820             spec=`echo $rule | awk -F = '{print $1}'`
6821             do_facet mgs "$LCTL conf_param -d $spec"
6822         done
6823     fi
6824
6825     # verify no rules left
6826     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
6827     [ $nrule -ne 0 ] && error "still $nrule rules left"
6828
6829     # wait for default flavor to be applied
6830     # currently default flavor for all connections are 'null'
6831     wait_flavor all2all null
6832     echo "now at default flavor settings"
6833 }
6834
6835 set_flavor_all()
6836 {
6837     local flavor=${1:-null}
6838
6839     echo "setting all flavor to $flavor"
6840
6841     # FIXME need parameter to this fn
6842     # and remove global vars
6843     local cnt_all2all=$(calc_connection_cnt all2all)
6844
6845     local res=$(do_check_flavor all2all $flavor)
6846     if [ $res -eq $cnt_all2all ]; then
6847         echo "already have total $res $flavor connections"
6848         return
6849     fi
6850
6851     echo "found $res $flavor out of total $cnt_all2all connections"
6852     restore_to_default_flavor
6853
6854     [[ $flavor = null ]] && return 0
6855
6856     set_rule $FSNAME any any $flavor
6857     wait_flavor all2all $flavor
6858 }
6859
6860
6861 check_logdir() {
6862     local dir=$1
6863     # Checking for shared logdir
6864     if [ ! -d $dir ]; then
6865         # Not found. Create local logdir
6866         mkdir -p $dir
6867     else
6868         touch $dir/check_file.$(hostname -s)
6869     fi
6870     return 0
6871 }
6872
6873 check_write_access() {
6874         local dir=$1
6875         local list=${2:-$(comma_list $(nodes_list))}
6876         local node
6877         local file
6878
6879         for node in ${list//,/ }; do
6880                 file=$dir/check_file.$(short_nodename $node)
6881                 if [[ ! -f "$file" ]]; then
6882                         # Logdir not accessible/writable from this node.
6883                         return 1
6884                 fi
6885                 rm -f $file || return 1
6886         done
6887         return 0
6888 }
6889
6890 init_logging() {
6891         [[ -n $YAML_LOG ]] && return
6892         local save_umask=$(umask)
6893         umask 0000
6894
6895         export YAML_LOG=${LOGDIR}/results.yml
6896         mkdir -p $LOGDIR
6897         init_clients_lists
6898
6899         # If the yaml log already exists then we will just append to it
6900         if [ ! -f $YAML_LOG ]; then
6901                 if check_shared_dir $LOGDIR; then
6902                         touch $LOGDIR/shared
6903                         echo "Logging to shared log directory: $LOGDIR"
6904                 else
6905                         echo "Logging to local directory: $LOGDIR"
6906                 fi
6907
6908                 yml_nodes_file $LOGDIR >> $YAML_LOG
6909                 yml_results_file >> $YAML_LOG
6910         fi
6911
6912         umask $save_umask
6913
6914         # If modules are not yet loaded then older "lctl lustre_build_version"
6915         # will fail.  Use lctl build version instead.
6916         log "Client: $($LCTL lustre_build_version)"
6917         log "MDS: $(do_facet $SINGLEMDS $LCTL lustre_build_version 2>/dev/null||
6918                     do_facet $SINGLEMDS $LCTL --version)"
6919         log "OSS: $(do_facet ost1 $LCTL lustre_build_version 2> /dev/null ||
6920                     do_facet ost1 $LCTL --version)"
6921 }
6922
6923 log_test() {
6924     yml_log_test $1 >> $YAML_LOG
6925 }
6926
6927 log_test_status() {
6928      yml_log_test_status $@ >> $YAML_LOG
6929 }
6930
6931 log_sub_test_begin() {
6932     yml_log_sub_test_begin "$@" >> $YAML_LOG
6933 }
6934
6935 log_sub_test_end() {
6936     yml_log_sub_test_end "$@" >> $YAML_LOG
6937 }
6938
6939 run_llverdev()
6940 {
6941         local dev=$1
6942         local llverdev_opts=$2
6943         local devname=$(basename $1)
6944         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
6945         # loop devices aren't in /proc/partitions
6946         [ "x$size" == "x" ] && local size=$(ls -l $dev | awk '{print $5}')
6947
6948         size=$(($size / 1024 / 1024)) # Gb
6949
6950         local partial_arg=""
6951         # Run in partial (fast) mode if the size
6952         # of a partition > 1 GB
6953         [ $size -gt 1 ] && partial_arg="-p"
6954
6955         llverdev --force $partial_arg $llverdev_opts $dev
6956 }
6957
6958 run_llverfs()
6959 {
6960         local dir=$1
6961         local llverfs_opts=$2
6962         local use_partial_arg=$3
6963         local partial_arg=""
6964         local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB
6965
6966         # Run in partial (fast) mode if the size
6967         # of a partition > 1 GB
6968         [ "x$use_partial_arg" != "xno" ] && [ $size -gt 1 ] && partial_arg="-p"
6969
6970         llverfs $partial_arg $llverfs_opts $dir
6971 }
6972
6973 #Remove objects from OST
6974 remove_ost_objects() {
6975         local facet=$1
6976         local ostdev=$2
6977         local group=$3
6978         shift 3
6979         local objids="$@"
6980         local mntpt=$(facet_mntpt $facet)
6981         local opts=$OST_MOUNT_OPTS
6982         local i
6983         local rc
6984
6985         echo "removing objects from $ostdev on $facet: $objids"
6986         if ! test -b $ostdev; then
6987                 opts=$(csa_add "$opts" -o loop)
6988         fi
6989         mount -t $(facet_fstype $facet) $opts $ostdev $mntpt ||
6990                 return $?
6991         rc=0
6992         for i in $objids; do
6993                 rm $mntpt/O/$group/d$((i % 32))/$i || { rc=$?; break; }
6994         done
6995         umount -f $mntpt || return $?
6996         return $rc
6997 }
6998
6999 #Remove files from MDT
7000 remove_mdt_files() {
7001         local facet=$1
7002         local mdtdev=$2
7003         shift 2
7004         local files="$@"
7005         local mntpt=$(facet_mntpt $facet)
7006         local opts=$MDS_MOUNT_OPTS
7007
7008         echo "removing files from $mdtdev on $facet: $files"
7009         if [ $(facet_fstype $facet) == ldiskfs ] &&
7010            ! do_facet $facet test -b $mdtdev; then
7011                 opts=$(csa_add "$opts" -o loop)
7012         fi
7013         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
7014                 return $?
7015         rc=0
7016         for f in $files; do
7017                 rm $mntpt/ROOT/$f || { rc=$?; break; }
7018         done
7019         umount -f $mntpt || return $?
7020         return $rc
7021 }
7022
7023 duplicate_mdt_files() {
7024         local facet=$1
7025         local mdtdev=$2
7026         shift 2
7027         local files="$@"
7028         local mntpt=$(facet_mntpt $facet)
7029         local opts=$MDS_MOUNT_OPTS
7030
7031         echo "duplicating files on $mdtdev on $facet: $files"
7032         mkdir -p $mntpt || return $?
7033         if [ $(facet_fstype $facet) == ldiskfs ] &&
7034            ! do_facet $facet test -b $mdtdev; then
7035                 opts=$(csa_add "$opts" -o loop)
7036         fi
7037         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
7038                 return $?
7039
7040     do_umount() {
7041         trap 0
7042         popd > /dev/null
7043         rm $tmp
7044         umount -f $mntpt
7045     }
7046     trap do_umount EXIT
7047
7048     tmp=$(mktemp $TMP/setfattr.XXXXXXXXXX)
7049     pushd $mntpt/ROOT > /dev/null || return $?
7050     rc=0
7051     for f in $files; do
7052         touch $f.bad || return $?
7053         getfattr -n trusted.lov $f | sed "s#$f#&.bad#" > $tmp
7054         rc=${PIPESTATUS[0]}
7055         [ $rc -eq 0 ] || return $rc
7056         setfattr --restore $tmp || return $?
7057     done
7058     do_umount
7059 }
7060
7061 run_sgpdd () {
7062     local devs=${1//,/ }
7063     shift
7064     local params=$@
7065     local rslt=$TMP/sgpdd_survey
7066
7067     # sgpdd-survey cleanups ${rslt}.* files
7068
7069     local cmd="rslt=$rslt $params scsidevs=\"$devs\" $SGPDDSURVEY"
7070     echo + $cmd
7071     eval $cmd
7072     cat ${rslt}.detail
7073 }
7074
7075 # returns the canonical name for an ldiskfs device
7076 ldiskfs_canon() {
7077         local dev="$1"
7078         local facet="$2"
7079
7080         do_facet $facet "dv=\\\$(lctl get_param -n $dev);
7081 if foo=\\\$(lvdisplay -c \\\$dv 2>/dev/null); then
7082     echo dm-\\\${foo##*:};
7083 else
7084     echo \\\$(basename \\\$dv);
7085 fi;"
7086 }
7087
7088 is_sanity_benchmark() {
7089     local benchmarks="dbench bonnie iozone fsx"
7090     local suite=$1
7091     for b in $benchmarks; do
7092         if [ "$b" == "$suite" ]; then
7093             return 0
7094         fi
7095     done
7096     return 1
7097 }
7098
7099 min_ost_size () {
7100     $LCTL get_param -n osc.*.kbytesavail | sort -n | head -n1
7101 }
7102
7103 #
7104 # Get the available size (KB) of a given obd target.
7105 #
7106 get_obd_size() {
7107         local facet=$1
7108         local obd=$2
7109         local size
7110
7111         [[ $facet != client ]] || return 0
7112
7113         size=$(do_facet $facet $LCTL get_param -n *.$obd.kbytesavail | head -n1)
7114         echo -n $size
7115 }
7116
7117 #
7118 # Get the page size (bytes) on a given facet node.
7119 #
7120 get_page_size() {
7121         local facet=$1
7122         local size=$(getconf PAGE_SIZE 2>/dev/null)
7123
7124         [ -z "$CLIENTONLY" ] && size=$(do_facet $facet getconf PAGE_SIZE)
7125         echo -n ${size:-4096}
7126 }
7127
7128 #
7129 # Get the block count of the filesystem.
7130 #
7131 get_block_count() {
7132         local facet=$1
7133         local device=$2
7134         local count
7135
7136         [ -z "$CLIENTONLY" ] && count=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
7137                 awk '/^Block count:/ {print $3}')
7138         echo -n ${count:-0}
7139 }
7140
7141 # Get the block size of the filesystem.
7142 get_block_size() {
7143         local facet=$1
7144         local device=$2
7145         local size
7146
7147         [ -z "$CLIENTONLY" ] && size=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
7148                 awk '/^Block size:/ {print $3}')
7149         echo -n ${size:-0}
7150 }
7151
7152 # Check whether the "large_xattr" feature is enabled or not.
7153 large_xattr_enabled() {
7154         [[ $(facet_fstype $SINGLEMDS) == zfs ]] && return 0
7155
7156         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
7157
7158         do_facet $SINGLEMDS "$DUMPE2FS -h $mds_dev 2>&1 |
7159                 grep -E -q '(ea_inode|large_xattr)'"
7160         return ${PIPESTATUS[0]}
7161 }
7162
7163 # Get the maximum xattr size supported by the filesystem.
7164 max_xattr_size() {
7165     local size
7166
7167     if large_xattr_enabled; then
7168         # include/linux/limits.h: #define XATTR_SIZE_MAX 65536
7169         size=65536
7170     else
7171         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
7172         local block_size=$(get_block_size $SINGLEMDS $mds_dev)
7173
7174         # maximum xattr size = size of block - size of header -
7175         #                      size of 1 entry - 4 null bytes
7176         size=$((block_size - 32 - 32 - 4))
7177     fi
7178
7179     echo $size
7180 }
7181
7182 # Dump the value of the named xattr from a file.
7183 get_xattr_value() {
7184     local xattr_name=$1
7185     local file=$2
7186
7187     echo "$(getfattr -n $xattr_name --absolute-names --only-values $file)"
7188 }
7189
7190 # Generate a string with size of $size bytes.
7191 generate_string() {
7192     local size=${1:-1024} # in bytes
7193
7194     echo "$(head -c $size < /dev/zero | tr '\0' y)"
7195 }
7196
7197 reformat_external_journal() {
7198         local facet=$1
7199         local var
7200
7201         var=${facet}_JRN
7202         if [ -n "${!var}" ]; then
7203                 local rcmd="do_facet $facet"
7204
7205                 echo "reformat external journal on $facet:${!var}"
7206                 ${rcmd} mke2fs -O journal_dev ${!var} || return 1
7207         fi
7208 }
7209
7210 # MDT file-level backup/restore
7211 mds_backup_restore() {
7212         local facet=$1
7213         local igif=$2
7214         local devname=$(mdsdevname $(facet_number $facet))
7215         local mntpt=$(facet_mntpt brpt)
7216         local rcmd="do_facet $facet"
7217         local metaea=${TMP}/backup_restore.ea
7218         local metadata=${TMP}/backup_restore.tgz
7219         local opts=${MDS_MOUNT_OPTS}
7220         local svc=${facet}_svc
7221
7222         if ! ${rcmd} test -b ${devname}; then
7223                 opts=$(csa_add "$opts" -o loop)
7224         fi
7225
7226         echo "file-level backup/restore on $facet:${devname}"
7227
7228         # step 1: build mount point
7229         ${rcmd} mkdir -p $mntpt
7230         # step 2: cleanup old backup
7231         ${rcmd} rm -f $metaea $metadata
7232         # step 3: mount dev
7233         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
7234         if [ ! -z $igif ]; then
7235                 # step 3.5: rm .lustre
7236                 ${rcmd} rm -rf $mntpt/ROOT/.lustre || return 1
7237         fi
7238         # step 4: backup metaea
7239         echo "backup EA"
7240         ${rcmd} "cd $mntpt && getfattr -R -d -m '.*' -P . > $metaea && cd -" ||
7241                 return 2
7242         # step 5: backup metadata
7243         echo "backup data"
7244         ${rcmd} tar zcf $metadata -C $mntpt/ . > /dev/null 2>&1 || return 3
7245         # step 6: umount
7246         ${rcmd} $UMOUNT $mntpt || return 4
7247         # step 8: reformat dev
7248         echo "reformat new device"
7249         format_mdt $(facet_number $facet)
7250         # step 9: mount dev
7251         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 7
7252         # step 10: restore metadata
7253         echo "restore data"
7254         ${rcmd} tar zxfp $metadata -C $mntpt > /dev/null 2>&1 || return 8
7255         # step 11: restore metaea
7256         echo "restore EA"
7257         ${rcmd} "cd $mntpt && setfattr --restore=$metaea && cd - " || return 9
7258         # step 12: remove recovery logs
7259         echo "remove recovery logs"
7260         ${rcmd} rm -fv $mntpt/OBJECTS/* $mntpt/CATALOGS
7261         # step 13: umount dev
7262         ${rcmd} $UMOUNT $mntpt || return 10
7263         # step 14: cleanup tmp backup
7264         ${rcmd} rm -f $metaea $metadata
7265         # step 15: reset device label - it's not virgin on
7266         ${rcmd} e2label $devname ${!svc}
7267 }
7268
7269 # remove OI files
7270 mds_remove_ois() {
7271         local facet=$1
7272         local idx=$2
7273         local devname=$(mdsdevname $(facet_number $facet))
7274         local mntpt=$(facet_mntpt brpt)
7275         local rcmd="do_facet $facet"
7276         local opts=${MDS_MOUNT_OPTS}
7277
7278         if ! ${rcmd} test -b ${devname}; then
7279                 opts=$(csa_add "$opts" -o loop)
7280         fi
7281
7282         echo "removing OI files on $facet: idx=${idx}"
7283
7284         # step 1: build mount point
7285         ${rcmd} mkdir -p $mntpt
7286         # step 2: mount dev
7287         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
7288         if [ -z $idx ]; then
7289                 # step 3: remove all OI files
7290                 ${rcmd} rm -fv $mntpt/oi.16*
7291         elif [ $idx -lt 2 ]; then
7292                 ${rcmd} rm -fv $mntpt/oi.16.${idx}
7293         else
7294                 local i
7295
7296                 # others, rm oi.16.[idx, idx * idx, idx ** ...]
7297                 for ((i=${idx}; i<64; i=$((i * idx)))); do
7298                         ${rcmd} rm -fv $mntpt/oi.16.${i}
7299                 done
7300         fi
7301         # step 4: umount
7302         ${rcmd} $UMOUNT $mntpt || return 2
7303         # OI files will be recreated when mounted as lustre next time.
7304 }
7305
7306 # generate maloo upload-able log file name
7307 # \param logname specify unique part of file name
7308 generate_logname() {
7309         local logname=${1:-"default_logname"}
7310
7311         echo "$TESTLOG_PREFIX.$TESTNAME.$logname.$(hostname -s).log"
7312 }
7313
7314 # make directory on different MDTs
7315 test_mkdir() {
7316         local path
7317         local p_option
7318         local stripe_count=2
7319         local stripe_index=-1
7320         local OPTIND=1
7321
7322         while getopts "c:i:p" opt; do
7323                 case $opt in
7324                         c) stripe_count=$OPTARG;;
7325                         i) stripe_index=$OPTARG;;
7326                         p) p_option="-p";;
7327                         \?) error "only support -i -c -p";;
7328                 esac
7329         done
7330
7331         shift $((OPTIND - 1))
7332         [ $# -eq 1 ] || error "Only creating single directory is supported"
7333         path="$*"
7334
7335         if [ "$p_option" == "-p" ]; then
7336                 local parent=$(dirname $path)
7337
7338                 [ -d $path ] && return 0
7339                 [ ! -d ${parent} ] && mkdir -p ${parent}
7340         fi
7341
7342         if [ $MDSCOUNT -le 1 ]; then
7343                 mkdir $path
7344         else
7345                 local test_num=$(echo $testnum | sed -e 's/[^0-9]*//g')
7346                 local mdt_index
7347
7348                 if [ $stripe_index -eq -1 ]; then
7349                         mdt_index=$((test_num % MDSCOUNT))
7350                 else
7351                         mdt_index=$stripe_index
7352                 fi
7353                 echo "striped dir -i$mdt_index -c$stripe_count $path"
7354                 $LFS setdirstripe -i$mdt_index -c$stripe_count $path
7355         fi
7356 }
7357
7358 # free_fd: find the smallest and not in use file descriptor [above @last_fd]
7359 #
7360 # If called many times, passing @last_fd will avoid repeated searching
7361 # already-open FDs repeatedly if we know they are still in use.
7362 #
7363 # usage: free_fd [last_fd]
7364 free_fd()
7365 {
7366         local max_fd=$(ulimit -n)
7367         local fd=$((${1:-2} + 1))
7368
7369         while [[ $fd -le $max_fd && -e /proc/self/fd/$fd ]]; do
7370                 ((++fd))
7371         done
7372         [ $fd -lt $max_fd ] || error "finding free file descriptor failed"
7373         echo $fd
7374 }
7375
7376 check_mount_and_prep()
7377 {
7378         is_mounted $MOUNT || setupall
7379
7380         rm -rf $DIR/[df][0-9]* || error "Fail to cleanup the env!"
7381         mkdir $DIR/$tdir || error "Fail to mkdir $DIR/$tdir."
7382         for idx in $(seq $MDSCOUNT); do
7383                 local name="MDT$(printf '%04x' $((idx - 1)))"
7384                 rm -rf $MOUNT/.lustre/lost+found/$name/*
7385         done
7386 }
7387
7388 # calcule how many ost-objects to be created.
7389 precreated_ost_obj_count()
7390 {
7391         local mdt_idx=$1
7392         local ost_idx=$2
7393         local mdt_name="MDT$(printf '%04x' $mdt_idx)"
7394         local ost_name="OST$(printf '%04x' $ost_idx)"
7395         local proc_path="${FSNAME}-${ost_name}-osc-${mdt_name}"
7396         local last_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \
7397                         osp.$proc_path.prealloc_last_id)
7398         local next_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \
7399                         osp.$proc_path.prealloc_next_id)
7400         echo $((last_id - next_id + 1))
7401 }
7402
7403 check_file_in_pool()
7404 {
7405         local file=$1
7406         local pool=$2
7407         local tlist="$3"
7408         local res=$($GETSTRIPE $file | grep 0x | cut -f2)
7409         for i in $res
7410         do
7411                 for t in $tlist ; do
7412                         [ "$i" -eq "$t" ] && continue 2
7413                 done
7414
7415                 echo "pool list: $tlist"
7416                 echo "striping: $res"
7417                 error_noexit "$file not allocated in $pool"
7418                 return 1
7419         done
7420         return 0
7421 }
7422
7423 pool_add() {
7424         echo "Creating new pool"
7425         local pool=$1
7426
7427         create_pool $FSNAME.$pool ||
7428                 { error_noexit "No pool created, result code $?"; return 1; }
7429         [ $($LFS pool_list $FSNAME | grep -c "$FSNAME.${pool}\$") -eq 1 ] ||
7430                 { error_noexit "$pool not in lfs pool_list"; return 2; }
7431 }
7432
7433 pool_add_targets() {
7434         echo "Adding targets to pool"
7435         local pool=$1
7436         local first=$2
7437         local last=$3
7438         local step=${4:-1}
7439
7440         local list=$(seq $first $step $last)
7441
7442         local t=$(for i in $list; do printf "$FSNAME-OST%04x_UUID " $i; done)
7443         do_facet mgs $LCTL pool_add \
7444                         $FSNAME.$pool $FSNAME-OST[$first-$last/$step]
7445
7446         # wait for OSTs to be added to the pool
7447         for mds_id in $(seq $MDSCOUNT); do
7448                 local mdt_id=$((mds_id-1))
7449                 local lodname=$FSNAME-MDT$(printf "%04x" $mdt_id)-mdtlov
7450                 wait_update_facet mds$mds_id \
7451                         "lctl get_param -n lod.$lodname.pools.$pool |
7452                                 sort -u | tr '\n' ' ' " "$t" || {
7453                         error_noexit "mds$mds_id: Add to pool failed"
7454                         return 3
7455                 }
7456         done
7457         wait_update $HOSTNAME "lctl get_param -n lov.$FSNAME-*.pools.$pool \
7458                         | sort -u | tr '\n' ' ' " "$t" || {
7459                 error_noexit "Add to pool failed"
7460                 return 1
7461         }
7462         local lfscount=$($LFS pool_list $FSNAME.$pool | grep -c "\-OST")
7463         local addcount=$(((last - first) / step + 1))
7464         [ $lfscount -eq $addcount ] || {
7465                 error_noexit "lfs pool_list bad ost count" \
7466                                                 "$lfscount != $addcount"
7467                 return 2
7468         }
7469 }
7470
7471 pool_set_dir() {
7472         local pool=$1
7473         local tdir=$2
7474         echo "Setting pool on directory $tdir"
7475
7476         $SETSTRIPE -c 2 -p $pool $tdir && return 0
7477
7478         error_noexit "Cannot set pool $pool to $tdir"
7479         return 1
7480 }
7481
7482 pool_check_dir() {
7483         local pool=$1
7484         local tdir=$2
7485         echo "Checking pool on directory $tdir"
7486
7487         local res=$($GETSTRIPE --pool $tdir | sed "s/\s*$//")
7488         [ "$res" = "$pool" ] && return 0
7489
7490         error_noexit "Pool on '$tdir' is '$res', not '$pool'"
7491         return 1
7492 }
7493
7494 pool_dir_rel_path() {
7495         echo "Testing relative path works well"
7496         local pool=$1
7497         local tdir=$2
7498         local root=$3
7499
7500         mkdir -p $root/$tdir/$tdir
7501         cd $root/$tdir
7502         pool_set_dir $pool $tdir          || return 1
7503         pool_set_dir $pool ./$tdir        || return 2
7504         pool_set_dir $pool ../$tdir       || return 3
7505         pool_set_dir $pool ../$tdir/$tdir || return 4
7506         rm -rf $tdir; cd - > /dev/null
7507 }
7508
7509 pool_alloc_files() {
7510         echo "Checking files allocation from directory pool"
7511         local pool=$1
7512         local tdir=$2
7513         local count=$3
7514         local tlist="$4"
7515
7516         local failed=0
7517         for i in $(seq -w 1 $count)
7518         do
7519                 local file=$tdir/file-$i
7520                 touch $file
7521                 check_file_in_pool $file $pool "$tlist" || \
7522                         failed=$((failed + 1))
7523         done
7524         [ "$failed" = 0 ] && return 0
7525
7526         error_noexit "$failed files not allocated in $pool"
7527         return 1
7528 }
7529
7530 pool_create_files() {
7531         echo "Creating files in pool"
7532         local pool=$1
7533         local tdir=$2
7534         local count=$3
7535         local tlist="$4"
7536
7537         mkdir -p $tdir
7538         local failed=0
7539         for i in $(seq -w 1 $count)
7540         do
7541                 local file=$tdir/spoo-$i
7542                 $SETSTRIPE -p $pool $file
7543                 check_file_in_pool $file $pool "$tlist" || \
7544                         failed=$((failed + 1))
7545         done
7546         [ "$failed" = 0 ] && return 0
7547
7548         error_noexit "$failed files not allocated in $pool"
7549         return 1
7550 }
7551
7552 pool_lfs_df() {
7553         echo "Checking 'lfs df' output"
7554         local pool=$1
7555
7556         local t=$($LCTL get_param -n lov.$FSNAME-clilov-*.pools.$pool |
7557                         tr '\n' ' ')
7558         local res=$($LFS df --pool $FSNAME.$pool |
7559                         awk '{print $1}' |
7560                         grep "$FSNAME-OST" |
7561                         tr '\n' ' ')
7562         [ "$res" = "$t" ] && return 0
7563
7564         error_noexit "Pools OSTs '$t' is not '$res' that lfs df reports"
7565         return 1
7566 }
7567
7568 pool_file_rel_path() {
7569         echo "Creating files in a pool with relative pathname"
7570         local pool=$1
7571         local tdir=$2
7572
7573         mkdir -p $tdir ||
7574                 { error_noexit "unable to create $tdir"; return 1 ; }
7575         local file="/..$tdir/$tfile-1"
7576         $SETSTRIPE -p $pool $file ||
7577                 { error_noexit "unable to create $file" ; return 2 ; }
7578
7579         cd $tdir
7580         $SETSTRIPE -p $pool $tfile-2 || {
7581                 error_noexit "unable to create $tfile-2 in $tdir"
7582                 return 3
7583         }
7584 }
7585
7586 pool_remove_first_target() {
7587         echo "Removing first target from a pool"
7588         local pool=$1
7589
7590         local pname="lov.$FSNAME-*.pools.$pool"
7591         local t=$($LCTL get_param -n $pname | head -1)
7592         do_facet mgs $LCTL pool_remove $FSNAME.$pool $t
7593         for mds_id in $(seq $MDSCOUNT); do
7594                 local mdt_id=$((mds_id-1))
7595                 local lodname=$FSNAME-MDT$(printf "%04x" $mdt_id)-mdtlov
7596                 wait_update_facet mds$mds_id \
7597                         "lctl get_param -n lod.$lodname.pools.$pool |
7598                                 grep $t" "" || {
7599                         error_noexit "mds$mds_id: $t not removed from" \
7600                         "$FSNAME.$pool"
7601                         return 2
7602                 }
7603         done
7604         wait_update $HOSTNAME "lctl get_param -n $pname | grep $t" "" || {
7605                 error_noexit "$t not removed from $FSNAME.$pool"
7606                 return 1
7607         }
7608 }
7609
7610 pool_remove_all_targets() {
7611         echo "Removing all targets from pool"
7612         local pool=$1
7613         local file=$2
7614         local pname="lov.$FSNAME-*.pools.$pool"
7615         for t in $($LCTL get_param -n $pname | sort -u)
7616         do
7617                 do_facet mgs $LCTL pool_remove $FSNAME.$pool $t
7618         done
7619         for mds_id in $(seq $MDSCOUNT); do
7620                 local mdt_id=$((mds_id-1))
7621                 local lodname=$FSNAME-MDT$(printf "%04x" $mdt_id)-mdtlov
7622                 wait_update_facet mds$mds_id "lctl get_param -n \
7623                         lod.$lodname.pools.$pool" "" || {
7624                         error_noexit "mds$mds_id: Pool $pool not drained"
7625                         return 4
7626                 }
7627         done
7628         wait_update $HOSTNAME "lctl get_param -n $pname" "" || {
7629                 error_noexit "Pool $FSNAME.$pool cannot be drained"
7630                 return 1
7631         }
7632         # striping on an empty/nonexistant pool should fall back
7633         # to "pool of everything"
7634         touch $file || {
7635                 error_noexit "failed to use fallback striping for empty pool"
7636                 return 2
7637         }
7638         # setstripe on an empty pool should fail
7639         $SETSTRIPE -p $pool $file 2>/dev/null && {
7640                 error_noexit "expected failure when creating file" \
7641                                                         "with empty pool"
7642                 return 3
7643         }
7644         return 0
7645 }
7646
7647 pool_remove() {
7648         echo "Destroying pool"
7649         local pool=$1
7650         local file=$2
7651
7652         do_facet mgs $LCTL pool_destroy $FSNAME.$pool
7653
7654         sleep 2
7655         # striping on an empty/nonexistant pool should fall back
7656         # to "pool of everything"
7657         touch $file || {
7658                 error_noexit "failed to use fallback striping for missing pool"
7659                 return 1
7660         }
7661         # setstripe on an empty pool should fail
7662         $SETSTRIPE -p $pool $file 2>/dev/null && {
7663                 error_noexit "expected failure when creating file" \
7664                                                         "with missing pool"
7665                 return 2
7666         }
7667
7668         # get param should return err once pool is gone
7669         if wait_update $HOSTNAME "lctl get_param -n \
7670                 lov.$FSNAME-*.pools.$pool 2>/dev/null || echo foo" "foo"
7671         then
7672                 remove_pool_from_list $FSNAME.$pool
7673                 return 0
7674         fi
7675         error_noexit "Pool $FSNAME.$pool is not destroyed"
7676         return 3
7677 }
7678
7679 # Get and check the actual stripe count of one file.
7680 # Usage: check_stripe_count <file> <expected_stripe_count>
7681 check_stripe_count() {
7682         local file=$1
7683         local expected=$2
7684         local actual
7685
7686         [[ -z "$file" || -z "$expected" ]] &&
7687                 error "check_stripe_count: invalid argument"
7688
7689         local cmd="$GETSTRIPE -c $file"
7690         actual=$($cmd) || error "$cmd failed"
7691         actual=${actual%% *}
7692
7693         if [[ $actual -ne $expected ]]; then
7694                 [[ $expected -eq -1 ]] ||
7695                         error "$cmd wrong: found $actual, expected $expected"
7696                 [[ $actual -eq $OSTCOUNT ]] ||
7697                         error "$cmd wrong: found $actual, expected $OSTCOUNT"
7698         fi
7699 }
7700
7701 # Get and check the actual list of OST indices on one file.
7702 # Usage: check_obdidx <file> <expected_comma_separated_list_of_ost_indices>
7703 check_obdidx() {
7704         local file=$1
7705         local expected=$2
7706         local obdidx
7707
7708         [[ -z "$file" || -z "$expected" ]] &&
7709                 error "check_obdidx: invalid argument!"
7710
7711         obdidx=$(comma_list $($GETSTRIPE $file | grep -A $OSTCOUNT obdidx |
7712                               grep -v obdidx | awk '{print $1}' | xargs))
7713
7714         [[ $obdidx = $expected ]] ||
7715                 error "list of OST indices on $file is $obdidx," \
7716                       "should be $expected"
7717 }
7718
7719 # Get and check the actual OST index of the first stripe on one file.
7720 # Usage: check_start_ost_idx <file> <expected_start_ost_idx>
7721 check_start_ost_idx() {
7722         local file=$1
7723         local expected=$2
7724         local start_ost_idx
7725
7726         [[ -z "$file" || -z "$expected" ]] &&
7727                 error "check_start_ost_idx: invalid argument!"
7728
7729         start_ost_idx=$($GETSTRIPE $file | grep -A 1 obdidx | grep -v obdidx |
7730                         awk '{print $1}')
7731
7732         [[ $start_ost_idx = $expected ]] ||
7733                 error "OST index of the first stripe on $file is" \
7734                       "$start_ost_idx, should be $expected"
7735 }
7736
7737 killall_process () {
7738         local clients=${1:-$(hostname)}
7739         local name=$2
7740         local signal=$3
7741         local rc=0
7742
7743         do_nodes $clients "killall $signal $name"
7744 }
7745
7746 lsnapshot_create()
7747 {
7748         do_facet mgs "$LCTL snapshot_create -F $FSNAME $*"
7749 }
7750
7751 lsnapshot_destroy()
7752 {
7753         do_facet mgs "$LCTL snapshot_destroy -F $FSNAME $*"
7754 }
7755
7756 lsnapshot_modify()
7757 {
7758         do_facet mgs "$LCTL snapshot_modify -F $FSNAME $*"
7759 }
7760
7761 lsnapshot_list()
7762 {
7763         do_facet mgs "$LCTL snapshot_list -F $FSNAME $*"
7764 }
7765
7766 lsnapshot_mount()
7767 {
7768         do_facet mgs "$LCTL snapshot_mount -F $FSNAME $*"
7769 }
7770
7771 lsnapshot_umount()
7772 {
7773         do_facet mgs "$LCTL snapshot_umount -F $FSNAME $*"
7774 }
7775
7776 lss_err()
7777 {
7778         local msg=$1
7779
7780         do_facet mgs "cat $LSNAPSHOT_LOG"
7781         error $msg
7782 }
7783
7784 lss_cleanup()
7785 {
7786         echo "Cleaning test environment ..."
7787
7788         # Every lsnapshot command takes exclusive lock with others,
7789         # so can NOT destroy the snapshot during list with 'xargs'.
7790         while true; do
7791                 local ssname=$(lsnapshot_list | grep snapshot_name |
7792                         grep lss_ | awk '{ print $2 }' | head -n 1)
7793                 [ -z "$ssname" ] && break
7794
7795                 lsnapshot_destroy -n $ssname -f ||
7796                         lss_err "Fail to destroy $ssname by force"
7797         done
7798 }
7799
7800 lss_gen_conf_one()
7801 {
7802         local facet=$1
7803         local role=$2
7804         local idx=$3
7805
7806         local host=$(facet_active_host $facet)
7807         local dir=$(dirname $(facet_vdevice $facet))
7808         local pool=$(zpool_name $facet)
7809         local lfsname=$(zfs_local_fsname $facet)
7810         local label=${FSNAME}-${role}$(printf '%04x' $idx)
7811
7812         do_facet mgs \
7813                 "echo '$host - $label zfs:${dir}/${pool}/${lfsname} - -' >> \
7814                 $LSNAPSHOT_CONF"
7815 }
7816
7817 lss_gen_conf()
7818 {
7819         do_facet mgs "rm -f $LSNAPSHOT_CONF"
7820         echo "Generating $LSNAPSHOT_CONF on MGS ..."
7821
7822         if ! combined_mgs_mds ; then
7823                 [ $(facet_fstype mgs) != zfs ] &&
7824                         skip "Lustre snapshot 1 only works for ZFS backend" &&
7825                         exit 0
7826
7827                 local host=$(facet_active_host mgs)
7828                 local dir=$(dirname $(facet_vdevice mgs))
7829                 local pool=$(zpool_name mgs)
7830                 local lfsname=$(zfs_local_fsname mgs)
7831
7832                 do_facet mgs \
7833                         "echo '$host - MGS zfs:${dir}/${pool}/${lfsname} - -' \
7834                         >> $LSNAPSHOT_CONF" || lss_err "generate lss conf (mgs)"
7835         fi
7836
7837         for num in `seq $MDSCOUNT`; do
7838                 [ $(facet_fstype mds$num) != zfs ] &&
7839                         skip "Lustre snapshot 1 only works for ZFS backend" &&
7840                         exit 0
7841
7842                 lss_gen_conf_one mds$num MDT $((num - 1)) ||
7843                         lss_err "generate lss conf (mds$num)"
7844         done
7845
7846         for num in `seq $OSTCOUNT`; do
7847                 [ $(facet_fstype ost$num) != zfs ] &&
7848                         skip "Lustre snapshot 1 only works for ZFS backend" &&
7849                         exit 0
7850
7851                 lss_gen_conf_one ost$num OST $((num - 1)) ||
7852                         lss_err "generate lss conf (ost$num)"
7853         done
7854
7855         do_facet mgs "cat $LSNAPSHOT_CONF"
7856 }