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