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