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