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