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