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