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