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