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