Whamcloud - gitweb
LU-12722 target: disable recovery for local clients
[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 # Mount the file system on the MDS
2335 mount_mds_client() {
2336         local mds_HOST=${SINGLEMDS}_HOST
2337         echo $mds_HOST
2338         do_facet $SINGLEMDS "mkdir -p $MOUNT2"
2339         zconf_mount $mds1_HOST $MOUNT2 $MOUNT_OPTS ||
2340                 error "unable to mount $MOUNT2 on MDS"
2341 }
2342
2343 # Unmount the file system on the MDS
2344 umount_mds_client() {
2345         local mds_HOST=${SINGLEMDS}_HOST
2346         zconf_umount $mds1_HOST $MOUNT2
2347         do_facet $SINGLEMDS "rm -rf $MOUNT2"
2348 }
2349
2350 # nodes is comma list
2351 sanity_mount_check_nodes () {
2352     local nodes=$1
2353     shift
2354     local mnts="$@"
2355     local mnt
2356
2357     # FIXME: assume that all cluster nodes run the same os
2358     [ "$(uname)" = Linux ] || return 0
2359
2360     local rc=0
2361     for mnt in $mnts ; do
2362         do_nodes $nodes "running=\\\$(grep -c $mnt' ' /proc/mounts);
2363 mpts=\\\$(mount | grep -c $mnt' ');
2364 if [ \\\$running -ne \\\$mpts ]; then
2365     echo \\\$(hostname) env are INSANE!;
2366     exit 1;
2367 fi"
2368     [ $? -eq 0 ] || rc=1
2369     done
2370     return $rc
2371 }
2372
2373 sanity_mount_check_servers () {
2374     [ -n "$CLIENTONLY" ] &&
2375         { echo "CLIENTONLY mode, skip mount_check_servers"; return 0; } || true
2376     echo Checking servers environments
2377
2378     # FIXME: modify get_facets to display all facets wo params
2379     local facets="$(get_facets OST),$(get_facets MDS),mgs"
2380     local node
2381     local mntpt
2382     local facet
2383     for facet in ${facets//,/ }; do
2384         node=$(facet_host ${facet})
2385         mntpt=$(facet_mntpt $facet)
2386         sanity_mount_check_nodes $node $mntpt ||
2387             { error "server $node environments are insane!"; return 1; }
2388     done
2389 }
2390
2391 sanity_mount_check_clients () {
2392     local clients=${1:-$CLIENTS}
2393     local mntpt=${2:-$MOUNT}
2394     local mntpt2=${3:-$MOUNT2}
2395
2396     [ -z $clients ] && clients=$(hostname)
2397     echo Checking clients $clients environments
2398
2399     sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
2400        error "clients environments are insane!"
2401 }
2402
2403 sanity_mount_check () {
2404     sanity_mount_check_servers || return 1
2405     sanity_mount_check_clients || return 2
2406 }
2407
2408 # mount clients if not mouted
2409 zconf_mount_clients() {
2410         local clients=$1
2411         local mnt=$2
2412         local opts=${3:-$MOUNT_OPTS}
2413         opts=${opts:+-o $opts}
2414         local flags=${4:-$MOUNT_FLAGS}
2415         local device=$MGSNID:/$FSNAME$FILESET
2416         if [ -z "$mnt" -o -z "$FSNAME" ]; then
2417                 echo "Bad conf mount command: opt=$flags $opts dev=$device " \
2418                      "mnt=$mnt"
2419                 exit 1
2420         fi
2421
2422         echo "Starting client $clients: $flags $opts $device $mnt"
2423         do_nodes $clients mkdir -p $mnt
2424         if [ -n "$FILESET" -a -z "$SKIP_FILESET" ]; then
2425                 if $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then
2426                         # Mount with own nodemap key
2427                         local i=0
2428                         # Mount all server nodes first with per-NM keys
2429                         for nmclient in ${clients//,/ }; do
2430 #                               do_nodes $(comma_list $(all_server_nodes)) "lgss_sk -t server -l $SK_PATH/nodemap/c$i.key -n c$i"
2431                                 do_nodes $(comma_list $(all_server_nodes)) "lgss_sk -t server -l $SK_PATH/nodemap/c$i.key"
2432                                 i=$((i + 1))
2433                         done
2434                         # set perms for per-nodemap keys else permission denied
2435                         do_nodes $(comma_list $(all_nodes)) \
2436                                 "keyctl show | grep lustre | cut -c1-11 |
2437                                 sed -e 's/ //g;' |
2438                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
2439                         local mountkey=$SK_PATH/$FSNAME-nmclient.key
2440                         i=0
2441                         for nmclient in ${clients//,/ }; do
2442                                 if $SK_UNIQUE_NM; then
2443                                         mountkey=$SK_PATH/nodemap/c$i.key
2444                                 fi
2445                                 do_node $nmclient "! grep -q $mnt' ' \
2446                                         /proc/mounts || umount $mnt"
2447                                 local prunedopts=$(add_sk_mntflag $prunedopts);
2448                                 prunedopts=$(echo $prunedopts | sed -e \
2449                                         "s#skpath=[^ ^,]*#skpath=$mountkey#g")
2450                                 set -x
2451                                 do_nodes $(comma_list $(all_server_nodes)) \
2452                                         "keyctl show"
2453                                 set +x
2454                                 do_node $nmclient $MOUNT_CMD $flags \
2455                                         $prunedopts $MGSNID:/$FSNAME $mnt ||
2456                                         return 1
2457                                 i=$((i + 1))
2458                         done
2459                 else
2460                         do_nodes $clients "! grep -q $mnt' ' /proc/mounts ||
2461                                         umount $mnt"
2462                         do_nodes $clients $MOUNT_CMD $flags $opts \
2463                                         $MGSNID:/$FSNAME $mnt || return 1
2464                 fi
2465                 #disable FILESET if not supported
2466                 do_nodes $clients lctl get_param -n \
2467                         mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
2468                                 device=$MGSNID:/$FSNAME
2469                 do_nodes $clients mkdir -p $mnt/$FILESET
2470                 do_nodes $clients "! grep -q $mnt' ' /proc/mounts ||
2471                         umount $mnt"
2472         fi
2473
2474         if $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then
2475                 # Mount with nodemap key
2476                 local i=0
2477                 local mountkey=$SK_PATH/$FSNAME-nmclient.key
2478                 for nmclient in ${clients//,/ }; do
2479                         if $SK_UNIQUE_NM; then
2480                                 mountkey=$SK_PATH/nodemap/c$i.key
2481                         fi
2482                         local prunedopts=$(echo $opts | sed -e \
2483                                 "s#skpath=[^ ^,]*#skpath=$mountkey#g");
2484                         do_node $nmclient "! grep -q $mnt' ' /proc/mounts ||
2485                                 umount $mnt"
2486                         do_node $nmclient "
2487                 running=\\\$(mount | grep -c $mnt' ');
2488                 rc=0;
2489                 if [ \\\$running -eq 0 ] ; then
2490                         mkdir -p $mnt;
2491                         $MOUNT_CMD $flags $prunedopts $device $mnt;
2492                         rc=\\\$?;
2493                 else
2494                         lustre_mnt_count=\\\$(mount | grep $mnt' ' | \
2495                                 grep 'type lustre' | wc -l);
2496                         if [ \\\$running -ne \\\$lustre_mnt_count ] ; then
2497                                 echo zconf_mount_clients FAILED: \
2498                                         mount count \\\$running, not matching \
2499                                         with mount count of 'type lustre' \
2500                                         \\\$lustre_mnt_count;
2501                                 rc=1;
2502                         fi;
2503                 fi;
2504         exit \\\$rc" || return ${PIPESTATUS[0]}
2505
2506                         i=$((i + 1))
2507                 done
2508         else
2509
2510                 local tmpopts=$opts
2511                 if $SHARED_KEY; then
2512                         tmpopts=$(add_sk_mntflag $opts)
2513                 fi
2514                 do_nodes $clients "
2515 running=\\\$(mount | grep -c $mnt' ');
2516 rc=0;
2517 if [ \\\$running -eq 0 ] ; then
2518         mkdir -p $mnt;
2519         $MOUNT_CMD $flags $tmpopts $device $mnt;
2520         rc=\\\$?;
2521 fi;
2522 exit \\\$rc" || return ${PIPESTATUS[0]}
2523         fi
2524
2525         echo "Started clients $clients: "
2526         do_nodes $clients "mount | grep $mnt' '"
2527
2528         set_default_debug_nodes $clients
2529
2530         return 0
2531 }
2532
2533 zconf_umount_clients() {
2534     local clients=$1
2535     local mnt=$2
2536     local force
2537
2538     [ "$3" ] && force=-f
2539
2540     echo "Stopping clients: $clients $mnt (opts:$force)"
2541     do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
2542 if [ \\\$running -ne 0 ] ; then
2543 echo Stopping client \\\$(hostname) $mnt opts:$force;
2544 lsof $mnt || need_kill=no;
2545 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
2546     pids=\\\$(lsof -t $mnt | sort -u);
2547     if [ -n \\\"\\\$pids\\\" ]; then
2548              kill -9 \\\$pids;
2549     fi
2550 fi;
2551 while umount $force $mnt 2>&1 | grep -q "busy"; do
2552     echo "$mnt is still busy, wait one second" && sleep 1;
2553 done;
2554 fi"
2555 }
2556
2557 shutdown_node () {
2558     local node=$1
2559     echo + $POWER_DOWN $node
2560     $POWER_DOWN $node
2561 }
2562
2563 shutdown_node_hard () {
2564     local host=$1
2565     local attempts=$SHUTDOWN_ATTEMPTS
2566
2567     for i in $(seq $attempts) ; do
2568         shutdown_node $host
2569         sleep 1
2570         wait_for_function --quiet "! ping -w 3 -c 1 $host" 5 1 && return 0
2571         echo "waiting for $host to fail attempts=$attempts"
2572         [ $i -lt $attempts ] || \
2573             { echo "$host still pingable after power down! attempts=$attempts" && return 1; }
2574     done
2575 }
2576
2577 shutdown_client() {
2578     local client=$1
2579     local mnt=${2:-$MOUNT}
2580     local attempts=3
2581
2582     if [ "$FAILURE_MODE" = HARD ]; then
2583         shutdown_node_hard $client
2584     else
2585        zconf_umount_clients $client $mnt -f
2586     fi
2587 }
2588
2589 facets_on_host () {
2590     local host=$1
2591     local facets="$(get_facets OST),$(get_facets MDS)"
2592     local affected
2593
2594     combined_mgs_mds || facets="$facets,mgs"
2595
2596     for facet in ${facets//,/ }; do
2597         if [ $(facet_active_host $facet) == $host ]; then
2598            affected="$affected $facet"
2599         fi
2600     done
2601
2602     echo $(comma_list $affected)
2603 }
2604
2605 facet_up() {
2606         local facet=$1
2607         local host=${2:-$(facet_host $facet)}
2608
2609         local label=$(convert_facet2label $facet)
2610         do_node $host $LCTL dl | awk '{ print $4 }' | grep -q "^$label\$"
2611 }
2612
2613 facets_up_on_host () {
2614     local host=$1
2615     local facets=$(facets_on_host $host)
2616     local affected_up
2617
2618     for facet in ${facets//,/ }; do
2619         if $(facet_up $facet $host); then
2620             affected_up="$affected_up $facet"
2621         fi
2622     done
2623
2624     echo $(comma_list $affected_up)
2625 }
2626
2627 shutdown_facet() {
2628         local facet=$1
2629         local affected_facet
2630         local affected_facets
2631
2632         if [[ "$FAILURE_MODE" = HARD ]]; then
2633                 if [[ $(facet_fstype $facet) = ldiskfs ]] &&
2634                         dm_flakey_supported $facet; then
2635                         affected_facets=$(affected_facets $facet)
2636                         for affected_facet in ${affected_facets//,/ }; do
2637                                 unexport_dm_dev $affected_facet
2638                         done
2639                 fi
2640
2641                 shutdown_node_hard $(facet_active_host $facet)
2642         else
2643                 stop $facet
2644         fi
2645 }
2646
2647 reboot_node() {
2648     local node=$1
2649     echo + $POWER_UP $node
2650     $POWER_UP $node
2651 }
2652
2653 remount_facet() {
2654     local facet=$1
2655
2656     stop $facet
2657     mount_facet $facet
2658 }
2659
2660 reboot_facet() {
2661         local facet=$1
2662         if [ "$FAILURE_MODE" = HARD ]; then
2663                 reboot_node $(facet_active_host $facet)
2664         else
2665                 sleep 10
2666         fi
2667 }
2668
2669 boot_node() {
2670     local node=$1
2671     if [ "$FAILURE_MODE" = HARD ]; then
2672        reboot_node $node
2673        wait_for_host $node
2674     fi
2675 }
2676
2677 facets_hosts () {
2678     local facets=$1
2679     local hosts
2680
2681     for facet in ${facets//,/ }; do
2682         hosts=$(expand_list $hosts $(facet_host $facet) )
2683     done
2684
2685     echo $hosts
2686 }
2687
2688 _check_progs_installed () {
2689     local progs=$@
2690     local rc=0
2691
2692     for prog in $progs; do
2693         if ! [ "$(which $prog)"  -o  "${!prog}" ]; then
2694            echo $prog missing on $(hostname)
2695            rc=1
2696         fi
2697     done
2698     return $rc
2699 }
2700
2701 check_progs_installed () {
2702         local nodes=$1
2703         shift
2704
2705         do_rpc_nodes "$nodes" _check_progs_installed $@
2706 }
2707
2708 # recovery-scale functions
2709 node_var_name() {
2710     echo __$(echo $1 | tr '-' '_' | tr '.' '_')
2711 }
2712
2713 start_client_load() {
2714         local client=$1
2715         local load=$2
2716         local var=$(node_var_name $client)_load
2717         eval export ${var}=$load
2718
2719         do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
2720                         BREAK_ON_ERROR=$BREAK_ON_ERROR \
2721                         END_RUN_FILE=$END_RUN_FILE \
2722                         LOAD_PID_FILE=$LOAD_PID_FILE \
2723                         TESTLOG_PREFIX=$TESTLOG_PREFIX \
2724                         TESTNAME=$TESTNAME \
2725                         DBENCH_LIB=$DBENCH_LIB \
2726                         DBENCH_SRC=$DBENCH_SRC \
2727                         CLIENT_COUNT=$((CLIENTCOUNT - 1)) \
2728                         LFS=$LFS \
2729                         LCTL=$LCTL \
2730                         FSNAME=$FSNAME \
2731                         MPIRUN=$MPIRUN \
2732                         MPIRUN_OPTIONS=\\\"$MPIRUN_OPTIONS\\\" \
2733                         MACHINEFILE_OPTION=\\\"$MACHINEFILE_OPTION\\\" \
2734                         num_clients=$(get_node_count ${CLIENTS//,/ }) \
2735                         ior_THREADS=$ior_THREADS ior_iteration=$ior_iteration \
2736                         ior_blockSize=$ior_blockSize \
2737                         ior_blockUnit=$ior_blockUnit \
2738                         ior_xferSize=$ior_xferSize ior_type=$ior_type \
2739                         ior_DURATION=$ior_DURATION \
2740                         ior_stripe_params=\\\"$ior_stripe_params\\\" \
2741                         ior_custom_params=\\\"$ior_custom_param\\\" \
2742                         mpi_ior_custom_threads=$mpi_ior_custom_threads \
2743                         run_${load}.sh" &
2744         local ppid=$!
2745         log "Started client load: ${load} on $client"
2746
2747         # get the children process IDs
2748         local pids=$(ps --ppid $ppid -o pid= | xargs)
2749         CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $ppid $pids"
2750         return 0
2751 }
2752
2753 start_client_loads () {
2754         local -a clients=(${1//,/ })
2755         local numloads=${#CLIENT_LOADS[@]}
2756
2757         for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
2758                 local load=$((nodenum % numloads))
2759                 start_client_load ${clients[nodenum]} ${CLIENT_LOADS[load]}
2760         done
2761         # bug 22169: wait the background threads to start
2762         sleep 2
2763 }
2764
2765 # only for remote client
2766 check_client_load () {
2767         local client=$1
2768         local var=$(node_var_name $client)_load
2769         local testload=run_${!var}.sh
2770
2771         ps auxww | grep -v grep | grep $client | grep -q $testload || return 1
2772
2773         # bug 18914: try to connect several times not only when
2774         # check ps, but  while check_node_health also
2775
2776         local tries=3
2777         local RC=254
2778         while [ $RC = 254 -a $tries -gt 0 ]; do
2779                 let tries=$tries-1
2780                 # assume success
2781                 RC=0
2782                 if ! check_node_health $client; then
2783                         RC=${PIPESTATUS[0]}
2784                         if [ $RC -eq 254 ]; then
2785                                 # FIXME: not sure how long we shuold sleep here
2786                                 sleep 10
2787                                 continue
2788                         fi
2789                         echo "check node health failed: RC=$RC "
2790                         return $RC
2791                 fi
2792         done
2793         # We can continue try to connect if RC=254
2794         # Just print the warning about this
2795         if [ $RC = 254 ]; then
2796                 echo "got a return status of $RC from do_node while checking " \
2797                 "node health on $client"
2798         fi
2799
2800         # see if the load is still on the client
2801         tries=3
2802         RC=254
2803         while [ $RC = 254 -a $tries -gt 0 ]; do
2804                 let tries=$tries-1
2805                 # assume success
2806                 RC=0
2807                 if ! do_node $client \
2808                         "ps auxwww | grep -v grep | grep -q $testload"; then
2809                         RC=${PIPESTATUS[0]}
2810                         sleep 30
2811                 fi
2812         done
2813         if [ $RC = 254 ]; then
2814                 echo "got a return status of $RC from do_node while checking " \
2815                 "(node health and 'ps') the client load on $client"
2816                 # see if we can diagnose a bit why this is
2817         fi
2818
2819         return $RC
2820 }
2821 check_client_loads () {
2822    local clients=${1//,/ }
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 ]; then
2830         log "Client load failed on node $client, rc=$rc"
2831         return $rc
2832       fi
2833    done
2834 }
2835
2836 restart_client_loads () {
2837     local clients=${1//,/ }
2838     local expectedfail=${2:-""}
2839     local client=
2840     local rc=0
2841
2842     for client in $clients; do
2843         check_client_load $client
2844         rc=${PIPESTATUS[0]}
2845         if [ "$rc" != 0 -a "$expectedfail" ]; then
2846             local var=$(node_var_name $client)_load
2847             start_client_load $client ${!var}
2848             echo "Restarted client load ${!var}: on $client. Checking ..."
2849             check_client_load $client
2850             rc=${PIPESTATUS[0]}
2851             if [ "$rc" != 0 ]; then
2852                 log "Client load failed to restart on node $client, rc=$rc"
2853                 # failure one client load means test fail
2854                 # we do not need to check other
2855                 return $rc
2856             fi
2857         else
2858             return $rc
2859         fi
2860     done
2861 }
2862
2863 # Start vmstat and save its process ID in a file.
2864 start_vmstat() {
2865     local nodes=$1
2866     local pid_file=$2
2867
2868     [ -z "$nodes" -o -z "$pid_file" ] && return 0
2869
2870     do_nodes $nodes \
2871         "vmstat 1 > $TESTLOG_PREFIX.$TESTNAME.vmstat.\\\$(hostname -s).log \
2872         2>/dev/null </dev/null & echo \\\$! > $pid_file"
2873 }
2874
2875 # Display the nodes on which client loads failed.
2876 print_end_run_file() {
2877     local file=$1
2878     local node
2879
2880     [ -s $file ] || return 0
2881
2882     echo "Found the END_RUN_FILE file: $file"
2883     cat $file
2884
2885     # A client load will stop if it finds the END_RUN_FILE file.
2886     # That does not mean the client load actually failed though.
2887     # The first node in END_RUN_FILE is the one we are interested in.
2888     read node < $file
2889
2890     if [ -n "$node" ]; then
2891         local var=$(node_var_name $node)_load
2892
2893         local prefix=$TESTLOG_PREFIX
2894         [ -n "$TESTNAME" ] && prefix=$prefix.$TESTNAME
2895         local stdout_log=$prefix.run_${!var}_stdout.$node.log
2896         local debug_log=$(echo $stdout_log | sed 's/\(.*\)stdout/\1debug/')
2897
2898         echo "Client load ${!var} failed on node $node:"
2899         echo "$stdout_log"
2900         echo "$debug_log"
2901     fi
2902 }
2903
2904 # Stop the process which had its PID saved in a file.
2905 stop_process() {
2906     local nodes=$1
2907     local pid_file=$2
2908
2909     [ -z "$nodes" -o -z "$pid_file" ] && return 0
2910
2911     do_nodes $nodes "test -f $pid_file &&
2912         { kill -s TERM \\\$(cat $pid_file); rm -f $pid_file; }" || true
2913 }
2914
2915 # Stop all client loads.
2916 stop_client_loads() {
2917     local nodes=${1:-$CLIENTS}
2918     local pid_file=$2
2919
2920     # stop the client loads
2921     stop_process $nodes $pid_file
2922
2923     # clean up the processes that started them
2924     [ -n "$CLIENT_LOAD_PIDS" ] && kill -9 $CLIENT_LOAD_PIDS 2>/dev/null || true
2925 }
2926 # End recovery-scale functions
2927
2928 # verify that lustre actually cleaned up properly
2929 cleanup_check() {
2930         VAR=$(lctl get_param -n catastrophe 2>&1)
2931         if [ $? = 0 ] ; then
2932                 if [ $VAR != 0 ]; then
2933                         error "LBUG/LASSERT detected"
2934                 fi
2935         fi
2936         BUSY=$(dmesg | grep -i destruct || true)
2937         if [ -n "$BUSY" ]; then
2938                 echo "$BUSY" 1>&2
2939                 [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.$(date +%s)
2940                 exit 205
2941         fi
2942
2943         check_mem_leak || exit 204
2944
2945         [[ $($LCTL dl 2>/dev/null | wc -l) -gt 0 ]] && $LCTL dl &&
2946                 echo "$TESTSUITE: lustre didn't clean up..." 1>&2 &&
2947                 return 202 || true
2948
2949         if module_loaded lnet || module_loaded libcfs; then
2950                 echo "$TESTSUITE: modules still loaded..." 1>&2
2951                 /sbin/lsmod 1>&2
2952                 return 203
2953         fi
2954         return 0
2955 }
2956
2957 wait_update () {
2958         local verbose=false
2959         if [[ "$1" == "--verbose" ]]; then
2960                 shift
2961                 verbose=true
2962         fi
2963
2964         local node=$1
2965         local TEST=$2
2966         local FINAL=$3
2967         local MAX=${4:-90}
2968         local RESULT
2969         local PREV_RESULT
2970         local WAIT=0
2971         local sleep=1
2972         local print=10
2973
2974         PREV_RESULT=$(do_node $node "$TEST")
2975         while [ true ]; do
2976                 RESULT=$(do_node $node "$TEST")
2977                 if [[ "$RESULT" == "$FINAL" ]]; then
2978                         [[ -z "$RESULT" || $WAIT -le $sleep ]] ||
2979                                 echo "Updated after ${WAIT}s: wanted '$FINAL'"\
2980                                      "got '$RESULT'"
2981                         return 0
2982                 fi
2983                 if [[ $verbose && "$RESULT" != "$PREV_RESULT" ]]; then
2984                         echo "Changed after ${WAIT}s: from '$PREV_RESULT'"\
2985                              "to '$RESULT'"
2986                         PREV_RESULT=$RESULT
2987                 fi
2988                 [[ $WAIT -ge $MAX ]] && break
2989                 [[ $((WAIT % print)) -eq 0 ]] &&
2990                         echo "Waiting $((MAX - WAIT)) secs for update"
2991                 WAIT=$((WAIT + sleep))
2992                 sleep $sleep
2993         done
2994         echo "Update not seen after ${MAX}s: wanted '$FINAL' got '$RESULT'"
2995         return 3
2996 }
2997
2998 wait_update_facet() {
2999         local verbose=
3000         [ "$1" = "--verbose" ] && verbose="$1" && shift
3001
3002         local facet=$1
3003         shift
3004         wait_update $verbose $(facet_active_host $facet) "$@"
3005 }
3006
3007 sync_all_data() {
3008         do_nodes $(comma_list $(mdts_nodes)) \
3009             "lctl set_param -n os[cd]*.*MDT*.force_sync=1"
3010         do_nodes $(comma_list $(osts_nodes)) \
3011             "lctl set_param -n osd*.*OS*.force_sync=1" 2>&1 |
3012                 grep -v 'Found no match'
3013 }
3014
3015 wait_zfs_commit() {
3016         local zfs_wait=${2:-5}
3017
3018         # the occupied disk space will be released
3019         # only after TXGs are committed
3020         if [[ $(facet_fstype $1) == zfs ]]; then
3021                 echo "sleep $zfs_wait for ZFS $(facet_fstype $1)"
3022                 sleep $zfs_wait
3023         fi
3024 }
3025
3026 fill_ost() {
3027         local filename=$1
3028         local ost_idx=$2
3029         local lwm=$3  #low watermark
3030         local size_mb #how many MB should we write to pass watermark
3031         local ost_name=$(ostname_from_index $ost_idx)
3032
3033         free_kb=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
3034         size_mb=0
3035         if (( $free_kb / 1024 > lwm )); then
3036                 size_mb=$((free_kb / 1024 - lwm))
3037         fi
3038         #If 10% of free space cross low watermark use it
3039         if (( $free_kb / 10240 > size_mb )); then
3040                 size_mb=$((free_kb / 10240))
3041         else
3042                 #At least we need to store 1.1 of difference between
3043                 #free space and low watermark
3044                 size_mb=$((size_mb + size_mb / 10))
3045         fi
3046         if (( lwm <= $free_kb / 1024 )) ||
3047            [ ! -f $DIR/${filename}.fill_ost$ost_idx ]; then
3048                 $LFS setstripe -i $ost_idx -c1 $DIR/${filename}.fill_ost$ost_idx
3049                 dd if=/dev/zero of=$DIR/${filename}.fill_ost$ost_idx bs=1M \
3050                         count=$size_mb oflag=append conv=notrunc
3051         fi
3052
3053         sleep_maxage
3054
3055         free_kb=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
3056         echo "OST still has $((free_kb / 1024)) MB free"
3057 }
3058
3059 # This checks only the primary MDS
3060 ost_watermarks_get() {
3061         local ost_idx=$1
3062         local ost_name=$(ostname_from_index $ost_idx)
3063         local mdtosc_proc=$(get_mdtosc_proc_path $SINGLEMDS $ost_name)
3064
3065         local hwm=$(do_facet $SINGLEMDS $LCTL get_param -n \
3066                         osp.$mdtosc_proc.reserved_mb_high)
3067         local lwm=$(do_facet $SINGLEMDS $LCTL get_param -n \
3068                         osp.$mdtosc_proc.reserved_mb_low)
3069
3070         echo "$lwm $hwm"
3071 }
3072
3073 # Note that we set watermarks on all MDSes (necessary for striped dirs)
3074 ost_watermarks_set() {
3075         local ost_idx=$1
3076         local lwm=$2
3077         local hwm=$3
3078         local ost_name=$(ostname_from_index $ost_idx)
3079         local facets=$(get_facets MDS)
3080
3081         do_nodes $(comma_list $(mdts_nodes)) $LCTL set_param -n \
3082                 osp.*$ost_name*.reserved_mb_low=$lwm \
3083                 osp.*$ost_name*.reserved_mb_high=$hwm > /dev/null
3084
3085         # sleep to ensure we see the change
3086         sleep_maxage
3087 }
3088
3089 ost_watermarks_set_low_space() {
3090         local ost_idx=$1
3091         local wms=$(ost_watermarks_get $ost_idx)
3092         local ost_name=$(ostname_from_index $ost_idx)
3093
3094         local old_lwm=$(echo $wms | awk '{ print $1 }')
3095         local old_hwm=$(echo $wms | awk '{ print $2 }')
3096
3097         local blocks=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
3098         # minimal extension size is 64M
3099         local new_lwm=50
3100         if (( $blocks / 1024 > 50 )); then
3101                 new_lwm=$((blocks / 1024 - 50))
3102         fi
3103         local new_hwm=$((new_lwm + 5))
3104
3105         ost_watermarks_set $ost_idx $new_lwm $new_hwm
3106         echo "watermarks: $old_lwm $old_hwm $new_lwm $new_hwm"
3107 }
3108
3109 # Set watermarks to ~current available space & then write data to fill it
3110 # Note OST is not *actually* full after this, it just reports ENOSPC in the
3111 # internal statfs used by the stripe allocator
3112 #
3113 # first parameter is the filename-prefix, which must get under t-f cleanup
3114 # requirements (rm -rf $DIR/[Rdfs][0-9]*), i.e. $tfile work fine
3115 ost_watermarks_set_enospc() {
3116         local filename=$1
3117         local ost_idx=$2
3118         # on the mdt's osc
3119         local ost_name=$(ostname_from_index $ost_idx)
3120         local facets=$(get_facets MDS)
3121         local wms
3122         local MDS
3123
3124         for MDS in ${facets//,/ }; do
3125                 local mdtosc_proc=$(get_mdtosc_proc_path $MDS $ost_name)
3126
3127                 do_facet $MDS $LCTL get_param -n \
3128                         osp.$mdtosc_proc.reserved_mb_high ||
3129                         skip  "remote MDS does not support reserved_mb_high"
3130         done
3131
3132         wms=$(ost_watermarks_set_low_space $ost_idx)
3133         local new_lwm=$(echo $wms | awk '{ print $4 }')
3134         fill_ost $filename $ost_idx $new_lwm
3135         #First enospc could execute orphan deletion so repeat
3136         fill_ost $filename $ost_idx $new_lwm
3137         echo $wms
3138 }
3139
3140 ost_watermarks_enospc_delete_files() {
3141         local filename=$1
3142         local ost_idx=$2
3143
3144         rm -f $DIR/${filename}.fill_ost$ost_idx
3145
3146         wait_delete_completed
3147         wait_mds_ost_sync
3148 }
3149
3150 # clean up from "ost_watermarks_set_enospc"
3151 ost_watermarks_clear_enospc() {
3152         local filename=$1
3153         local ost_idx=$2
3154         local old_lwm=$4
3155         local old_hwm=$5
3156
3157         ost_watermarks_enospc_delete_files $filename $ost_idx
3158         ost_watermarks_set $ost_idx $old_lwm $old_hwm
3159         echo "set OST$ost_idx lwm back to $old_lwm, hwm back to $old_hwm"
3160 }
3161
3162 wait_delete_completed_mds() {
3163         local max_wait=${1:-20}
3164         local mds2sync=""
3165         local stime=$(date +%s)
3166         local etime
3167         local node
3168         local changes
3169
3170         # find MDS with pending deletions
3171         for node in $(mdts_nodes); do
3172                 changes=$(do_node $node "$LCTL get_param -n osc.*MDT*.sync_*" \
3173                         2>/dev/null | calc_sum)
3174                 if [[ $changes -eq 0 ]]; then
3175                         continue
3176                 fi
3177                 mds2sync="$mds2sync $node"
3178         done
3179         if [ -z "$mds2sync" ]; then
3180                 wait_zfs_commit $SINGLEMDS
3181                 return 0
3182         fi
3183         mds2sync=$(comma_list $mds2sync)
3184
3185         # sync MDS transactions
3186         do_nodes $mds2sync "$LCTL set_param -n os[cd]*.*MD*.force_sync 1"
3187
3188         # wait till all changes are sent and commmitted by OSTs
3189         # for ldiskfs space is released upon execution, but DMU
3190         # do this upon commit
3191
3192         local WAIT=0
3193         while [[ $WAIT -ne $max_wait ]]; do
3194                 changes=$(do_nodes $mds2sync \
3195                         "$LCTL get_param -n osc.*MDT*.sync_*" | calc_sum)
3196                 #echo "$node: $changes changes on all"
3197                 if [[ $changes -eq 0 ]]; then
3198                         wait_zfs_commit $SINGLEMDS
3199
3200                         # the occupied disk space will be released
3201                         # only after TXGs are committed
3202                         wait_zfs_commit ost1
3203                         return 0
3204                 fi
3205                 sleep 1
3206                 WAIT=$((WAIT + 1))
3207         done
3208
3209         etime=$(date +%s)
3210         echo "Delete is not completed in $((etime - stime)) seconds"
3211         do_nodes $mds2sync "$LCTL get_param osc.*MDT*.sync_*"
3212         return 1
3213 }
3214
3215 wait_for_host() {
3216     local hostlist=$1
3217
3218     # we can use "for" here because we are waiting the slowest
3219     for host in ${hostlist//,/ }; do
3220         check_network "$host" 900
3221     done
3222     while ! do_nodes $hostlist hostname  > /dev/null; do sleep 5; done
3223 }
3224
3225 wait_for_facet() {
3226     local facetlist=$1
3227     local hostlist
3228
3229     for facet in ${facetlist//,/ }; do
3230         hostlist=$(expand_list $hostlist $(facet_active_host $facet))
3231     done
3232     wait_for_host $hostlist
3233 }
3234
3235 _wait_recovery_complete () {
3236     local param=$1
3237
3238     # Use default policy if $2 is not passed by caller.
3239     local MAX=${2:-$(max_recovery_time)}
3240
3241     local WAIT=0
3242     local STATUS=
3243
3244     while [ $WAIT -lt $MAX ]; do
3245         STATUS=$(lctl get_param -n $param | grep status)
3246         echo $param $STATUS
3247         [[ $STATUS = "status: COMPLETE" || $STATUS = "status: INACTIVE" ]] && return 0
3248         sleep 5
3249         WAIT=$((WAIT + 5))
3250         echo "Waiting $((MAX - WAIT)) secs for $param recovery done. $STATUS"
3251     done
3252     echo "$param recovery not done in $MAX sec. $STATUS"
3253     return 1
3254 }
3255
3256 wait_recovery_complete () {
3257     local facet=$1
3258
3259     # with an assumption that at_max is the same on all nodes
3260     local MAX=${2:-$(max_recovery_time)}
3261
3262     local facets=$facet
3263     if [ "$FAILURE_MODE" = HARD ]; then
3264         facets=$(facets_on_host $(facet_active_host $facet))
3265     fi
3266     echo affected facets: $facets
3267
3268         # we can use "for" here because we are waiting the slowest
3269         for facet in ${facets//,/ }; do
3270                 local var_svc=${facet}_svc
3271                 local param="*.${!var_svc}.recovery_status"
3272
3273                 local host=$(facet_active_host $facet)
3274                 do_rpc_nodes "$host" _wait_recovery_complete $param $MAX
3275         done
3276 }
3277
3278 wait_mds_ost_sync () {
3279         # just because recovery is done doesn't mean we've finished
3280         # orphan cleanup. Wait for llogs to get synchronized.
3281         echo "Waiting for orphan cleanup..."
3282         # MAX value includes time needed for MDS-OST reconnection
3283         local MAX=$(( TIMEOUT * 2 ))
3284         local WAIT_TIMEOUT=${1:-$MAX}
3285         local WAIT=0
3286         local new_wait=true
3287         local list=$(comma_list $(mdts_nodes))
3288         local cmd="$LCTL get_param -n osp.*osc*.old_sync_processed"
3289         if ! do_facet $SINGLEMDS \
3290                 "$LCTL list_param osp.*osc*.old_sync_processed 2> /dev/null"
3291         then
3292                 # old way, use mds_sync
3293                 new_wait=false
3294                 list=$(comma_list $(osts_nodes))
3295                 cmd="$LCTL get_param -n obdfilter.*.mds_sync"
3296         fi
3297
3298         echo "wait $WAIT_TIMEOUT secs maximumly for $list mds-ost sync done."
3299         while [ $WAIT -lt $WAIT_TIMEOUT ]; do
3300                 local -a sync=($(do_nodes $list "$cmd"))
3301                 local con=1
3302                 local i
3303                 for ((i=0; i<${#sync[@]}; i++)); do
3304                         if $new_wait; then
3305                                 [ ${sync[$i]} -eq 1 ] && continue
3306                         else
3307                                 [ ${sync[$i]} -eq 0 ] && continue
3308                         fi
3309                         # there is a not finished MDS-OST synchronization
3310                         con=0
3311                         break;
3312                 done
3313                 sleep 2 # increase waiting time and cover statfs cache
3314                 [ ${con} -eq 1 ] && return 0
3315                 echo "Waiting $WAIT secs for $list $i mds-ost sync done."
3316                 WAIT=$((WAIT + 2))
3317         done
3318
3319         # show which nodes are not finished.
3320         cmd=$(echo $cmd | sed 's/-n//')
3321         do_nodes $list "$cmd"
3322         echo "$facet recovery node $i not done in $WAIT_TIMEOUT sec. $STATUS"
3323         return 1
3324 }
3325
3326 # Wait OSTs to be active on both client and MDT side.
3327 wait_osts_up() {
3328         local cmd="$LCTL get_param -n lov.$FSNAME-clilov-*.target_obd |
3329                 awk 'BEGIN {c = 0} /ACTIVE/{c += 1} END {printf \\\"%d\\\", c}'"
3330         wait_update $HOSTNAME "eval $cmd" $OSTCOUNT ||
3331                 error "wait_update OSTs up on client failed"
3332
3333         cmd="$LCTL get_param osp.$FSNAME-OST*-MDT0000.prealloc_last_id |
3334              awk '/=[1-9][0-9]/ { c += 1 } END { printf \\\"%d\\\", c }'"
3335         wait_update_facet $SINGLEMDS "eval $cmd" $OSTCOUNT ||
3336                 error "wait_update OSTs up on MDT0000 failed"
3337 }
3338
3339 wait_destroy_complete () {
3340         echo "Waiting for local destroys to complete"
3341         # MAX value shouldn't be big as this mean server responsiveness
3342         # never increase this just to make test pass but investigate
3343         # why it takes so long time
3344         local MAX=5
3345         local WAIT=0
3346         while [ $WAIT -lt $MAX ]; do
3347                 local -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))
3348                 local con=1
3349                 local i
3350
3351                 for ((i=0; i<${#RPCs[@]}; i++)); do
3352                         [ ${RPCs[$i]} -eq 0 ] && continue
3353                         # there are still some destroy RPCs in flight
3354                         con=0
3355                         break;
3356                 done
3357                 sleep 1
3358                 [ ${con} -eq 1 ] && return 0 # done waiting
3359                 echo "Waiting ${WAIT}s for local destroys to complete"
3360                 WAIT=$((WAIT + 1))
3361         done
3362         echo "Local destroys weren't done in $MAX sec."
3363         return 1
3364 }
3365
3366 wait_delete_completed() {
3367         wait_delete_completed_mds $1 || return $?
3368         wait_destroy_complete || return $?
3369 }
3370
3371 wait_exit_ST () {
3372     local facet=$1
3373
3374     local WAIT=0
3375     local INTERVAL=1
3376     local running
3377     # conf-sanity 31 takes a long time cleanup
3378     while [ $WAIT -lt 300 ]; do
3379         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null &&
3380 lctl dl | grep ' ST ' || true")
3381         [ -z "${running}" ] && return 0
3382         echo "waited $WAIT for${running}"
3383         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
3384         sleep $INTERVAL
3385         WAIT=$((WAIT + INTERVAL))
3386     done
3387     echo "service didn't stop after $WAIT seconds.  Still running:"
3388     echo ${running}
3389     return 1
3390 }
3391
3392 wait_remote_prog () {
3393    local prog=$1
3394    local WAIT=0
3395    local INTERVAL=5
3396    local rc=0
3397
3398    [ "$PDSH" = "no_dsh" ] && return 0
3399
3400    while [ $WAIT -lt $2 ]; do
3401         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
3402         [ -z "${running}" ] && return 0 || true
3403         echo "waited $WAIT for: "
3404         echo "$running"
3405         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
3406         sleep $INTERVAL
3407         WAIT=$((WAIT + INTERVAL))
3408     done
3409     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
3410     [ -z "$pids" ] && return 0
3411     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
3412     # FIXME: not portable
3413     for pid in $pids; do
3414         cat /proc/${pid}/status || true
3415         cat /proc/${pid}/wchan || true
3416         echo "Killing $pid"
3417         kill -9 $pid || true
3418         sleep 1
3419         ps -P $pid && rc=1
3420     done
3421
3422     return $rc
3423 }
3424
3425 lfs_df_check() {
3426         local clients=${1:-$CLIENTS}
3427
3428         if [ -z "$clients" ]; then
3429                 $LFS df $MOUNT
3430         else
3431                 $PDSH $clients "$LFS df $MOUNT" > /dev/null
3432         fi
3433 }
3434
3435 clients_up() {
3436         # not every config has many clients
3437         sleep 1
3438         lfs_df_check
3439 }
3440
3441 client_up() {
3442         # usually checked on particular client or locally
3443         sleep 1
3444         lfs_df_check $1
3445 }
3446
3447 client_evicted() {
3448     ! client_up $1
3449 }
3450
3451 client_reconnect_try() {
3452         local f=$MOUNT/recon
3453
3454         uname -n >> $f
3455         if [ -z "$CLIENTS" ]; then
3456                 $LFS df $MOUNT; uname -n >> $f
3457         else
3458                 do_nodes $CLIENTS "$LFS df $MOUNT; uname -n >> $f" > /dev/null
3459         fi
3460         echo "Connected clients: $(cat $f)"
3461         ls -l $f > /dev/null
3462         rm $f
3463 }
3464
3465 client_reconnect() {
3466         # one client_reconnect_try call does not always do the job...
3467         while true ; do
3468                 client_reconnect_try && break
3469                 sleep 1
3470         done
3471 }
3472
3473 affected_facets () {
3474     local facet=$1
3475
3476     local host=$(facet_active_host $facet)
3477     local affected=$facet
3478
3479     if [ "$FAILURE_MODE" = HARD ]; then
3480         affected=$(facets_up_on_host $host)
3481     fi
3482     echo $affected
3483 }
3484
3485 facet_failover() {
3486         local E2FSCK_ON_MDT0=false
3487         if [ "$1" == "--fsck" ]; then
3488                 shift
3489                 [ $(facet_fstype $SINGLEMDS) == ldiskfs ] &&
3490                         E2FSCK_ON_MDT0=true
3491         fi
3492
3493         local facets=$1
3494         local sleep_time=$2
3495         local -a affecteds
3496         local facet
3497         local total=0
3498         local index=0
3499         local skip
3500
3501         #Because it will only get up facets, we need get affected
3502         #facets before shutdown
3503         #For HARD Failure mode, it needs make sure facets on the same
3504         #HOST will only be shutdown and reboot once
3505         for facet in ${facets//,/ }; do
3506                 local affected_facet
3507                 skip=0
3508                 #check whether facet has been included in other affected facets
3509                 for ((index=0; index<$total; index++)); do
3510                         [[ *,$facet,* == ,${affecteds[index]}, ]] && skip=1
3511                 done
3512
3513                 if [ $skip -eq 0 ]; then
3514                         affecteds[$total]=$(affected_facets $facet)
3515                         total=$((total+1))
3516                 fi
3517         done
3518
3519         for ((index=0; index<$total; index++)); do
3520                 facet=$(echo ${affecteds[index]} | tr -s " " | cut -d"," -f 1)
3521                 local host=$(facet_active_host $facet)
3522                 echo "Failing ${affecteds[index]} on $host"
3523                 shutdown_facet $facet
3524         done
3525
3526         $E2FSCK_ON_MDT0 && (run_e2fsck $(facet_active_host $SINGLEMDS) \
3527                 $(mdsdevname 1) "-n" || error "Running e2fsck")
3528
3529         for ((index=0; index<$total; index++)); do
3530                 facet=$(echo ${affecteds[index]} | tr -s " " | cut -d"," -f 1)
3531                 echo reboot facets: ${affecteds[index]}
3532
3533                 reboot_facet $facet
3534
3535                 change_active ${affecteds[index]}
3536
3537                 wait_for_facet ${affecteds[index]}
3538                 if $GSS_SK; then
3539                         init_gss
3540                         init_facets_vars_simple
3541                 fi
3542                 # start mgs first if it is affected
3543                 if ! combined_mgs_mds &&
3544                         list_member ${affecteds[index]} mgs; then
3545                         mount_facet mgs || error "Restart of mgs failed"
3546                 fi
3547                 # FIXME; has to be changed to mount all facets concurrently
3548                 affected=$(exclude_items_from_list ${affecteds[index]} mgs)
3549                 echo mount facets: ${affecteds[index]}
3550                 mount_facets ${affecteds[index]}
3551                 if $GSS_SK; then
3552                         do_nodes $(comma_list $(all_nodes)) \
3553                                 "keyctl show | grep lustre | cut -c1-11 |
3554                                 sed -e 's/ //g;' |
3555                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
3556                 fi
3557         done
3558 }
3559
3560 obd_name() {
3561     local facet=$1
3562 }
3563
3564 replay_barrier() {
3565         local facet=$1
3566         do_facet $facet "sync; sync; sync"
3567         $LFS df $MOUNT
3568
3569         # make sure there will be no seq change
3570         local clients=${CLIENTS:-$HOSTNAME}
3571         local f=fsa-\\\$\(hostname\)
3572         do_nodes $clients "mcreate $MOUNT/$f; rm $MOUNT/$f"
3573         do_nodes $clients "if [ -d $MOUNT2 ]; then mcreate $MOUNT2/$f; rm $MOUNT2/$f; fi"
3574
3575         local svc=${facet}_svc
3576         do_facet $facet $LCTL --device ${!svc} notransno
3577         #
3578         # If a ZFS OSD is made read-only here, its pool is "freezed". This
3579         # in-memory state has to be cleared by either rebooting the host or
3580         # exporting and reimporting the pool.
3581         #
3582         # Although the uberblocks are not updated when a pool is freezed,
3583         # transactions are still written to the disks. Modified blocks may be
3584         # cached in memory when tests try reading them back. The
3585         # export-and-reimport process also evicts any cached pool data from
3586         # memory to provide the correct "data loss" semantics.
3587         #
3588         # In the test framework, the exporting and importing operations are
3589         # handled by stop() and mount_facet() separately, which are used
3590         # inside fail() and fail_abort().
3591         #
3592         set_dev_readonly $facet
3593         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
3594         $LCTL mark "local REPLAY BARRIER on ${!svc}"
3595 }
3596
3597 replay_barrier_nodf() {
3598         local facet=$1    echo running=${running}
3599         do_facet $facet "sync; sync; sync"
3600         local svc=${facet}_svc
3601         echo Replay barrier on ${!svc}
3602         do_facet $facet $LCTL --device ${!svc} notransno
3603         set_dev_readonly $facet
3604         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
3605         $LCTL mark "local REPLAY BARRIER on ${!svc}"
3606 }
3607
3608 replay_barrier_nosync() {
3609         local facet=$1    echo running=${running}
3610         local svc=${facet}_svc
3611         echo Replay barrier on ${!svc}
3612         do_facet $facet $LCTL --device ${!svc} notransno
3613         set_dev_readonly $facet
3614         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
3615         $LCTL mark "local REPLAY BARRIER on ${!svc}"
3616 }
3617
3618 #
3619 # Get Lustre client uuid for a given Lustre mount point.
3620 #
3621 get_client_uuid() {
3622         local mntpnt=${1:-$MOUNT}
3623
3624         local name=$($LFS getname $mntpnt | cut -d' ' -f1)
3625         local uuid=$($LCTL get_param -n llite.$name.uuid)
3626
3627         echo -n $uuid
3628 }
3629
3630 mds_evict_client() {
3631         local mntpnt=${1:-$MOUNT}
3632         local uuid=$(get_client_uuid $mntpnt)
3633
3634         do_facet $SINGLEMDS \
3635                 "$LCTL set_param -n mdt.${mds1_svc}.evict_client $uuid"
3636 }
3637
3638 ost_evict_client() {
3639         local mntpnt=${1:-$MOUNT}
3640         local uuid=$(get_client_uuid $mntpnt)
3641
3642         do_facet ost1 \
3643                 "$LCTL set_param -n obdfilter.${ost1_svc}.evict_client $uuid"
3644 }
3645
3646 fail() {
3647         local facets=$1
3648         local clients=${CLIENTS:-$HOSTNAME}
3649
3650         SK_NO_KEY_save=$SK_NO_KEY
3651         if $GSS_SK; then
3652                 export SK_NO_KEY=false
3653         fi
3654         facet_failover $* || error "failover: $?"
3655         export SK_NO_KEY=$SK_NO_KEY_save
3656         # to initiate all OSC idling connections
3657         clients_up
3658         wait_clients_import_state "$clients" "$facets" "\(FULL\|IDLE\)"
3659         clients_up || error "post-failover stat: $?"
3660 }
3661
3662 fail_nodf() {
3663         local facet=$1
3664         facet_failover $facet
3665 }
3666
3667 fail_abort() {
3668         local facet=$1
3669         stop $facet
3670         change_active $facet
3671         wait_for_facet $facet
3672         mount_facet $facet -o abort_recovery
3673         clients_up || echo "first stat failed: $?"
3674         clients_up || error "post-failover stat: $?"
3675 }
3676
3677 host_nids_address() {
3678         local nodes=$1
3679         local net=${2:-"."}
3680
3681         do_nodes $nodes "$LCTL list_nids | grep $net | cut -f 1 -d @"
3682 }
3683
3684 h2name_or_ip() {
3685         if [ "$1" = "'*'" ]; then echo \'*\'; else
3686                 echo $1"@$2"
3687         fi
3688 }
3689
3690 h2nettype() {
3691         if [[ -n "$NETTYPE" ]]; then
3692                 h2name_or_ip "$1" "$NETTYPE"
3693         else
3694                 h2name_or_ip "$1" "$2"
3695         fi
3696 }
3697 declare -fx h2nettype
3698
3699 # Wrapper function to print the deprecation warning
3700 h2tcp() {
3701         echo "h2tcp: deprecated, use h2nettype instead" 1>&2
3702         if [[ -n "$NETTYPE" ]]; then
3703                 h2nettype "$@"
3704         else
3705                 h2nettype "$1" "tcp"
3706         fi
3707 }
3708
3709 # Wrapper function to print the deprecation warning
3710 h2o2ib() {
3711         echo "h2o2ib: deprecated, use h2nettype instead" 1>&2
3712         if [[ -n "$NETTYPE" ]]; then
3713                 h2nettype "$@"
3714         else
3715                 h2nettype "$1" "o2ib"
3716         fi
3717 }
3718
3719 # This enables variables in cfg/"setup".sh files to support the pdsh HOSTLIST
3720 # expressions format. As a bonus we can then just pass in those variables
3721 # to pdsh. What this function does is take a HOSTLIST type string and
3722 # expand it into a space deliminated list for us.
3723 hostlist_expand() {
3724     local hostlist=$1
3725     local offset=$2
3726     local myList
3727     local item
3728     local list
3729
3730     [ -z "$hostlist" ] && return
3731
3732     # Translate the case of [..],..,[..] to [..] .. [..]
3733     list="${hostlist/],/] }"
3734     front=${list%%[*}
3735     [[ "$front" == *,* ]] && {
3736         new="${list%,*} "
3737         old="${list%,*},"
3738         list=${list/${old}/${new}}
3739     }
3740
3741     for item in $list; do
3742         # Test if we have any []'s at all
3743         if [ "$item" != "${item/\[/}" ]; then {
3744             # Expand the [*] into list
3745             name=${item%%[*}
3746             back=${item#*]}
3747
3748             if [ "$name" != "$item" ]; then
3749                 group=${item#$name[*}
3750                 group=${group%%]*}
3751
3752                 for range in ${group//,/ }; do
3753                     local order
3754
3755                     begin=${range%-*}
3756                     end=${range#*-}
3757
3758                     # Number of leading zeros
3759                     padlen=${#begin}
3760                     padlen2=${#end}
3761                     end=$(echo $end | sed 's/0*//')
3762                     [[ -z "$end" ]] && end=0
3763                     [[ $padlen2 -gt $padlen ]] && {
3764                         [[ $padlen2 -eq ${#end} ]] && padlen2=0
3765                         padlen=$padlen2
3766                     }
3767                     begin=$(echo $begin | sed 's/0*//')
3768                     [ -z $begin ] && begin=0
3769
3770                     if [ ! -z "${begin##[!0-9]*}" ]; then
3771                         order=$(seq -f "%0${padlen}g" $begin $end)
3772                     else
3773                         order=$(eval echo {$begin..$end});
3774                     fi
3775
3776                     for num in $order; do
3777                         value="${name#*,}${num}${back}"
3778                         [ "$value" != "${value/\[/}" ] && {
3779                             value=$(hostlist_expand "$value")
3780                         }
3781                         myList="$myList $value"
3782                     done
3783                 done
3784             fi
3785         } else {
3786             myList="$myList $item"
3787         } fi
3788     done
3789     myList=${myList//,/ }
3790     myList=${myList:1} # Remove first character which is a space
3791
3792     # Filter any duplicates without sorting
3793     list="$myList "
3794     myList="${list%% *}"
3795
3796     while [[ "$list" != ${myList##* } ]]; do
3797         local tlist=" $list"
3798         list=${tlist// ${list%% *} / }
3799         list=${list:1}
3800         myList="$myList ${list%% *}"
3801     done
3802     myList="${myList%* }";
3803
3804     # We can select an object at an offset in the list
3805     [ $# -eq 2 ] && {
3806         cnt=0
3807         for item in $myList; do
3808             let cnt=cnt+1
3809             [ $cnt -eq $offset ] && {
3810                 myList=$item
3811             }
3812         done
3813         [ $(get_node_count $myList) -ne 1 ] && myList=""
3814     }
3815     echo $myList
3816 }
3817
3818 facet_host() {
3819         local facet=$1
3820         local varname
3821
3822         [ "$facet" == client ] && echo -n $HOSTNAME && return
3823         varname=${facet}_HOST
3824         if [ -z "${!varname}" ]; then
3825                 if [ "${facet:0:3}" == "ost" ]; then
3826                         local fh=${facet%failover}_HOST
3827                         eval export ${facet}_HOST=${!fh}
3828                         if [ -z "${!varname}" ]; then
3829                                 eval export ${facet}_HOST=${ost_HOST}
3830                         fi
3831                 elif [ "${facet:0:3}" == "mdt" -o \
3832                         "${facet:0:3}" == "mds" -o \
3833                         "${facet:0:3}" == "mgs" ]; then
3834                         eval export ${facet}_HOST=${mds_HOST}
3835                 fi
3836         fi
3837         echo -n ${!varname}
3838 }
3839
3840 facet_failover_host() {
3841         local facet=$1
3842         local varname
3843
3844         var=${facet}failover_HOST
3845         if [ -n "${!var}" ]; then
3846                 echo ${!var}
3847                 return
3848         fi
3849
3850         if [ "${facet:0:3}" == "mdt" -o "${facet:0:3}" == "mds" -o \
3851              "${facet:0:3}" == "mgs" ]; then
3852
3853                 eval export ${facet}failover_host=${mds_HOST}
3854                 echo ${mds_HOST}
3855                 return
3856         fi
3857
3858         if [[ $facet == ost* ]]; then
3859                 eval export ${facet}failover_host=${ost_HOST}
3860                 echo ${ost_HOST}
3861                 return
3862         fi
3863 }
3864
3865 facet_active() {
3866     local facet=$1
3867     local activevar=${facet}active
3868
3869     if [ -f $TMP/${facet}active ] ; then
3870         source $TMP/${facet}active
3871     fi
3872
3873     active=${!activevar}
3874     if [ -z "$active" ] ; then
3875         echo -n ${facet}
3876     else
3877         echo -n ${active}
3878     fi
3879 }
3880
3881 facet_active_host() {
3882         facet_host $(facet_active $1)
3883 }
3884
3885 # Get the passive failover partner host of facet.
3886 facet_passive_host() {
3887         local facet=$1
3888         [[ $facet = client ]] && return
3889
3890         local host=${facet}_HOST
3891         local failover_host=${facet}failover_HOST
3892         local active_host=$(facet_active_host $facet)
3893
3894         [[ -z ${!failover_host} || ${!failover_host} = ${!host} ]] && return
3895
3896         if [[ $active_host = ${!host} ]]; then
3897                 echo -n ${!failover_host}
3898         else
3899                 echo -n ${!host}
3900         fi
3901 }
3902
3903 change_active() {
3904     local facetlist=$1
3905     local facet
3906
3907     facetlist=$(exclude_items_from_list $facetlist mgs)
3908
3909     for facet in ${facetlist//,/ }; do
3910     local failover=${facet}failover
3911     local host=`facet_host $failover`
3912     [ -z "$host" ] && return
3913
3914     local curactive=`facet_active $facet`
3915     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
3916         eval export ${facet}active=$facet
3917     else
3918         eval export ${facet}active=$failover
3919     fi
3920     # save the active host for this facet
3921     local activevar=${facet}active
3922     echo "$activevar=${!activevar}" > $TMP/$activevar
3923     [[ $facet = mds1 ]] && combined_mgs_mds && \
3924         echo "mgsactive=${!activevar}" > $TMP/mgsactive
3925     local TO=`facet_active_host $facet`
3926     echo "Failover $facet to $TO"
3927     done
3928 }
3929
3930 do_node() {
3931     local verbose=false
3932     # do not stripe off hostname if verbose, bug 19215
3933     if [ x$1 = x--verbose ]; then
3934         shift
3935         verbose=true
3936     fi
3937
3938     local HOST=$1
3939     shift
3940     local myPDSH=$PDSH
3941     if [ "$HOST" = "$HOSTNAME" ]; then
3942         myPDSH="no_dsh"
3943     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
3944         echo "cannot run remote command on $HOST with $myPDSH"
3945         return 128
3946     fi
3947     if $VERBOSE; then
3948         echo "CMD: $HOST $@" >&2
3949         $myPDSH $HOST "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
3950     fi
3951
3952         if [[ "$myPDSH" == "rsh" ]] ||
3953            [[ "$myPDSH" == *pdsh* && "$myPDSH" != *-S* ]]; then
3954                 # we need this because rsh and pdsh do not return
3955                 # exit code of an executed command
3956                 local command_status="$TMP/cs"
3957                 eval $myPDSH $HOST ":> $command_status"
3958                 eval $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests;
3959                                      PATH=\$PATH:/sbin:/usr/sbin;
3960                                      cd $RPWD;
3961                                      LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
3962                                      echo command failed >$command_status"
3963                 [[ -n "$($myPDSH $HOST cat $command_status)" ]] && return 1 ||
3964                         return 0
3965         fi
3966
3967     if $verbose ; then
3968         # print HOSTNAME for myPDSH="no_dsh"
3969         if [[ $myPDSH = no_dsh ]]; then
3970             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
3971         else
3972             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
3973         fi
3974     else
3975         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
3976     fi
3977     return ${PIPESTATUS[0]}
3978 }
3979
3980 do_nodev() {
3981     do_node --verbose "$@"
3982 }
3983
3984 single_local_node () {
3985    [ "$1" = "$HOSTNAME" ]
3986 }
3987
3988 # Outputs environment variable assignments that should be passed to remote nodes
3989 get_env_vars() {
3990         local var
3991         local value
3992         local facets=$(get_facets)
3993         local facet
3994
3995         for var in ${!MODOPTS_*}; do
3996                 value=${!var//\"/\\\"}
3997                 echo -n " ${var}=\"$value\""
3998         done
3999
4000         for facet in ${facets//,/ }; do
4001                 var=${facet}_FSTYPE
4002                 if [ -n "${!var}" ]; then
4003                         echo -n " $var=${!var}"
4004                 fi
4005         done
4006
4007         for var in MGSFSTYPE MDSFSTYPE OSTFSTYPE; do
4008                 if [ -n "${!var}" ]; then
4009                         echo -n " $var=${!var}"
4010                 fi
4011         done
4012
4013         for var in VERBOSE; do
4014                 if [ -n "${!var}" ]; then
4015                         echo -n " $var=${!var}"
4016                 fi
4017         done
4018
4019         if [ -n "$FSTYPE" ]; then
4020                 echo -n " FSTYPE=$FSTYPE"
4021         fi
4022
4023         for var in LNETLND NETTYPE; do
4024                 if [ -n "${!var}" ]; then
4025                         echo -n " $var=${!var}"
4026                 fi
4027         done
4028 }
4029
4030 do_nodes() {
4031     local verbose=false
4032     # do not stripe off hostname if verbose, bug 19215
4033     if [ x$1 = x--verbose ]; then
4034         shift
4035         verbose=true
4036     fi
4037
4038     local rnodes=$1
4039     shift
4040
4041     if single_local_node $rnodes; then
4042         if $verbose; then
4043            do_nodev $rnodes "$@"
4044         else
4045            do_node $rnodes "$@"
4046         fi
4047         return $?
4048     fi
4049
4050     # This is part from do_node
4051     local myPDSH=$PDSH
4052
4053     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
4054         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
4055
4056     export FANOUT=$(get_node_count "${rnodes//,/ }")
4057     if $VERBOSE; then
4058         echo "CMD: $rnodes $@" >&2
4059         $myPDSH $rnodes "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
4060     fi
4061
4062     # do not replace anything from pdsh output if -N is used
4063     # -N     Disable hostname: prefix on lines of output.
4064     if $verbose || [[ $myPDSH = *-N* ]]; then
4065         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")"
4066     else
4067         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")" | sed -re "s/^[^:]*: //g"
4068     fi
4069     return ${PIPESTATUS[0]}
4070 }
4071
4072 ##
4073 # Execute commands on a single service's host
4074 #
4075 # The \a facet (service) may be on a local or remote node, which is
4076 # determined at the time the command is run.
4077 #
4078 # usage: do_facet $facet command [arg ...]
4079 do_facet() {
4080         local facet=$1
4081         shift
4082         local HOST=$(facet_active_host $facet)
4083         [ -z $HOST ] && echo "No host defined for facet ${facet}" && exit 1
4084         do_node $HOST "$@"
4085 }
4086
4087 # Function: do_facet_random_file $FACET $FILE $SIZE
4088 # Creates FILE with random content on the given FACET of given SIZE
4089
4090 do_facet_random_file() {
4091         local facet="$1"
4092         local fpath="$2"
4093         local fsize="$3"
4094         local cmd="dd if=/dev/urandom of='$fpath' bs=$fsize count=1"
4095         do_facet $facet "$cmd 2>/dev/null"
4096 }
4097
4098 do_facet_create_file() {
4099         local facet="$1"
4100         local fpath="$2"
4101         local fsize="$3"
4102         local cmd="dd if=/dev/zero of='$fpath' bs=$fsize count=1"
4103         do_facet $facet "$cmd 2>/dev/null"
4104 }
4105
4106 do_nodesv() {
4107     do_nodes --verbose "$@"
4108 }
4109
4110 add() {
4111         local facet=$1
4112         shift
4113         # make sure its not already running
4114         stop ${facet} -f
4115         rm -f $TMP/${facet}active
4116         [[ $facet = mds1 ]] && combined_mgs_mds && rm -f $TMP/mgsactive
4117         do_facet ${facet} $MKFS $* || return ${PIPESTATUS[0]}
4118
4119         if [[ $(facet_fstype $facet) == zfs ]]; then
4120                 #
4121                 # After formatting a ZFS target, "cachefile=none" property will
4122                 # be set on the ZFS storage pool so that the pool is not
4123                 # automatically imported on system startup. And then the pool
4124                 # will be exported so as to leave the importing and exporting
4125                 # operations handled by mount_facet() and stop() separately.
4126                 #
4127                 refresh_partition_table $facet $(facet_vdevice $facet)
4128                 disable_zpool_cache $facet
4129                 export_zpool $facet
4130         fi
4131 }
4132
4133 # Device formatted as ost
4134 ostdevname() {
4135         local num=$1
4136         local DEVNAME=OSTDEV$num
4137
4138         local fstype=$(facet_fstype ost$num)
4139
4140         case $fstype in
4141                 ldiskfs )
4142                         local dev=ost${num}_dev
4143                         [[ -n ${!dev} ]] && eval DEVPTR=${!dev} ||
4144                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
4145                         eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
4146                 zfs )
4147                         #try $OSTZFSDEVn - independent of vdev
4148                         DEVNAME=OSTZFSDEV$num
4149                         eval DEVPTR=${!DEVNAME:=${FSNAME}-ost${num}/ost${num}};;
4150                 * )
4151                         error "unknown fstype!";;
4152         esac
4153
4154     echo -n $DEVPTR
4155 }
4156
4157 # Physical device location of data
4158 ostvdevname() {
4159         local num=$1
4160         local DEVNAME
4161         local VDEVPTR
4162
4163         local fstype=$(facet_fstype ost$num)
4164
4165         case $fstype in
4166                 ldiskfs )
4167                         # vdevs are not supported by ldiskfs
4168                         eval VDEVPTR="";;
4169                 zfs )
4170                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE{n}
4171                         # Device formatted by zfs
4172                         DEVNAME=OSTDEV$num
4173                         eval VDEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
4174                 * )
4175                         error "unknown fstype!";;
4176         esac
4177
4178         echo -n $VDEVPTR
4179 }
4180
4181 # Logical device formatted for lustre
4182 mdsdevname() {
4183         local num=$1
4184         local DEVNAME=MDSDEV$num
4185
4186         local fstype=$(facet_fstype mds$num)
4187
4188         case $fstype in
4189                 ldiskfs )
4190                         local dev=mds${num}_dev
4191                         [[ -n ${!dev} ]] && eval DEVPTR=${!dev} ||
4192                         #if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
4193                         eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
4194                 zfs )
4195                         # try $MDSZFSDEVn - independent of vdev
4196                         DEVNAME=MDSZFSDEV$num
4197                         eval DEVPTR=${!DEVNAME:=${FSNAME}-mdt${num}/mdt${num}};;
4198                 * )
4199                         error "unknown fstype!";;
4200         esac
4201
4202         echo -n $DEVPTR
4203 }
4204
4205 # Physical location of data
4206 mdsvdevname() {
4207         local VDEVPTR=""
4208         local num=$1
4209         local fstype=$(facet_fstype mds$num)
4210
4211         case $fstype in
4212                 ldiskfs )
4213                         # vdevs are not supported by ldiskfs
4214                         eval VDEVPTR="";;
4215                 zfs )
4216                         # if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
4217                         # Device formatted by ZFS
4218                         local DEVNAME=MDSDEV$num
4219                         eval VDEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
4220                 * )
4221                         error "unknown fstype!";;
4222         esac
4223
4224         echo -n $VDEVPTR
4225 }
4226
4227 mgsdevname() {
4228         local DEVPTR
4229         local fstype=$(facet_fstype mgs)
4230
4231         case $fstype in
4232         ldiskfs )
4233                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
4234                    ( [ -z "$MGSDEV" ] || [ $MGSDEV = $MDSDEV1 ] ); then
4235                         DEVPTR=$(mdsdevname 1)
4236                 else
4237                         [[ -n $mgs_dev ]] && DEVPTR=$mgs_dev ||
4238                         DEVPTR=$MGSDEV
4239                 fi;;
4240         zfs )
4241                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
4242                     ( [ -z "$MGSZFSDEV" ] &&
4243                         [ -z "$MGSDEV" -o "$MGSDEV" = $(mdsvdevname 1) ] ); then
4244                         DEVPTR=$(mdsdevname 1)
4245                 else
4246                         DEVPTR=${MGSZFSDEV:-${FSNAME}-mgs/mgs}
4247                 fi;;
4248         * )
4249                 error "unknown fstype!";;
4250         esac
4251
4252         echo -n $DEVPTR
4253 }
4254
4255 mgsvdevname() {
4256         local VDEVPTR=""
4257
4258         local fstype=$(facet_fstype mgs)
4259
4260         case $fstype in
4261         ldiskfs )
4262                 # vdevs are not supported by ldiskfs
4263                 ;;
4264         zfs )
4265                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
4266                    ( [ -z "$MGSDEV" ] &&
4267                        [ -z "$MGSZFSDEV" -o "$MGSZFSDEV" = $(mdsdevname 1) ]); then
4268                         VDEVPTR=$(mdsvdevname 1)
4269                 elif [ -n "$MGSDEV" ]; then
4270                         VDEVPTR=$MGSDEV
4271                 fi;;
4272         * )
4273                 error "unknown fstype!";;
4274         esac
4275
4276         echo -n $VDEVPTR
4277 }
4278
4279 facet_mntpt () {
4280     local facet=$1
4281     [[ $facet = mgs ]] && combined_mgs_mds && facet="mds1"
4282
4283     local var=${facet}_MOUNT
4284     eval mntpt=${!var:-${MOUNT}-$facet}
4285
4286     echo -n $mntpt
4287 }
4288
4289 mount_ldiskfs() {
4290         local facet=$1
4291         local dev=$(facet_device $facet)
4292         local mnt=${2:-$(facet_mntpt $facet)}
4293         local opts
4294         local dm_dev=$dev
4295
4296         if dm_flakey_supported $facet; then
4297                 dm_dev=$(dm_create_dev $facet $dev)
4298                 [[ -n "$dm_dev" ]] || dm_dev=$dev
4299         fi
4300         is_blkdev $facet $dm_dev || opts=$(csa_add "$opts" -o loop)
4301         export_dm_dev $facet $dm_dev
4302
4303         do_facet $facet mount -t ldiskfs $opts $dm_dev $mnt
4304 }
4305
4306 unmount_ldiskfs() {
4307         local facet=$1
4308         local dev=$(facet_device $facet)
4309         local mnt=${2:-$(facet_mntpt $facet)}
4310
4311         do_facet $facet $UMOUNT $mnt
4312 }
4313
4314 var_name() {
4315         echo -n "$1" | tr -c '[:alnum:]\n' '_'
4316 }
4317
4318 mount_zfs() {
4319         local facet=$1
4320         local ds=$(facet_device $facet)
4321         local mnt=${2:-$(facet_mntpt $facet)}
4322         local canmnt
4323         local mntpt
4324
4325         import_zpool $facet
4326         canmnt=$(do_facet $facet $ZFS get -H -o value canmount $ds)
4327         mntpt=$(do_facet $facet $ZFS get -H -o value mountpoint $ds)
4328         do_facet $facet $ZFS set canmount=noauto $ds
4329         #
4330         # The "legacy" mount method is used here because "zfs unmount $mnt"
4331         # calls stat(2) on $mnt/../*, which may include $MOUNT.  If certain
4332         # targets are not available at the time, the stat(2) on $MOUNT will
4333         # hang.
4334         #
4335         do_facet $facet $ZFS set mountpoint=legacy $ds
4336         do_facet $facet mount -t zfs $ds $mnt
4337         eval export mz_$(var_name ${facet}_$ds)_canmount=$canmnt
4338         eval export mz_$(var_name ${facet}_$ds)_mountpoint=$mntpt
4339 }
4340
4341 unmount_zfs() {
4342         local facet=$1
4343         local ds=$(facet_device $facet)
4344         local mnt=${2:-$(facet_mntpt $facet)}
4345         local var_mntpt=mz_$(var_name ${facet}_$ds)_mountpoint
4346         local var_canmnt=mz_$(var_name ${facet}_$ds)_canmount
4347         local mntpt=${!var_mntpt}
4348         local canmnt=${!var_canmnt}
4349
4350         unset $var_mntpt
4351         unset $var_canmnt
4352         do_facet $facet umount $mnt
4353         do_facet $facet $ZFS set mountpoint=$mntpt $ds
4354         do_facet $facet $ZFS set canmount=$canmnt $ds
4355         export_zpool $facet
4356 }
4357
4358 mount_fstype() {
4359         local facet=$1
4360         local mnt=$2
4361         local fstype=$(facet_fstype $facet)
4362
4363         mount_$fstype $facet $mnt
4364 }
4365
4366 unmount_fstype() {
4367         local facet=$1
4368         local mnt=$2
4369         local fstype=$(facet_fstype $facet)
4370
4371         unmount_$fstype $facet $mnt
4372 }
4373
4374 ########
4375 ## MountConf setup
4376
4377 stopall() {
4378         # make sure we are using the primary server, so test-framework will
4379         # be able to clean up properly.
4380         activemds=`facet_active mds1`
4381         if [ $activemds != "mds1" ]; then
4382                 fail mds1
4383         fi
4384
4385         local clients=$CLIENTS
4386         [ -z $clients ] && clients=$(hostname)
4387
4388         zconf_umount_clients $clients $MOUNT "$*" || true
4389         [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
4390
4391         [ -n "$CLIENTONLY" ] && return
4392
4393         # The add fn does rm ${facet}active file, this would be enough
4394         # if we use do_facet <facet> only after the facet added, but
4395         # currently we use do_facet mds in local.sh
4396         for num in `seq $MDSCOUNT`; do
4397                 stop mds$num -f
4398                 rm -f ${TMP}/mds${num}active
4399         done
4400         combined_mgs_mds && rm -f $TMP/mgsactive
4401
4402         for num in `seq $OSTCOUNT`; do
4403                 stop ost$num -f
4404                 rm -f $TMP/ost${num}active
4405         done
4406
4407         if ! combined_mgs_mds ; then
4408                 stop mgs
4409         fi
4410
4411         if $SHARED_KEY; then
4412                 export SK_MOUNTED=false
4413         fi
4414
4415         return 0
4416 }
4417
4418 cleanup_echo_devs () {
4419         trap 0
4420         local dev
4421         local devs=$($LCTL dl | grep echo | awk '{print $4}')
4422
4423         for dev in $devs; do
4424                 $LCTL --device $dev cleanup
4425                 $LCTL --device $dev detach
4426         done
4427 }
4428
4429 cleanupall() {
4430         nfs_client_mode && return
4431         cifs_client_mode && return
4432
4433         cleanup_echo_devs
4434         CLEANUP_DM_DEV=true stopall $*
4435
4436         unload_modules
4437         cleanup_sk
4438         cleanup_gss
4439 }
4440
4441 combined_mgs_mds () {
4442         [[ "$(mdsdevname 1)" = "$(mgsdevname)" ]] &&
4443                 [[ "$(facet_host mds1)" = "$(facet_host mgs)" ]]
4444 }
4445
4446 lower() {
4447         echo -n "$1" | tr '[:upper:]' '[:lower:]'
4448 }
4449
4450 upper() {
4451         echo -n "$1" | tr '[:lower:]' '[:upper:]'
4452 }
4453
4454 squash_opt() {
4455         local var="$*"
4456         local other=""
4457         local opt_o=""
4458         local opt_e=""
4459         local first_e=0
4460         local first_o=0
4461         local take=""
4462
4463         var=$(echo "$var" | sed -e 's/,\( \)*/,/g')
4464         for i in $(echo "$var"); do
4465                 if [ "$i" == "-O" ]; then
4466                         take="o";
4467                         first_o=$(($first_o + 1))
4468                         continue;
4469                 fi
4470                 if [ "$i" == "-E" ]; then
4471                         take="e";
4472                         first_e=$(($first_e + 1 ))
4473                         continue;
4474                 fi
4475                 case $take in
4476                         "o")
4477                                 [ $first_o -gt 1 ] && opt_o+=",";
4478                                 opt_o+="$i";
4479                                 ;;
4480                         "e")
4481                                 [ $first_e -gt 1 ] && opt_e+=",";
4482                                 opt_e+="$i";
4483                                 ;;
4484                         *)
4485                                 other+=" $i";
4486                                 ;;
4487                 esac
4488                 take=""
4489         done
4490
4491         echo -n "$other"
4492         [ -n "$opt_o" ] && echo " -O $opt_o"
4493         [ -n "$opt_e" ] && echo " -E $opt_e"
4494 }
4495
4496 mkfs_opts() {
4497         local facet=$1
4498         local dev=$2
4499         local fsname=${3:-"$FSNAME"}
4500         local type=$(facet_type $facet)
4501         local index=$(facet_index $facet)
4502         local fstype=$(facet_fstype $facet)
4503         local host=$(facet_host $facet)
4504         local opts
4505         local fs_mkfs_opts
4506         local var
4507
4508         if [ $type == MGS ] || ( [ $type == MDS ] &&
4509                                  [ "$dev" == $(mgsdevname) ] &&
4510                                  [ "$host" == "$(facet_host mgs)" ] ); then
4511                 opts="--mgs"
4512         else
4513                 opts="--mgsnode=$MGSNID"
4514         fi
4515
4516         if [ $type != MGS ]; then
4517                 opts+=" --fsname=$fsname --$(lower ${type/MDS/MDT}) \
4518                         --index=$index"
4519         fi
4520
4521         var=${facet}failover_HOST
4522         if [ -n "${!var}" ] && [ ${!var} != $(facet_host $facet) ]; then
4523                 opts+=" --failnode=$(h2nettype ${!var})"
4524         fi
4525
4526         opts+=${TIMEOUT:+" --param=sys.timeout=$TIMEOUT"}
4527         opts+=${LDLM_TIMEOUT:+" --param=sys.ldlm_timeout=$LDLM_TIMEOUT"}
4528
4529         if [ $type == MDS ]; then
4530                 opts+=${MDSCAPA:+" --param-mdt.capa=$MDSCAPA"}
4531                 opts+=${DEF_STRIPE_SIZE:+" --param=lov.stripesize=$DEF_STRIPE_SIZE"}
4532                 opts+=${DEF_STRIPE_COUNT:+" --param=lov.stripecount=$DEF_STRIPE_COUNT"}
4533                 opts+=${L_GETIDENTITY:+" --param=mdt.identity_upcall=$L_GETIDENTITY"}
4534
4535                 if [ $fstype == ldiskfs ]; then
4536                         fs_mkfs_opts+="-O ea_inode,large_dir"
4537
4538                         var=${facet}_JRN
4539                         if [ -n "${!var}" ]; then
4540                                 fs_mkfs_opts+=" -J device=${!var}"
4541                         else
4542                                 fs_mkfs_opts+=${MDSJOURNALSIZE:+" -J size=$MDSJOURNALSIZE"}
4543                         fi
4544                         fs_mkfs_opts+=${MDSISIZE:+" -i $MDSISIZE"}
4545                 fi
4546         fi
4547
4548         if [ $type == OST ]; then
4549                 opts+=${OSSCAPA:+" --param=ost.capa=$OSSCAPA"}
4550
4551                 if [ $fstype == ldiskfs ]; then
4552                         var=${facet}_JRN
4553                         if [ -n "${!var}" ]; then
4554                                 fs_mkfs_opts+=" -J device=${!var}"
4555                         else
4556                                 fs_mkfs_opts+=${OSTJOURNALSIZE:+" -J size=$OSTJOURNALSIZE"}
4557                         fi
4558                 fi
4559         fi
4560
4561         opts+=" --backfstype=$fstype"
4562
4563         var=${type}SIZE
4564         if [ -n "${!var}" ]; then
4565                 opts+=" --device-size=${!var}"
4566         fi
4567
4568         var=$(upper $fstype)_MKFS_OPTS
4569         fs_mkfs_opts+=${!var:+" ${!var}"}
4570
4571         var=${type}_FS_MKFS_OPTS
4572         fs_mkfs_opts+=${!var:+" ${!var}"}
4573
4574         [ $fstype == ldiskfs ] && fs_mkfs_opts=$(squash_opt $fs_mkfs_opts)
4575
4576         if [ -n "${fs_mkfs_opts## }" ]; then
4577                 opts+=" --mkfsoptions=\\\"${fs_mkfs_opts## }\\\""
4578         fi
4579
4580         var=${type}OPT
4581         opts+=${!var:+" ${!var}"}
4582
4583         echo -n "$opts"
4584 }
4585
4586 mountfs_opts() {
4587         local facet=$1
4588         local type=$(facet_type $facet)
4589         local var=${type}_MOUNT_FS_OPTS
4590         local opts=""
4591         if [ -n "${!var}" ]; then
4592                 opts+=" --mountfsoptions=${!var}"
4593         fi
4594         echo -n "$opts"
4595 }
4596
4597 check_ost_indices() {
4598         local index_count=${#OST_INDICES[@]}
4599         [[ $index_count -eq 0 || $OSTCOUNT -le $index_count ]] && return 0
4600
4601         # OST count is greater than the index count in $OST_INDEX_LIST.
4602         # We need check whether there are duplicate indices.
4603         local i
4604         local j
4605         local index
4606         for i in $(seq $((index_count + 1)) $OSTCOUNT); do
4607                 index=$(facet_index ost$i)
4608                 for j in $(seq 0 $((index_count - 1))); do
4609                         [[ $index -ne ${OST_INDICES[j]} ]] ||
4610                         error "ost$i has the same index $index as ost$((j+1))"
4611                 done
4612         done
4613 }
4614
4615 __touch_device()
4616 {
4617         local facet_type=$1 # mgs || mds || ost
4618         local facet_num=$2
4619         local facet=${1}${2}
4620         local device
4621
4622         case "$(facet_fstype $facet)" in
4623         ldiskfs)
4624                 device=$(${facet_type}devname $facet_num)
4625                 ;;
4626         zfs)
4627                 device=$(${facet_type}vdevname $facet_num)
4628                 ;;
4629         *)
4630                 error "Unhandled filesystem type"
4631                 ;;
4632         esac
4633
4634         do_facet $facet "[ -e \"$device\" ]" && return
4635
4636         # Note: the following check only works with absolute paths
4637         [[ ! "$device" =~ ^/dev/ ]] || [[ "$device" =~ ^/dev/shm/ ]] ||
4638                 error "$facet: device '$device' does not exist"
4639
4640         # zpool create doesn't like empty files
4641         [[ $(facet_fstype $facet) == zfs ]] && return 0
4642
4643         do_facet $facet "touch \"${device}\""
4644 }
4645
4646 format_mgs() {
4647         local quiet
4648
4649         if ! $VERBOSE; then
4650                 quiet=yes
4651         fi
4652         echo "Format mgs: $(mgsdevname)"
4653         reformat_external_journal mgs
4654
4655         # touch "device" in case it is a loopback file for testing and needs to
4656         # be created. mkfs.lustre doesn't do this to avoid accidentally writing
4657         # to non-existent files in /dev if the admin made a typo during setup
4658         __touch_device mgs
4659
4660         add mgs $(mkfs_opts mgs $(mgsdevname)) $(mountfs_opts mgs) --reformat \
4661                 $(mgsdevname) $(mgsvdevname) ${quiet:+>/dev/null} || exit 10
4662 }
4663
4664 format_mdt() {
4665         local num=$1
4666         local quiet
4667
4668         if ! $VERBOSE; then
4669                 quiet=yes
4670         fi
4671         echo "Format mds$num: $(mdsdevname $num)"
4672         reformat_external_journal mds$num
4673
4674         __touch_device mds $num
4675
4676         add mds$num $(mkfs_opts mds$num $(mdsdevname ${num})) \
4677                 $(mountfs_opts mds$num) --reformat $(mdsdevname $num) \
4678                 $(mdsvdevname $num) ${quiet:+>/dev/null} || exit 10
4679 }
4680
4681 format_ost() {
4682         local num=$1
4683
4684         if ! $VERBOSE; then
4685                 quiet=yes
4686         fi
4687         echo "Format ost$num: $(ostdevname $num)"
4688         reformat_external_journal ost$num
4689
4690         __touch_device ost $num
4691
4692         add ost$num $(mkfs_opts ost$num $(ostdevname ${num})) \
4693                 $(mountfs_opts ost$num) --reformat $(ostdevname $num) \
4694                 $(ostvdevname ${num}) ${quiet:+>/dev/null} || exit 10
4695 }
4696
4697 formatall() {
4698         stopall -f
4699         # Set hostid for ZFS/SPL zpool import protection
4700         # (Assumes MDS version is also OSS version)
4701         if [ $(lustre_version_code $SINGLEMDS) -ge $(version_code 2.8.54) ];
4702         then
4703                 do_rpc_nodes "$(comma_list $(all_server_nodes))" set_hostid
4704         fi
4705
4706         # We need ldiskfs here, may as well load them all
4707         load_modules
4708         [ -n "$CLIENTONLY" ] && return
4709         echo Formatting mgs, mds, osts
4710         if ! combined_mgs_mds ; then
4711                 format_mgs
4712         fi
4713
4714         for num in $(seq $MDSCOUNT); do
4715                 format_mdt $num
4716         done
4717
4718         export OST_INDICES=($(hostlist_expand "$OST_INDEX_LIST"))
4719         check_ost_indices
4720         for num in $(seq $OSTCOUNT); do
4721                 format_ost $num
4722         done
4723 }
4724
4725 mount_client() {
4726         grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
4727 }
4728
4729 umount_client() {
4730         grep " $1 " /proc/mounts && zconf_umount $HOSTNAME $*
4731 }
4732
4733 # return value:
4734 # 0: success, the old identity set already.
4735 # 1: success, the old identity does not set.
4736 # 2: fail.
4737 switch_identity() {
4738     local num=$1
4739     local switch=$2
4740     local j=`expr $num - 1`
4741     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
4742
4743     if [ -z "$MDT" ]; then
4744         return 2
4745     fi
4746
4747     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
4748
4749     if $switch; then
4750         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
4751     else
4752         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
4753     fi
4754
4755     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush=-1"
4756
4757     if [ $old = "NONE" ]; then
4758         return 1
4759     else
4760         return 0
4761     fi
4762 }
4763
4764 remount_client()
4765 {
4766         zconf_umount $HOSTNAME $1 || error "umount failed"
4767         zconf_mount $HOSTNAME $1 || error "mount failed"
4768 }
4769
4770 writeconf_facet() {
4771         local facet=$1
4772         local dev=$2
4773
4774         stop ${facet} -f
4775         rm -f $TMP/${facet}active
4776         do_facet ${facet} "$TUNEFS --quiet --writeconf $dev" || return 1
4777         return 0
4778 }
4779
4780 writeconf_all () {
4781         local mdt_count=${1:-$MDSCOUNT}
4782         local ost_count=${2:-$OSTCOUNT}
4783         local rc=0
4784
4785         for num in $(seq $mdt_count); do
4786                 DEVNAME=$(mdsdevname $num)
4787                 writeconf_facet mds$num $DEVNAME || rc=$?
4788         done
4789
4790         for num in $(seq $ost_count); do
4791                 DEVNAME=$(ostdevname $num)
4792                 writeconf_facet ost$num $DEVNAME || rc=$?
4793         done
4794         return $rc
4795 }
4796
4797 mountmgs() {
4798         if ! combined_mgs_mds ; then
4799                 start mgs $(mgsdevname) $MGS_MOUNT_OPTS
4800         fi
4801 }
4802
4803 mountmds() {
4804         local num
4805         local devname
4806         local host
4807         local varname
4808         for num in $(seq $MDSCOUNT); do
4809                 devname=$(mdsdevname $num)
4810                 start mds$num $devname $MDS_MOUNT_OPTS
4811
4812                 # We started mds$num, now we should set mds${num}_HOST
4813                 # and mds${num}failover_HOST variables properly if they
4814                 # are not set.
4815                 host=$(facet_host mds$num)
4816                 for varname in mds${num}_HOST mds${num}failover_HOST; do
4817                         if [[ -z "${!varname}" ]]; then
4818                                 eval $varname=$host
4819                         fi
4820                 done
4821                 if [ $IDENTITY_UPCALL != "default" ]; then
4822                         switch_identity $num $IDENTITY_UPCALL
4823                 fi
4824         done
4825 }
4826
4827 mountoss() {
4828         local num
4829         local devname
4830         local host
4831         local varname
4832         for num in $(seq $OSTCOUNT); do
4833                 devname=$(ostdevname $num)
4834                 start ost$num $devname $OST_MOUNT_OPTS
4835
4836                 # We started ost$num, now we should set ost${num}_HOST
4837                 # and ost${num}failover_HOST variables properly if they
4838                 # are not set.
4839                 host=$(facet_host ost$num)
4840                 for varname in ost${num}_HOST ost${num}failover_HOST; do
4841                         if [[ -z "${!varname}" ]]; then
4842                                 eval $varname=$host
4843                         fi
4844                 done
4845         done
4846 }
4847
4848 mountcli() {
4849         [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
4850         if [ ! -z $arg1 ]; then
4851                 [ "$arg1" = "server_only" ] && return
4852         fi
4853         mount_client $MOUNT
4854         if [ -n "$CLIENTS" ]; then
4855                 zconf_mount_clients $CLIENTS $MOUNT
4856         fi
4857         clients_up
4858
4859         if [ "$MOUNT_2" ]; then
4860                 mount_client $MOUNT2
4861                 if [ -n "$CLIENTS" ]; then
4862                         zconf_mount_clients $CLIENTS $MOUNT2
4863                 fi
4864         fi
4865 }
4866
4867 sk_nodemap_setup() {
4868         local sk_map_name=${1:-$SK_S2SNM}
4869         local sk_map_nodes=${2:-$HOSTNAME}
4870         do_node $(mgs_node) "$LCTL nodemap_add $sk_map_name"
4871         for servernode in $sk_map_nodes; do
4872                 local nids=$(do_nodes $servernode "$LCTL list_nids")
4873                 for nid in $nids; do
4874                         do_node $(mgs_node) "$LCTL nodemap_add_range --name \
4875                                 $sk_map_name --range $nid"
4876                 done
4877         done
4878 }
4879
4880 setupall() {
4881         local arg1=$1
4882
4883         nfs_client_mode && return
4884         cifs_client_mode && return
4885
4886         sanity_mount_check || error "environments are insane!"
4887
4888         load_modules
4889
4890         init_gss
4891
4892         if [ -z "$CLIENTONLY" ]; then
4893                 echo Setup mgs, mdt, osts
4894                 echo $WRITECONF | grep -q "writeconf" && writeconf_all
4895
4896                 if $SK_MOUNTED; then
4897                         echo "Shared Key file system already mounted"
4898                 else
4899                         mountmgs
4900                         mountmds
4901                         mountoss
4902                         if $SHARED_KEY; then
4903                                 export SK_MOUNTED=true
4904                         fi
4905                 fi
4906                 if $GSS_SK; then
4907                         echo "GSS_SK: setting kernel keyring perms"
4908                         do_nodes $(comma_list $(all_nodes)) \
4909                                 "keyctl show | grep lustre | cut -c1-11 |
4910                                 sed -e 's/ //g;' |
4911                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
4912
4913                         if $SK_S2S; then
4914                                 # Need to start one nodemap for servers,
4915                                 # and one for clients.
4916                                 sk_nodemap_setup $SK_S2SNM \
4917                                         $(comma_list $(all_server_nodes))
4918                                 mountcli
4919                                 sk_nodemap_setup $SK_S2SNMCLI \
4920                                         ${CLIENTS:-$HOSTNAME}
4921                                 echo "Nodemap set up for SK S2S, remounting."
4922                                 stopall
4923                                 mountmgs
4924                                 mountmds
4925                                 mountoss
4926                         fi
4927                 fi
4928         fi
4929
4930         # wait a while to allow sptlrpc configuration be propogated to targets,
4931         # only needed when mounting new target devices.
4932         if $GSS; then
4933                 sleep 10
4934         fi
4935
4936         mountcli
4937         init_param_vars
4938
4939         # by remounting mdt before ost, initial connect from mdt to ost might
4940         # timeout because ost is not ready yet. wait some time to its fully
4941         # recovery. initial obd_connect timeout is 5s; in GSS case it's
4942         # preceeded by a context negotiation rpc with $TIMEOUT.
4943         # FIXME better by monitoring import status.
4944         if $GSS; then
4945                 if $GSS_SK; then
4946                         set_rule $FSNAME any cli2mdt $SK_FLAVOR
4947                         set_rule $FSNAME any cli2ost $SK_FLAVOR
4948                         if $SK_SKIPFIRST; then
4949                                 export SK_SKIPFIRST=false
4950
4951                                 sleep 30
4952                                 do_nodes $CLIENTS \
4953                                          "lctl set_param osc.*.idle_connect=1"
4954                                 return
4955                         else
4956                                 wait_flavor cli2mdt $SK_FLAVOR
4957                                 wait_flavor cli2ost $SK_FLAVOR
4958                         fi
4959                 else
4960                         set_flavor_all $SEC
4961                 fi
4962                 sleep $((TIMEOUT + 5))
4963         else
4964                 sleep 5
4965         fi
4966 }
4967
4968 mounted_lustre_filesystems() {
4969         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
4970 }
4971
4972 init_facet_vars () {
4973         [ -n "$CLIENTONLY" ] && return 0
4974         local facet=$1
4975         shift
4976         local device=$1
4977
4978         shift
4979
4980         eval export ${facet}_dev=${device}
4981         eval export ${facet}_opt=\"$@\"
4982
4983         local dev=${facet}_dev
4984
4985         # We need to loop for the label
4986         # in case its not initialized yet.
4987         for wait_time in {0,1,3,5,10}; do
4988
4989                 if [ $wait_time -gt 0 ]; then
4990                         echo "${!dev} not yet initialized,"\
4991                                 "waiting ${wait_time} seconds."
4992                         sleep $wait_time
4993                 fi
4994
4995                 local label=$(devicelabel ${facet} ${!dev})
4996
4997                 # Check to make sure the label does
4998                 # not include ffff at the end of the label.
4999                 # This indicates it has not been initialized yet.
5000
5001                 if [[ $label =~ [f|F]{4}$ ]]; then
5002                         # label is not initialized, unset the result
5003                         # and either try again or fail
5004                         unset label
5005                 else
5006                         break
5007                 fi
5008         done
5009
5010         [ -z "$label" ] && echo no label for ${!dev} && exit 1
5011
5012         eval export ${facet}_svc=${label}
5013
5014         local varname=${facet}failover_HOST
5015         if [ -z "${!varname}" ]; then
5016                 eval export $varname=$(facet_host $facet)
5017         fi
5018
5019         varname=${facet}_HOST
5020         if [ -z "${!varname}" ]; then
5021                 eval export $varname=$(facet_host $facet)
5022         fi
5023
5024         # ${facet}failover_dev is set in cfg file
5025         varname=${facet}failover_dev
5026         if [ -n "${!varname}" ] ; then
5027                 eval export ${facet}failover_dev=${!varname}
5028         else
5029                 eval export ${facet}failover_dev=$device
5030         fi
5031
5032         # get mount point of already mounted device
5033         # is facet_dev is already mounted then use the real
5034         #  mount point of this facet; otherwise use $(facet_mntpt $facet)
5035         # i.e. ${facet}_MOUNT if specified by user or default
5036         local mntpt=$(do_facet ${facet} cat /proc/mounts | \
5037                         awk '"'${!dev}'" == $1 && $3 == "lustre" { print $2 }')
5038         if [ -z $mntpt ]; then
5039                 mntpt=$(facet_mntpt $facet)
5040         fi
5041         eval export ${facet}_MOUNT=$mntpt
5042 }
5043
5044 init_facets_vars () {
5045         local DEVNAME
5046
5047         if ! remote_mds_nodsh; then
5048                 for num in $(seq $MDSCOUNT); do
5049                         DEVNAME=`mdsdevname $num`
5050                         init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
5051                 done
5052         fi
5053
5054         combined_mgs_mds || init_facet_vars mgs $(mgsdevname) $MGS_MOUNT_OPTS
5055
5056         if ! remote_ost_nodsh; then
5057                 for num in $(seq $OSTCOUNT); do
5058                         DEVNAME=$(ostdevname $num)
5059                         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
5060                 done
5061         fi
5062 }
5063
5064 init_facets_vars_simple () {
5065         local devname
5066
5067         if ! remote_mds_nodsh; then
5068                 for num in $(seq $MDSCOUNT); do
5069                         devname=$(mdsdevname $num)
5070                         eval export mds${num}_dev=${devname}
5071                         eval export mds${num}_opt=\"${MDS_MOUNT_OPTS}\"
5072                 done
5073         fi
5074
5075         if ! combined_mgs_mds ; then
5076                 eval export mgs_dev=$(mgsdevname)
5077                 eval export mgs_opt=\"${MGS_MOUNT_OPTS}\"
5078         fi
5079
5080         if ! remote_ost_nodsh; then
5081                 for num in $(seq $OSTCOUNT); do
5082                         devname=$(ostdevname $num)
5083                         eval export ost${num}_dev=${devname}
5084                         eval export ost${num}_opt=\"${OST_MOUNT_OPTS}\"
5085                 done
5086         fi
5087 }
5088
5089 osc_ensure_active () {
5090     local facet=$1
5091     local timeout=$2
5092     local period=0
5093
5094     while [ $period -lt $timeout ]; do
5095         count=$(do_facet $facet "lctl dl | grep ' IN osc ' 2>/dev/null | wc -l")
5096         if [ $count -eq 0 ]; then
5097             break
5098         fi
5099
5100         echo "There are $count OST are inactive, wait $period seconds, and try again"
5101         sleep 3
5102         period=$((period+3))
5103     done
5104
5105     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
5106 }
5107
5108 set_conf_param_and_check() {
5109         local myfacet=$1
5110         local TEST=$2
5111         local PARAM=$3
5112         local ORIG=$(do_facet $myfacet "$TEST")
5113         if [ $# -gt 3 ]; then
5114                 local FINAL=$4
5115         else
5116                 local -i FINAL
5117                 FINAL=$((ORIG + 5))
5118         fi
5119         echo "Setting $PARAM from $ORIG to $FINAL"
5120         do_facet mgs "$LCTL conf_param $PARAM='$FINAL'" ||
5121                 error "conf_param $PARAM failed"
5122
5123         wait_update_facet $myfacet "$TEST" "$FINAL" ||
5124                 error "check $PARAM failed!"
5125 }
5126
5127 set_persistent_param() {
5128         local myfacet=$1
5129         local test_param=$2
5130         local param=$3
5131         local orig=$(do_facet $myfacet "$LCTL get_param -n $test_param")
5132
5133         if [ $# -gt 3 ]; then
5134                 local final=$4
5135         else
5136                 local -i final
5137                 final=$((orig + 5))
5138         fi
5139
5140         if [[ $PERM_CMD == *"set_param -P"* ]]; then
5141                 echo "Setting $test_param from $orig to $final"
5142                 do_facet mgs "$PERM_CMD $test_param='$final'" ||
5143                         error "$PERM_CMD $test_param failed"
5144         else
5145                 echo "Setting $param from $orig to $final"
5146                 do_facet mgs "$PERM_CMD $param='$final'" ||
5147                         error "$PERM_CMD $param failed"
5148         fi
5149 }
5150
5151 set_persistent_param_and_check() {
5152         local myfacet=$1
5153         local test_param=$2
5154         local param=$3
5155         local orig=$(do_facet $myfacet "$LCTL get_param -n $test_param")
5156
5157         if [ $# -gt 3 ]; then
5158                 local final=$4
5159         else
5160                 local -i final
5161                 final=$((orig + 5))
5162         fi
5163
5164         set_persistent_param $myfacet $test_param $param "$final"
5165
5166         wait_update_facet $myfacet "$LCTL get_param -n $test_param" "$final" ||
5167                 error "check $param failed!"
5168 }
5169
5170 init_param_vars () {
5171         TIMEOUT=$(lctl get_param -n timeout)
5172         TIMEOUT=${TIMEOUT:-20}
5173
5174         if [ -n "$arg1" ]; then
5175                 [ "$arg1" = "server_only" ] && return
5176         fi
5177
5178         remote_mds_nodsh && log "Using TIMEOUT=$TIMEOUT" && return 0
5179
5180         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
5181         log "Using TIMEOUT=$TIMEOUT"
5182
5183         osc_ensure_active $SINGLEMDS $TIMEOUT
5184         osc_ensure_active client $TIMEOUT
5185         $LCTL set_param osc.*.idle_timeout=debug
5186
5187         if [ -n "$(lctl get_param -n mdc.*.connect_flags|grep jobstats)" ]; then
5188                 local current_jobid_var=$($LCTL get_param -n jobid_var)
5189
5190                 if [ $JOBID_VAR = "existing" ]; then
5191                         echo "keeping jobstats as $current_jobid_var"
5192                 elif [ $current_jobid_var != $JOBID_VAR ]; then
5193                         echo "setting jobstats to $JOBID_VAR"
5194
5195                         set_persistent_param_and_check client \
5196                                 "jobid_var" "$FSNAME.sys.jobid_var" $JOBID_VAR
5197                 fi
5198         else
5199                 echo "jobstats not supported by server"
5200         fi
5201
5202         if [ $QUOTA_AUTO -ne 0 ]; then
5203                 if [ "$ENABLE_QUOTA" ]; then
5204                         echo "enable quota as required"
5205                         setup_quota $MOUNT || return 2
5206                 else
5207                         echo "disable quota as required"
5208                         # $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
5209                 fi
5210         fi
5211         return 0
5212 }
5213
5214 nfs_client_mode () {
5215     if [ "$NFSCLIENT" ]; then
5216         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
5217         local clients=$CLIENTS
5218         [ -z $clients ] && clients=$(hostname)
5219
5220         # FIXME: remove hostname when 19215 fixed
5221         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
5222         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
5223         if [[ ${#nfsexport[@]} -eq 0 ]]; then
5224                 error_exit NFSCLIENT=$NFSCLIENT mode, but no NFS export found!
5225         fi
5226         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
5227         return
5228     fi
5229     return 1
5230 }
5231
5232 cifs_client_mode () {
5233         [ x$CIFSCLIENT = xyes ] &&
5234                 echo "CIFSCLIENT=$CIFSCLIENT mode: setup, cleanup, check config skipped"
5235 }
5236
5237 check_config_client () {
5238     local mntpt=$1
5239
5240     local mounted=$(mount | grep " $mntpt ")
5241     if [ -n "$CLIENTONLY" ]; then
5242         # bug 18021
5243         # CLIENTONLY should not depend on *_HOST settings
5244         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
5245         # in theory someone could create a new,
5246         # client-only config file that assumed lustre was already
5247         # configured and didn't set the MGSNID. If MGSNID is not set,
5248         # then we should use the mgs nid currently being used
5249         # as the default value. bug 18021
5250         [[ x$MGSNID = x ]] &&
5251             MGSNID=${mgc//MGC/}
5252
5253         if [[ x$mgc != xMGC$MGSNID ]]; then
5254             if [ "$mgs_HOST" ]; then
5255                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
5256 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
5257 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
5258             fi
5259         fi
5260         return 0
5261     fi
5262
5263     echo Checking config lustre mounted on $mntpt
5264     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
5265     mgshost=$(echo $mgshost | awk -F: '{print $1}')
5266
5267 }
5268
5269 check_config_clients () {
5270         local clients=${CLIENTS:-$HOSTNAME}
5271         local mntpt=$1
5272
5273         nfs_client_mode && return
5274         cifs_client_mode && return
5275
5276         do_rpc_nodes "$clients" check_config_client $mntpt
5277
5278         sanity_mount_check || error "environments are insane!"
5279 }
5280
5281 check_timeout () {
5282     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
5283     local cltimeout=$(lctl get_param -n timeout)
5284     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
5285         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
5286         return 1
5287     fi
5288 }
5289
5290 is_mounted () {
5291         local mntpt=$1
5292         [ -z $mntpt ] && return 1
5293         local mounted=$(mounted_lustre_filesystems)
5294
5295         echo $mounted' ' | grep -w -q $mntpt' '
5296 }
5297
5298 is_empty_dir() {
5299         [ $(find $1 -maxdepth 1 -print | wc -l) = 1 ] && return 0
5300         return 1
5301 }
5302
5303 # empty lustre filesystem may have empty directories lost+found and .lustre
5304 is_empty_fs() {
5305         # exclude .lustre & lost+found
5306         [ $(find $1 -maxdepth 1 -name lost+found -o -name .lustre -prune -o \
5307                 -print | wc -l) = 1 ] || return 1
5308         [ ! -d $1/lost+found ] || is_empty_dir $1/lost+found || return 1
5309         if [ $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.4.0) ]; then
5310                 # exclude .lustre/fid (LU-2780)
5311                 [ $(find $1/.lustre -maxdepth 1 -name fid -prune -o \
5312                         -print | wc -l) = 1 ] || return 1
5313         else
5314                 [ ! -d $1/.lustre ] || is_empty_dir $1/.lustre || return 1
5315         fi
5316         return 0
5317 }
5318
5319 check_and_setup_lustre() {
5320         sanitize_parameters
5321         nfs_client_mode && return
5322         cifs_client_mode && return
5323
5324         local MOUNTED=$(mounted_lustre_filesystems)
5325
5326         local do_check=true
5327         # 1.
5328         # both MOUNT and MOUNT2 are not mounted
5329         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
5330                 [ "$REFORMAT" = "yes" ] && CLEANUP_DM_DEV=true formatall
5331                 # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
5332                 setupall
5333                 is_mounted $MOUNT || error "NAME=$NAME not mounted"
5334                 export I_MOUNTED=yes
5335                 do_check=false
5336     # 2.
5337     # MOUNT2 is mounted
5338     elif is_mounted $MOUNT2; then
5339             # 3.
5340             # MOUNT2 is mounted, while MOUNT_2 is not set
5341             if ! [ "$MOUNT_2" ]; then
5342                 cleanup_mount $MOUNT2
5343                 export I_UMOUNTED2=yes
5344
5345             # 4.
5346             # MOUNT2 is mounted, MOUNT_2 is set
5347             else
5348                 # FIXME: what to do if check_config failed?
5349                 # i.e. if:
5350                 # 1) remote client has mounted other Lustre fs ?
5351                 # 2) it has insane env ?
5352                 # let's try umount MOUNT2 on all clients and mount it again:
5353                 if ! check_config_clients $MOUNT2; then
5354                     cleanup_mount $MOUNT2
5355                     restore_mount $MOUNT2
5356                     export I_MOUNTED2=yes
5357                 fi
5358             fi
5359
5360     # 5.
5361     # MOUNT is mounted MOUNT2 is not mounted
5362     elif [ "$MOUNT_2" ]; then
5363         restore_mount $MOUNT2
5364         export I_MOUNTED2=yes
5365     fi
5366
5367     if $do_check; then
5368         # FIXME: what to do if check_config failed?
5369         # i.e. if:
5370         # 1) remote client has mounted other Lustre fs?
5371         # 2) lustre is mounted on remote_clients atall ?
5372         check_config_clients $MOUNT
5373         init_facets_vars
5374         init_param_vars
5375
5376         set_default_debug_nodes $(comma_list $(nodes_list))
5377     fi
5378
5379         if [ -z "$CLIENTONLY" -a $(lower $OSD_TRACK_DECLARES_LBUG) == 'yes' ]; then
5380                 local facets=""
5381                 [ "$(facet_fstype ost1)" = "ldiskfs" ] &&
5382                         facets="$(get_facets OST)"
5383                 [ "$(facet_fstype mds1)" = "ldiskfs" ] &&
5384                         facets="$facets,$(get_facets MDS)"
5385                 [ "$(facet_fstype mgs)" = "ldiskfs" ] &&
5386                         facets="$facets,mgs"
5387                 local nodes="$(facets_hosts ${facets})"
5388                 if [ -n "$nodes" ] ; then
5389                         do_nodes $nodes "$LCTL set_param \
5390                                  osd-ldiskfs.track_declares_assert=1 || true"
5391                 fi
5392         fi
5393
5394         if $GSS_SK; then
5395                 set_flavor_all null
5396         elif $GSS; then
5397                 set_flavor_all $SEC
5398         fi
5399
5400         if [ "$ONLY" == "setup" ]; then
5401                 exit 0
5402         fi
5403 }
5404
5405 restore_mount () {
5406    local clients=${CLIENTS:-$HOSTNAME}
5407    local mntpt=$1
5408
5409    zconf_mount_clients $clients $mntpt
5410 }
5411
5412 cleanup_mount () {
5413         local clients=${CLIENTS:-$HOSTNAME}
5414         local mntpt=$1
5415
5416         zconf_umount_clients $clients $mntpt
5417 }
5418
5419 cleanup_and_setup_lustre() {
5420     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
5421         lctl set_param debug=0 || true
5422         cleanupall
5423         if [ "$ONLY" == "cleanup" ]; then
5424             exit 0
5425         fi
5426     fi
5427     check_and_setup_lustre
5428 }
5429
5430 # Get all of the server target devices from a given server node and type.
5431 get_mnt_devs() {
5432         local node=$1
5433         local type=$2
5434         local devs
5435         local dev
5436
5437         if [ "$type" == ost ]; then
5438                 devs=$(get_osd_param $node "" mntdev)
5439         else
5440                 devs=$(do_node $node $LCTL get_param -n osd-*.$FSNAME-M*.mntdev)
5441         fi
5442         for dev in $devs; do
5443                 case $dev in
5444                 *loop*) do_node $node "losetup $dev" | \
5445                                 sed -e "s/.*(//" -e "s/).*//" ;;
5446                 *) echo $dev ;;
5447                 esac
5448         done
5449 }
5450
5451 # Get all of the server target devices.
5452 get_svr_devs() {
5453         local node
5454         local i
5455
5456         # Master MDS parameters used by lfsck
5457         MDTNODE=$(facet_active_host $SINGLEMDS)
5458         MDTDEV=$(echo $(get_mnt_devs $MDTNODE mdt) | awk '{print $1}')
5459
5460         # MDT devices
5461         i=0
5462         for node in $(mdts_nodes); do
5463                 MDTDEVS[i]=$(get_mnt_devs $node mdt)
5464                 i=$((i + 1))
5465         done
5466
5467         # OST devices
5468         i=0
5469         for node in $(osts_nodes); do
5470                 OSTDEVS[i]=$(get_mnt_devs $node ost)
5471                 i=$((i + 1))
5472         done
5473 }
5474
5475 # Run e2fsck on MDT or OST device.
5476 run_e2fsck() {
5477         local node=$1
5478         local target_dev=$2
5479         local extra_opts=$3
5480         local cmd="$E2FSCK -d -v -t -t -f $extra_opts $target_dev"
5481         local log=$TMP/e2fsck.log
5482         local rc=0
5483
5484         echo $cmd
5485         do_node $node $cmd 2>&1 | tee $log
5486         rc=${PIPESTATUS[0]}
5487         if [ -n "$(grep "DNE mode isn't supported" $log)" ]; then
5488                 rm -f $log
5489                 if [ $MDSCOUNT -gt 1 ]; then
5490                         skip_noexit "DNE mode isn't supported!"
5491                         cleanupall
5492                         exit_status
5493                 else
5494                         error "It's not DNE mode."
5495                 fi
5496         fi
5497         rm -f $log
5498
5499         [ $rc -le $FSCK_MAX_ERR ] ||
5500                 error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
5501
5502         return 0
5503 }
5504
5505 #
5506 # Run resize2fs on MDT or OST device.
5507 #
5508 run_resize2fs() {
5509         local facet=$1
5510         local device=$2
5511         local size=$3
5512         shift 3
5513         local opts="$@"
5514
5515         do_facet $facet "$RESIZE2FS $opts $device $size"
5516 }
5517
5518 # verify a directory is shared among nodes.
5519 check_shared_dir() {
5520         local dir=$1
5521         local list=${2:-$(comma_list $(nodes_list))}
5522
5523         [ -z "$dir" ] && return 1
5524         do_rpc_nodes "$list" check_logdir $dir
5525         check_write_access $dir "$list" || return 1
5526         return 0
5527 }
5528
5529 run_lfsck() {
5530         do_nodes $(comma_list $(mdts_nodes) $(osts_nodes)) \
5531                 $LCTL set_param printk=+lfsck
5532         do_facet $SINGLEMDS "$LCTL lfsck_start -M $FSNAME-MDT0000 -r -A -t all"
5533
5534         for k in $(seq $MDSCOUNT); do
5535                 # wait up to 10+1 minutes for LFSCK to complete
5536                 wait_update_facet --verbose mds${k} "$LCTL get_param -n \
5537                         mdd.$(facet_svc mds${k}).lfsck_layout |
5538                         awk '/^status/ { print \\\$2 }'" "completed" 600 ||
5539                         error "MDS${k} layout isn't the expected 'completed'"
5540                 wait_update_facet --verbose mds${k} "$LCTL get_param -n \
5541                         mdd.$(facet_svc mds${k}).lfsck_namespace |
5542                         awk '/^status/ { print \\\$2 }'" "completed" 60 ||
5543                         error "MDS${k} namespace isn't the expected 'completed'"
5544         done
5545         local rep_mdt=$(do_nodes $(comma_list $(mdts_nodes)) \
5546                         $LCTL get_param -n mdd.$FSNAME-*.lfsck_* |
5547                         awk '/repaired/ { print $2 }' | calc_sum)
5548         local rep_ost=$(do_nodes $(comma_list $(osts_nodes)) \
5549                         $LCTL get_param -n obdfilter.$FSNAME-*.lfsck_* |
5550                         awk '/repaired/ { print $2 }' | calc_sum)
5551         local repaired=$((rep_mdt + rep_ost))
5552         [ $repaired -eq 0 ] ||
5553                 error "lfsck repaired $rep_mdt MDT and $rep_ost OST errors"
5554 }
5555
5556 dump_file_contents() {
5557         local nodes=$1
5558         local dir=$2
5559         local logname=$3
5560         local node
5561
5562         if [ -z "$nodes" -o -z "$dir" -o -z "$logname" ]; then
5563                 error_noexit false \
5564                         "Invalid parameters for dump_file_contents()"
5565                 return 1
5566         fi
5567         for node in ${nodes}; do
5568                 do_node $node "for i in \\\$(find $dir -type f); do
5569                                 echo ====\\\${i}=======================;
5570                                 cat \\\${i};
5571                                 done" >> ${logname}.${node}.log
5572         done
5573 }
5574
5575 dump_command_output() {
5576         local nodes=$1
5577         local cmd=$2
5578         local logname=$3
5579         local node
5580
5581         if [ -z "$nodes" -o -z "$cmd" -o -z "$logname" ]; then
5582                 error_noexit false \
5583                         "Invalid parameters for dump_command_output()"
5584                 return 1
5585         fi
5586
5587         for node in ${nodes}; do
5588                 do_node $node "echo ====${cmd}=======================;
5589                                 $cmd" >> ${logname}.${node}.log
5590         done
5591 }
5592
5593 log_zfs_info() {
5594         local logname=$1
5595
5596         # dump file contents from /proc/spl in case of zfs test
5597         if [ "$(facet_fstype ost1)" = "zfs" ]; then
5598                 dump_file_contents "$(osts_nodes)" "/proc/spl" "${logname}"
5599                 dump_command_output \
5600                         "$(osts_nodes)" "zpool events -v" "${logname}"
5601         fi
5602
5603         if [ "$(facet_fstype $SINGLEMDS)" = "zfs" ]; then
5604                 dump_file_contents "$(mdts_nodes)" "/proc/spl" "${logname}"
5605                 dump_command_output \
5606                         "$(mdts_nodes)" "zpool events -v" "${logname}"
5607         fi
5608 }
5609
5610 check_and_cleanup_lustre() {
5611         if [ "$LFSCK_ALWAYS" = "yes" -a "$TESTSUITE" != "sanity-lfsck" -a \
5612              "$TESTSUITE" != "sanity-scrub" ]; then
5613                 run_lfsck
5614         fi
5615
5616         if is_mounted $MOUNT; then
5617                 if $DO_CLEANUP; then
5618                         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]* ||
5619                                 error "remove sub-test dirs failed"
5620                 else
5621                         echo "skip cleanup"
5622                 fi
5623                 [ "$ENABLE_QUOTA" ] && restore_quota || true
5624         fi
5625
5626         if [ "$I_UMOUNTED2" = "yes" ]; then
5627                 restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
5628         fi
5629
5630         if [ "$I_MOUNTED2" = "yes" ]; then
5631                 cleanup_mount $MOUNT2
5632         fi
5633
5634         if [[ "$I_MOUNTED" = "yes" ]] && ! $AUSTER_CLEANUP; then
5635                 cleanupall -f || error "cleanup failed"
5636                 unset I_MOUNTED
5637         fi
5638 }
5639
5640 #######
5641 # General functions
5642
5643 wait_for_function () {
5644     local quiet=""
5645
5646     # suppress fn both stderr and stdout
5647     if [ "$1" = "--quiet" ]; then
5648         shift
5649         quiet=" > /dev/null 2>&1"
5650
5651     fi
5652
5653     local fn=$1
5654     local max=${2:-900}
5655     local sleep=${3:-5}
5656
5657     local wait=0
5658
5659     while true; do
5660
5661         eval $fn $quiet && return 0
5662
5663         wait=$((wait + sleep))
5664         [ $wait -lt $max ] || return 1
5665         echo waiting $fn, $((max - wait)) secs left ...
5666         sleep $sleep
5667     done
5668 }
5669
5670 check_network() {
5671         local host=$1
5672         local max=$2
5673         local sleep=${3:-5}
5674
5675         [ "$host" = "$HOSTNAME" ] && return 0
5676
5677         echo "$(date +'%H:%M:%S (%s)') waiting for $host network $max secs ..."
5678         if ! wait_for_function --quiet "ping -c 1 -w 3 $host" $max $sleep ; then
5679                 echo "Network not available!"
5680                 exit 1
5681         fi
5682
5683         echo "$(date +'%H:%M:%S (%s)') network interface is UP"
5684 }
5685
5686 no_dsh() {
5687     shift
5688     eval $@
5689 }
5690
5691 # Convert a space-delimited list to a comma-delimited list.  If the input is
5692 # only whitespace, ensure the output is empty (i.e. "") so [ -n $list ] works
5693 comma_list() {
5694         # echo is used to convert newlines to spaces, since it doesn't
5695         # introduce a trailing space as using "tr '\n' ' '" does
5696         echo $(tr -s " " "\n" <<< $* | sort -b -u) | tr ' ' ','
5697 }
5698
5699 list_member () {
5700     local list=$1
5701     local item=$2
5702     echo $list | grep -qw $item
5703 }
5704
5705 # list, excluded are the comma separated lists
5706 exclude_items_from_list () {
5707     local list=$1
5708     local excluded=$2
5709     local item
5710
5711     list=${list//,/ }
5712     for item in ${excluded//,/ }; do
5713         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
5714     done
5715     echo $(comma_list $list)
5716 }
5717
5718 # list, expand  are the comma separated lists
5719 expand_list () {
5720     local list=${1//,/ }
5721     local expand=${2//,/ }
5722     local expanded=
5723
5724     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
5725     echo $(comma_list $expanded)
5726 }
5727
5728 testslist_filter () {
5729     local script=$LUSTRE/tests/${TESTSUITE}.sh
5730
5731     [ -f $script ] || return 0
5732
5733     local start_at=$START_AT
5734     local stop_at=$STOP_AT
5735
5736     local var=${TESTSUITE//-/_}_START_AT
5737     [ x"${!var}" != x ] && start_at=${!var}
5738     var=${TESTSUITE//-/_}_STOP_AT
5739     [ x"${!var}" != x ] && stop_at=${!var}
5740
5741     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
5742         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
5743             /^'${start_at}'$/ {flag = 0}
5744             {if (flag == 1) print $0}
5745             /^'${stop_at}'$/ { flag = 1 }'
5746 }
5747
5748 absolute_path() {
5749     (cd `dirname $1`; echo $PWD/`basename $1`)
5750 }
5751
5752 get_facets () {
5753     local types=${1:-"OST MDS MGS"}
5754
5755     local list=""
5756
5757     for entry in $types; do
5758         local name=$(echo $entry | tr "[:upper:]" "[:lower:]")
5759         local type=$(echo $entry | tr "[:lower:]" "[:upper:]")
5760
5761         case $type in
5762                 MGS ) list="$list $name";;
5763             MDS|OST|AGT ) local count=${type}COUNT
5764                        for ((i=1; i<=${!count}; i++)) do
5765                           list="$list ${name}$i"
5766                       done;;
5767                   * ) error "Invalid facet type"
5768                  exit 1;;
5769         esac
5770     done
5771     echo $(comma_list $list)
5772 }
5773
5774 ##################################
5775 # Adaptive Timeouts funcs
5776
5777 at_is_enabled() {
5778     # only check mds, we assume at_max is the same on all nodes
5779     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
5780     if [ $at_max -eq 0 ]; then
5781         return 1
5782     else
5783         return 0
5784     fi
5785 }
5786
5787 at_get() {
5788     local facet=$1
5789     local at=$2
5790
5791     # suppose that all ost-s have the same $at value set
5792     [ $facet != "ost" ] || facet=ost1
5793
5794     do_facet $facet "lctl get_param -n $at"
5795 }
5796
5797 at_max_get() {
5798     at_get $1 at_max
5799 }
5800
5801 at_min_get() {
5802         at_get $1 at_min
5803 }
5804
5805 at_max_set() {
5806     local at_max=$1
5807     shift
5808
5809     local facet
5810     local hosts
5811     for facet in $@; do
5812         if [ $facet == "ost" ]; then
5813             facet=$(get_facets OST)
5814         elif [ $facet == "mds" ]; then
5815             facet=$(get_facets MDS)
5816         fi
5817         hosts=$(expand_list $hosts $(facets_hosts $facet))
5818     done
5819
5820     do_nodes $hosts lctl set_param at_max=$at_max
5821 }
5822
5823 ##################################
5824 # OBD_FAIL funcs
5825
5826 drop_request() {
5827 # OBD_FAIL_MDS_ALL_REQUEST_NET
5828     RC=0
5829     do_facet $SINGLEMDS lctl set_param fail_val=0 fail_loc=0x123
5830     do_facet client "$1" || RC=$?
5831     do_facet $SINGLEMDS lctl set_param fail_loc=0
5832     return $RC
5833 }
5834
5835 drop_reply() {
5836 # OBD_FAIL_MDS_ALL_REPLY_NET
5837         RC=0
5838         do_facet $SINGLEMDS $LCTL set_param fail_loc=0x122
5839         eval "$@" || RC=$?
5840         do_facet $SINGLEMDS $LCTL set_param fail_loc=0
5841         return $RC
5842 }
5843
5844 drop_reint_reply() {
5845 # OBD_FAIL_MDS_REINT_NET_REP
5846         RC=0
5847         do_facet $SINGLEMDS $LCTL set_param fail_loc=0x119
5848         eval "$@" || RC=$?
5849         do_facet $SINGLEMDS $LCTL set_param fail_loc=0
5850         return $RC
5851 }
5852
5853 drop_update_reply() {
5854 # OBD_FAIL_OUT_UPDATE_NET_REP
5855         local index=$1
5856         shift 1
5857         RC=0
5858         do_facet mds${index} lctl set_param fail_loc=0x1701
5859         do_facet client "$@" || RC=$?
5860         do_facet mds${index} lctl set_param fail_loc=0
5861         return $RC
5862 }
5863
5864 pause_bulk() {
5865 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
5866         RC=0
5867
5868         local timeout=${2:-0}
5869         # default is (obd_timeout / 4) if unspecified
5870         echo "timeout is $timeout/$2"
5871         do_facet ost1 lctl set_param fail_val=$timeout fail_loc=0x80000214
5872         do_facet client "$1" || RC=$?
5873         do_facet client "sync"
5874         do_facet ost1 lctl set_param fail_loc=0
5875         return $RC
5876 }
5877
5878 drop_ldlm_cancel() {
5879 #define OBD_FAIL_LDLM_CANCEL_NET                        0x304
5880         local RC=0
5881         local list=$(comma_list $(mdts_nodes) $(osts_nodes))
5882         do_nodes $list lctl set_param fail_loc=0x304
5883
5884         do_facet client "$@" || RC=$?
5885
5886         do_nodes $list lctl set_param fail_loc=0
5887         return $RC
5888 }
5889
5890 drop_bl_callback_once() {
5891         local rc=0
5892         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0
5893 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
5894         do_facet client lctl set_param fail_loc=0x80000305
5895         do_facet client "$@" || rc=$?
5896         do_facet client lctl set_param fail_loc=0
5897         do_facet client lctl set_param fail_val=0
5898         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1
5899         return $rc
5900 }
5901
5902 drop_bl_callback() {
5903         rc=0
5904         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0
5905 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
5906         do_facet client lctl set_param fail_loc=0x305
5907         do_facet client "$@" || rc=$?
5908         do_facet client lctl set_param fail_loc=0
5909         do_facet client lctl set_param fail_val=0
5910         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1
5911         return $rc
5912 }
5913
5914 drop_mdt_ldlm_reply() {
5915 #define OBD_FAIL_MDS_LDLM_REPLY_NET     0x157
5916     RC=0
5917     local list=$(comma_list $(mdts_nodes))
5918     do_nodes $list lctl set_param fail_loc=0x157
5919
5920     do_facet client "$@" || RC=$?
5921
5922     do_nodes $list lctl set_param fail_loc=0
5923     return $RC
5924 }
5925
5926 drop_mdt_ldlm_reply_once() {
5927 #define OBD_FAIL_MDS_LDLM_REPLY_NET     0x157
5928     RC=0
5929     local list=$(comma_list $(mdts_nodes))
5930     do_nodes $list lctl set_param fail_loc=0x80000157
5931
5932     do_facet client "$@" || RC=$?
5933
5934     do_nodes $list lctl set_param fail_loc=0
5935     return $RC
5936 }
5937
5938 clear_failloc() {
5939     facet=$1
5940     pause=$2
5941     sleep $pause
5942     echo "clearing fail_loc on $facet"
5943     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
5944 }
5945
5946 set_nodes_failloc () {
5947         local fv=${3:-0}
5948         do_nodes $(comma_list $1)  lctl set_param fail_val=$fv fail_loc=$2
5949 }
5950
5951 cancel_lru_locks() {
5952         #$LCTL mark "cancel_lru_locks $1 start"
5953         $LCTL set_param -n ldlm.namespaces.*$1*.lru_size=clear
5954         $LCTL get_param ldlm.namespaces.*$1*.lock_unused_count | grep -v '=0'
5955         #$LCTL mark "cancel_lru_locks $1 stop"
5956 }
5957
5958 default_lru_size()
5959 {
5960         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
5961         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
5962         echo "$DEFAULT_LRU_SIZE"
5963 }
5964
5965 lru_resize_enable()
5966 {
5967     lctl set_param ldlm.namespaces.*$1*.lru_size=0
5968 }
5969
5970 lru_resize_disable()
5971 {
5972     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
5973 }
5974
5975 flock_is_enabled()
5976 {
5977         local mountpath=${1:-$MOUNT}
5978         local RC=0
5979
5980         [ -z "$(mount | grep "$mountpath .*flock" | grep -v noflock)" ] && RC=1
5981         return $RC
5982 }
5983
5984 pgcache_empty() {
5985     local FILE
5986     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
5987         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
5988             echo there is still data in page cache $FILE ?
5989             lctl get_param -n $FILE
5990             return 1
5991         fi
5992     done
5993     return 0
5994 }
5995
5996 debugsave() {
5997         DEBUGSAVE="$(lctl get_param -n debug)"
5998         DEBUGSAVE_SERVER=$(do_facet $SINGLEMDS "$LCTL get_param -n debug")
5999 }
6000
6001 debugrestore() {
6002         [ -n "$DEBUGSAVE" ] &&
6003                 do_nodes $CLIENTS "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\""||
6004                 true
6005         DEBUGSAVE=""
6006
6007         [ -n "$DEBUGSAVE_SERVER" ] &&
6008                 do_nodes $(comma_list $(all_server_nodes)) \
6009                          "$LCTL set_param debug=\\\"${DEBUGSAVE_SERVER}\\\"" ||
6010                          true
6011         DEBUGSAVE_SERVER=""
6012 }
6013
6014 debug_size_save() {
6015     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
6016 }
6017
6018 debug_size_restore() {
6019     [ -n "$DEBUG_SIZE_SAVED" ] && \
6020         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
6021     DEBUG_SIZE_SAVED=""
6022 }
6023
6024 start_full_debug_logging() {
6025         debugsave
6026         debug_size_save
6027
6028         local fulldebug=-1
6029         local debug_size=150
6030         local nodes=$(comma_list $(nodes_list))
6031
6032         do_nodes $nodes "$LCTL set_param debug=$fulldebug debug_mb=$debug_size"
6033 }
6034
6035 stop_full_debug_logging() {
6036         debug_size_restore
6037         debugrestore
6038 }
6039
6040 # prints bash call stack
6041 print_stack_trace() {
6042         local skip=${1:-1}
6043         echo "  Trace dump:"
6044         for (( i=$skip; i < ${#BASH_LINENO[*]} ; i++ )) ; do
6045                 local src=${BASH_SOURCE[$i]}
6046                 local lineno=${BASH_LINENO[$i-1]}
6047                 local funcname=${FUNCNAME[$i]}
6048                 echo "  = $src:$lineno:$funcname()"
6049         done
6050 }
6051
6052 report_error() {
6053         local TYPE=${TYPE:-"FAIL"}
6054
6055         local dump=true
6056         # do not dump logs if $1=false
6057         if [ "x$1" = "xfalse" ]; then
6058                 shift
6059                 dump=false
6060         fi
6061
6062         log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
6063         (print_stack_trace 2) >&2
6064         mkdir -p $LOGDIR
6065         # We need to dump the logs on all nodes
6066         if $dump; then
6067                 gather_logs $(comma_list $(nodes_list))
6068         fi
6069
6070         debugrestore
6071         [ "$TESTSUITELOG" ] &&
6072                 echo "$TESTSUITE: $TYPE: $TESTNAME $@" >> $TESTSUITELOG
6073         if [ -z "$*" ]; then
6074                 echo "error() without useful message, please fix" > $LOGDIR/err
6075         else
6076                 if [[ `echo $TYPE | grep ^IGNORE` ]]; then
6077                         echo "$@" > $LOGDIR/ignore
6078                 else
6079                         echo "$@" > $LOGDIR/err
6080                 fi
6081         fi
6082
6083         # cleanup the env for failed tests
6084         reset_fail_loc
6085 }
6086
6087 ##################################
6088 # Test interface
6089 ##################################
6090
6091 # usage: stack_trap arg sigspec
6092 #
6093 # stack_trap() behaves like bash's built-in trap, except that it "stacks" the
6094 # command "arg" on top of previously defined commands for "sigspec" instead
6095 # of overwriting them.
6096 # stacked traps are executed in reverse order of their registration
6097 #
6098 # arg and sigspec have the same meaning as in man (1) trap
6099 stack_trap()
6100 {
6101         local arg="$1"
6102         local sigspec="${2:-EXIT}"
6103
6104         # Use "trap -p" to get the quoting right
6105         local old_trap="$(trap -p "$sigspec")"
6106         # Append ";" and remove the leading "trap -- '" added by "trap -p"
6107         old_trap="${old_trap:+"; ${old_trap#trap -- \'}"}"
6108
6109         # Once again, use "trap -p" to get the quoting right
6110         local new_trap="$(trap -- "$arg" "$sigspec"
6111                           trap -p "$sigspec"
6112                           trap -- '' "$sigspec")"
6113
6114         # Remove the trailing "' $sigspec" part added by "trap -p" and merge
6115         #
6116         # The resulting string should be safe to "eval" as it is (supposedly
6117         # correctly) quoted by "trap -p"
6118         eval "${new_trap%\' $sigspec}${old_trap:-"' $sigspec"}"
6119 }
6120
6121 error_noexit() {
6122         report_error "$@"
6123 }
6124
6125 exit_status () {
6126         local status=0
6127         local log=$TESTSUITELOG
6128
6129         [ -f "$log" ] && grep -qw FAIL $log && status=1
6130         exit $status
6131 }
6132
6133 error() {
6134         report_error "$@"
6135         exit 1
6136 }
6137
6138 error_exit() {
6139         report_error "$@"
6140         exit 1
6141 }
6142
6143 # use only if we are ignoring failures for this test, bugno required.
6144 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
6145 # e.g. error_ignore bz5494 "your message" or
6146 # error_ignore LU-5494 "your message"
6147 error_ignore() {
6148         local TYPE="IGNORE ($1)"
6149         shift
6150         report_error "$@"
6151 }
6152
6153 error_and_remount() {
6154         report_error "$@"
6155         remount_client $MOUNT
6156         exit 1
6157 }
6158
6159 # Throw an error if it's not running in vm - usually for performance
6160 # verification
6161 error_not_in_vm() {
6162         local virt=$(running_in_vm)
6163         if [[ -n "$virt" ]]; then
6164                 echo "running in VM '$virt', ignore error"
6165                 error_ignore env=$virt "$@"
6166         else
6167                 error "$@"
6168         fi
6169 }
6170
6171 #
6172 # Function: skip_env()
6173 # Purpose:  to skip a test during developer testing because some tool
6174 #           is missing, but fail the test in release testing because the test
6175 #           environment is not configured properly".
6176 #
6177 skip_env () {
6178         $FAIL_ON_SKIP_ENV && error false $@ || skip $@
6179 }
6180
6181 skip_noexit() {
6182         echo
6183         log " SKIP: $TESTSUITE $TESTNAME $@"
6184
6185         if [[ -n "$ALWAYS_SKIPPED" ]]; then
6186                 skip_logged $TESTNAME "$@"
6187         else
6188                 mkdir -p $LOGDIR
6189                 echo "$@" > $LOGDIR/skip
6190         fi
6191
6192         [[ -n "$TESTSUITELOG" ]] &&
6193                 echo "$TESTSUITE: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
6194         unset TESTNAME
6195 }
6196
6197 skip() {
6198         skip_noexit $@
6199         exit 0
6200 }
6201
6202 build_test_filter() {
6203         EXCEPT="$EXCEPT $(testslist_filter)"
6204
6205         for O in $ONLY; do
6206                 if [[ $O = [0-9]*-[0-9]* ]]; then
6207                         for num in $(seq $(echo $O | tr '-' ' ')); do
6208                                 eval ONLY_$num=true
6209                         done
6210                 else
6211                         eval ONLY_${O}=true
6212                 fi
6213         done
6214
6215     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
6216         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
6217     [ "$EXCEPT_SLOW" ] && \
6218         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
6219     for E in $EXCEPT; do
6220         eval EXCEPT_${E}=true
6221     done
6222     for E in $ALWAYS_EXCEPT; do
6223         eval EXCEPT_ALWAYS_${E}=true
6224     done
6225     for E in $EXCEPT_SLOW; do
6226         eval EXCEPT_SLOW_${E}=true
6227     done
6228     for G in $GRANT_CHECK_LIST; do
6229         eval GCHECK_ONLY_${G}=true
6230         done
6231 }
6232
6233 basetest() {
6234     if [[ $1 = [a-z]* ]]; then
6235         echo $1
6236     else
6237         echo ${1%%[a-zA-Z]*}
6238     fi
6239 }
6240
6241 # print a newline if the last test was skipped
6242 export LAST_SKIPPED=
6243 export ALWAYS_SKIPPED=
6244 #
6245 # Main entry into test-framework. This is called with the number and
6246 # description of a test. The number is used to find the function to run
6247 # the test using "test_$name".
6248 #
6249 # This supports a variety of methods of specifying specific test to
6250 # run or not run:
6251 # - ONLY= env variable with space-separated list of test numbers to run
6252 # - EXCEPT= env variable with space-separated list of test numbers to exclude
6253 #
6254 run_test() {
6255         assert_DIR
6256         local testnum=$1
6257         local testmsg=$2
6258         export base=$(basetest $testnum)
6259         export TESTNAME=test_$testnum
6260         LAST_SKIPPED=
6261         ALWAYS_SKIPPED=
6262
6263         # Check the EXCEPT, ALWAYS_EXCEPT and SLOW lists to see if we
6264         # need to skip the current test. If so, set the ALWAYS_SKIPPED flag.
6265         local isexcept=EXCEPT_$testnum
6266         local isexcept_base=EXCEPT_$base
6267         if [ ${!isexcept}x != x ]; then
6268                 ALWAYS_SKIPPED="y"
6269                 skip_message="skipping excluded test $testnum"
6270         elif [ ${!isexcept_base}x != x ]; then
6271                 ALWAYS_SKIPPED="y"
6272                 skip_message="skipping excluded test $testnum (base $base)"
6273         fi
6274
6275         isexcept=EXCEPT_ALWAYS_$testnum
6276         isexcept_base=EXCEPT_ALWAYS_$base
6277         if [ ${!isexcept}x != x ]; then
6278                 ALWAYS_SKIPPED="y"
6279                 skip_message="skipping ALWAYS excluded test $testnum"
6280         elif [ ${!isexcept_base}x != x ]; then
6281                 ALWAYS_SKIPPED="y"
6282                 skip_message="skipping ALWAYS excluded test $testnum (base $base)"
6283         fi
6284
6285         isexcept=EXCEPT_SLOW_$testnum
6286         isexcept_base=EXCEPT_SLOW_$base
6287         if [ ${!isexcept}x != x ]; then
6288                 ALWAYS_SKIPPED="y"
6289                 skip_message="skipping SLOW test $testnum"
6290         elif [ ${!isexcept_base}x != x ]; then
6291                 ALWAYS_SKIPPED="y"
6292                 skip_message="skipping SLOW test $testnum (base $base)"
6293         fi
6294
6295         # If there are tests on the ONLY list, check if the current test
6296         # is on that list and, if so, check if the test is to be skipped
6297         # and if we are supposed to honor the skip lists.
6298         if [ -n "$ONLY" ]; then
6299                 local isonly=ONLY_$testnum
6300                 local isonly_base=ONLY_$base
6301                 if [[ ${!isonly}x != x || ${!isonly_base}x != x ]]; then
6302
6303                         if [[ -n "$ALWAYS_SKIPPED" && -n "$HONOR_EXCEPT" ]]; then
6304                                 LAST_SKIPPED="y"
6305                                 skip_noexit "$skip_message"
6306                                 return 0
6307                         else
6308                                 [ -n "$LAST_SKIPPED" ] &&
6309                                         echo "" && LAST_SKIPPED=
6310                                 ALWAYS_SKIPPED=
6311                                 run_one_logged $testnum "$testmsg"
6312                                 return $?
6313                         fi
6314
6315                 else
6316                         LAST_SKIPPED="y"
6317                         return 0
6318                 fi
6319         fi
6320
6321         if [ -n "$ALWAYS_SKIPPED" ]; then
6322                 LAST_SKIPPED="y"
6323                 skip_noexit "$skip_message"
6324                 return 0
6325         else
6326                 run_one_logged $testnum "$testmsg"
6327                 return $?
6328         fi
6329 }
6330
6331 log() {
6332         echo "$*" >&2
6333         load_module ../libcfs/libcfs/libcfs
6334
6335     local MSG="$*"
6336     # Get rid of '
6337     MSG=${MSG//\'/\\\'}
6338     MSG=${MSG//\(/\\\(}
6339     MSG=${MSG//\)/\\\)}
6340     MSG=${MSG//\;/\\\;}
6341     MSG=${MSG//\|/\\\|}
6342     MSG=${MSG//\>/\\\>}
6343     MSG=${MSG//\</\\\<}
6344     MSG=${MSG//\//\\\/}
6345     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
6346 }
6347
6348 trace() {
6349         log "STARTING: $*"
6350         strace -o $TMP/$1.strace -ttt $*
6351         RC=$?
6352         log "FINISHED: $*: rc $RC"
6353         return 1
6354 }
6355
6356 complete () {
6357     local duration=$1
6358
6359     banner test complete, duration $duration sec
6360     [ -f "$TESTSUITELOG" ] && egrep .FAIL $TESTSUITELOG || true
6361     echo duration $duration >>$TESTSUITELOG
6362 }
6363
6364 pass() {
6365         # Set TEST_STATUS here. It will be used for logging the result.
6366         TEST_STATUS="PASS"
6367
6368         if [[ -f $LOGDIR/err ]]; then
6369                 TEST_STATUS="FAIL"
6370         elif [[ -f $LOGDIR/skip ]]; then
6371                 TEST_STATUS="SKIP"
6372         fi
6373         echo "$TEST_STATUS $@" 2>&1 | tee -a $TESTSUITELOG
6374 }
6375
6376 check_mds() {
6377     local FFREE=$(do_node $SINGLEMDS \
6378         lctl get_param -n osd*.*MDT*.filesfree | calc_sum)
6379     local FTOTAL=$(do_node $SINGLEMDS \
6380         lctl get_param -n osd*.*MDT*.filestotal | calc_sum)
6381
6382     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
6383 }
6384
6385 reset_fail_loc () {
6386         echo -n "Resetting fail_loc on all nodes..."
6387         do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 \
6388             fail_val=0 2>/dev/null" || true
6389         echo done.
6390 }
6391
6392
6393 #
6394 # Log a message (on all nodes) padded with "=" before and after.
6395 # Also appends a timestamp and prepends the testsuite name.
6396 #
6397
6398 EQUALS="===================================================================================================="
6399 banner() {
6400     msg="== ${TESTSUITE} $*"
6401     last=${msg: -1:1}
6402     [[ $last != "=" && $last != " " ]] && msg="$msg "
6403     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
6404     # always include at least == after the message
6405     log "$msg== $(date +"%H:%M:%S (%s)")"
6406 }
6407
6408 check_dmesg_for_errors() {
6409         local res
6410         local errors="VFS: Busy inodes after unmount of\|\
6411 ldiskfs_check_descriptors: Checksum for group 0 failed\|\
6412 group descriptors corrupted"
6413
6414         res=$(do_nodes $(comma_list $(nodes_list)) "dmesg" | grep "$errors")
6415         [ -z "$res" ] && return 0
6416         echo "Kernel error detected: $res"
6417         return 1
6418 }
6419
6420 #
6421 # Run a single test function and cleanup after it.
6422 #
6423 # This function should be run in a subshell so the test func can
6424 # exit() without stopping the whole script.
6425 #
6426 run_one() {
6427         local testnum=$1
6428         local testmsg="$2"
6429         local SAVE_UMASK=`umask`
6430         umask 0022
6431
6432         if ! grep -q $DIR /proc/mounts; then
6433                 $SETUP
6434         fi
6435
6436         banner "test $testnum: $testmsg"
6437         test_${testnum} || error "test_$testnum failed with $?"
6438         cd $SAVE_PWD
6439         reset_fail_loc
6440         check_grant ${testnum} || error "check_grant $testnum failed with $?"
6441         check_node_health
6442         check_dmesg_for_errors || error "Error in dmesg detected"
6443         if [ "$PARALLEL" != "yes" ]; then
6444                 ps auxww | grep -v grep | grep -q "multiop " &&
6445                                         error "multiop still running"
6446         fi
6447         umask $SAVE_UMASK
6448         $CLEANUP
6449         return 0
6450 }
6451
6452 #
6453 # Wrapper around run_one to ensure:
6454 #  - test runs in subshell
6455 #  - output of test is saved to separate log file for error reporting
6456 #  - test result is saved to data file
6457 #
6458 run_one_logged() {
6459         local before=$SECONDS
6460         local testnum=$1
6461         local testmsg=$2
6462         export tfile=f${testnum}.${TESTSUITE}
6463         export tdir=d${testnum}.${TESTSUITE}
6464         local name=$TESTSUITE.$TESTNAME.test_log.$(hostname -s).log
6465         local test_log=$LOGDIR/$name
6466         local zfs_log_name=$TESTSUITE.$TESTNAME.zfs_log
6467         local zfs_debug_log=$LOGDIR/$zfs_log_name
6468         local SAVE_UMASK=$(umask)
6469         local rc=0
6470         umask 0022
6471
6472         rm -f $LOGDIR/err $LOGDIR/ignore $LOGDIR/skip
6473         echo
6474         # if ${ONLY_$testnum} set, repeat $ONLY_REPEAT times, otherwise once
6475         local isonly=ONLY_$testnum
6476         local repeat=${!isonly:+$ONLY_REPEAT}
6477
6478         for testiter in $(seq ${repeat:-1}); do
6479                 local before_sub=$SECONDS
6480                 log_sub_test_begin $TESTNAME
6481
6482                 # remove temp files between repetitions to avoid test failures
6483                 [ -n "$append" -a -n "$DIR" -a -n "$tdir" -a -n "$tfile" ] &&
6484                         rm -rf $DIR/$tdir* $DIR/$tfile*
6485                 # loop around subshell so stack_trap EXIT triggers each time
6486                 (run_one $testnum "$testmsg") 2>&1 | tee -i $append $test_log
6487                 rc=${PIPESTATUS[0]}
6488                 local append=-a
6489                 local duration_sub=$((SECONDS - before_sub))
6490                 local test_error
6491
6492                 [[ $rc != 0 && ! -f $LOGDIR/err ]] &&
6493                         echo "$TESTNAME returned $rc" | tee $LOGDIR/err
6494
6495                 if [[ -f $LOGDIR/err ]]; then
6496                         test_error=$(cat $LOGDIR/err)
6497                         TEST_STATUS="FAIL"
6498                 elif [[ -f $LOGDIR/ignore ]]; then
6499                         test_error=$(cat $LOGDIR/ignore)
6500                 elif [[ -f $LOGDIR/skip ]]; then
6501                         test_error=$(cat $LOGDIR/skip)
6502                         TEST_STATUS="SKIP"
6503                 else
6504                         TEST_STATUS="PASS"
6505                 fi
6506
6507                 pass "$testnum" "($((SECONDS - before))s)"
6508                 log_sub_test_end $TEST_STATUS $duration_sub "$rc" "$test_error"
6509                 [[ $rc != 0 ]] && break
6510         done
6511
6512         if [[ "$TEST_STATUS" != "SKIP" && -f $TF_SKIP ]]; then
6513                 rm -f $TF_SKIP
6514         fi
6515
6516         if [ -f $LOGDIR/err ]; then
6517                 log_zfs_info "$zfs_debug_log"
6518                 $FAIL_ON_ERROR && exit $rc
6519         fi
6520
6521         umask $SAVE_UMASK
6522
6523         unset TESTNAME
6524         unset tdir
6525         unset tfile
6526
6527         return 0
6528 }
6529
6530 #
6531 # Print information of skipped tests to result.yml
6532 #
6533 skip_logged(){
6534         log_sub_test_begin $1
6535         shift
6536         log_sub_test_end "SKIP" "0" "0" "$@"
6537 }
6538
6539 canonical_path() {
6540         (cd $(dirname $1); echo $PWD/$(basename $1))
6541 }
6542
6543
6544 check_grant() {
6545         export base=$(basetest $1)
6546         [ "$CHECK_GRANT" == "no" ] && return 0
6547
6548         local isonly_base=GCHECK_ONLY_${base}
6549         local isonly=GCHECK_ONLY_$1
6550         [ ${!isonly_base}x == x -a ${!isonly}x == x ] && return 0
6551
6552         echo -n "checking grant......"
6553
6554         local clients=$CLIENTS
6555         [ -z "$clients" ] && clients=$(hostname)
6556
6557         # sync all the data and make sure no pending data on server
6558         do_nodes $clients sync
6559         clients_up # initiate all idling connections
6560
6561         # get client grant
6562         client_grant=$(do_nodes $clients \
6563                 "$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes" |
6564                 awk '{ total += $1 } END { printf("%0.0f", total) }')
6565
6566         # get server grant
6567         # which is tot_granted less grant_precreate
6568         server_grant=$(do_nodes $(comma_list $(osts_nodes)) \
6569                 "$LCTL get_param "\
6570                 "obdfilter.${FSNAME}-OST*.{tot_granted,tot_pending,grant_precreate}" |
6571                 sed 's/=/ /'| awk '/tot_granted/{ total += $2 };
6572                                 /tot_pending/{ total -= $2 };
6573                                 /grant_precreate/{ total -= $2 };
6574                                 END { printf("%0.0f", total) }')
6575
6576         # check whether client grant == server grant
6577         if [[ $client_grant -ne $server_grant ]]; then
6578                 do_nodes $(comma_list $(osts_nodes)) \
6579                         "$LCTL get_param obdfilter.${FSNAME}-OST*.tot*" \
6580                         "obdfilter.${FSNAME}-OST*.grant_*"
6581                 do_nodes $clients "$LCTL get_param osc.${FSNAME}-*.cur_*_bytes"
6582                 error "failed: client:${client_grant} server: ${server_grant}."
6583         else
6584                 echo "pass: client:${client_grant} server: ${server_grant}"
6585         fi
6586 }
6587
6588 ########################
6589 # helper functions
6590
6591 osc_to_ost()
6592 {
6593     osc=$1
6594     ost=`echo $1 | awk -F_ '{print $3}'`
6595     if [ -z $ost ]; then
6596         ost=`echo $1 | sed 's/-osc.*//'`
6597     fi
6598     echo $ost
6599 }
6600
6601 ostuuid_from_index()
6602 {
6603     $LFS osts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
6604 }
6605
6606 ostname_from_index() {
6607     local uuid=$(ostuuid_from_index $1)
6608     echo ${uuid/_UUID/}
6609 }
6610
6611 index_from_ostuuid()
6612 {
6613     $LFS osts $2 | sed -ne "/${1}/s/\(.*\): .* .*$/\1/p"
6614 }
6615
6616 mdtuuid_from_index()
6617 {
6618     $LFS mdts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
6619 }
6620
6621 # Description:
6622 #   Return unique identifier for given hostname
6623 host_id() {
6624         local host_name=$1
6625         echo $host_name | md5sum | cut -d' ' -f1
6626 }
6627
6628 # Description:
6629 #   Returns list of ip addresses for each interface
6630 local_addr_list() {
6631         ip addr | awk '/inet\ / {print $2}' | awk -F\/ '{print $1}'
6632 }
6633
6634 is_local_addr() {
6635         local addr=$1
6636         # Cache address list to avoid mutiple execution of local_addr_list
6637         LOCAL_ADDR_LIST=${LOCAL_ADDR_LIST:-$(local_addr_list)}
6638         local i
6639         for i in $LOCAL_ADDR_LIST ; do
6640                 [[ "$i" == "$addr" ]] && return 0
6641         done
6642         return 1
6643 }
6644
6645 local_node() {
6646         local host_name=$1
6647         local is_local="IS_LOCAL_$(host_id $host_name)"
6648         if [ -z "${!is_local-}" ] ; then
6649                 eval $is_local=0
6650                 local host_ip=$($LUSTRE/tests/resolveip $host_name)
6651                 is_local_addr "$host_ip" && eval $is_local=1
6652         fi
6653         [[ "${!is_local}" == "1" ]]
6654 }
6655
6656 remote_node () {
6657         local node=$1
6658         local_node $node && return 1
6659         return 0
6660 }
6661
6662 remote_mds ()
6663 {
6664     local node
6665     for node in $(mdts_nodes); do
6666         remote_node $node && return 0
6667     done
6668     return 1
6669 }
6670
6671 remote_mds_nodsh()
6672 {
6673         [ -n "$CLIENTONLY" ] && return 0 || true
6674         remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
6675 }
6676
6677 require_dsh_mds()
6678 {
6679         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" &&
6680                 MSKIPPED=1 && return 1
6681         return 0
6682 }
6683
6684 remote_ost ()
6685 {
6686     local node
6687     for node in $(osts_nodes) ; do
6688         remote_node $node && return 0
6689     done
6690     return 1
6691 }
6692
6693 remote_ost_nodsh()
6694 {
6695         [ -n "$CLIENTONLY" ] && return 0 || true
6696         remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
6697 }
6698
6699 require_dsh_ost()
6700 {
6701         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
6702             OSKIPPED=1 && return 1
6703         return 0
6704 }
6705
6706 remote_mgs_nodsh()
6707 {
6708         [ -n "$CLIENTONLY" ] && return 0 || true
6709         local MGS
6710         MGS=$(facet_host mgs)
6711         remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
6712 }
6713
6714 local_mode ()
6715 {
6716     remote_mds_nodsh || remote_ost_nodsh || \
6717         $(single_local_node $(comma_list $(nodes_list)))
6718 }
6719
6720 remote_servers () {
6721     remote_ost && remote_mds
6722 }
6723
6724 # Get the active nodes for facets.
6725 facets_nodes () {
6726         local facets=$1
6727         local facet
6728         local nodes
6729         local nodes_sort
6730         local i
6731
6732         for facet in ${facets//,/ }; do
6733                 nodes="$nodes $(facet_active_host $facet)"
6734         done
6735
6736         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
6737         echo -n $nodes_sort
6738 }
6739
6740 # Get name of the active MGS node.
6741 mgs_node () {
6742         echo -n $(facets_nodes $(get_facets MGS))
6743 }
6744
6745 # Get all of the active MDS nodes.
6746 mdts_nodes () {
6747         echo -n $(facets_nodes $(get_facets MDS))
6748 }
6749
6750 # Get all of the active OSS nodes.
6751 osts_nodes () {
6752         echo -n $(facets_nodes $(get_facets OST))
6753 }
6754
6755 # Get all of the active AGT (HSM agent) nodes.
6756 agts_nodes () {
6757         echo -n $(facets_nodes $(get_facets AGT))
6758 }
6759
6760 # Get all of the client nodes and active server nodes.
6761 nodes_list () {
6762         local nodes=$HOSTNAME
6763         local nodes_sort
6764         local i
6765
6766         # CLIENTS (if specified) contains the local client
6767         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
6768
6769         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
6770                 nodes="$nodes $(facets_nodes $(get_facets))"
6771         fi
6772
6773         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
6774         echo -n $nodes_sort
6775 }
6776
6777 # Get all of the remote client nodes and remote active server nodes.
6778 remote_nodes_list () {
6779         echo -n $(nodes_list) | sed -re "s/\<$HOSTNAME\>//g"
6780 }
6781
6782 # Get all of the MDS nodes, including active and passive nodes.
6783 all_mdts_nodes () {
6784         local host
6785         local failover_host
6786         local nodes
6787         local nodes_sort
6788         local i
6789
6790         for i in $(seq $MDSCOUNT); do
6791                 host=mds${i}_HOST
6792                 failover_host=mds${i}failover_HOST
6793                 nodes="$nodes ${!host} ${!failover_host}"
6794         done
6795
6796         [ -n "$nodes" ] || nodes="${mds_HOST} ${mdsfailover_HOST}"
6797         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
6798         echo -n $nodes_sort
6799 }
6800
6801 # Get all of the OSS nodes, including active and passive nodes.
6802 all_osts_nodes () {
6803         local host
6804         local failover_host
6805         local nodes=
6806         local nodes_sort
6807         local i
6808
6809         for i in $(seq $OSTCOUNT); do
6810                 host=ost${i}_HOST
6811                 failover_host=ost${i}failover_HOST
6812                 nodes="$nodes ${!host} ${!failover_host}"
6813         done
6814
6815         [ -n "$nodes" ] || nodes="${ost_HOST} ${ostfailover_HOST}"
6816         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
6817         echo -n $nodes_sort
6818 }
6819
6820 # Get all of the server nodes, including active and passive nodes.
6821 all_server_nodes () {
6822         local nodes
6823         local nodes_sort
6824         local i
6825
6826         nodes="$mgs_HOST $mgsfailover_HOST $(all_mdts_nodes) $(all_osts_nodes)"
6827
6828         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
6829         echo -n $nodes_sort
6830 }
6831
6832 # Get all of the client and server nodes, including active and passive nodes.
6833 all_nodes () {
6834         local nodes=$HOSTNAME
6835         local nodes_sort
6836         local i
6837
6838         # CLIENTS (if specified) contains the local client
6839         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
6840
6841         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
6842                 nodes="$nodes $(all_server_nodes)"
6843         fi
6844
6845         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
6846         echo -n $nodes_sort
6847 }
6848
6849 init_clients_lists () {
6850     # Sanity check: exclude the local client from RCLIENTS
6851     local clients=$(hostlist_expand "$RCLIENTS")
6852     local rclients=$(exclude_items_from_list "$clients" $HOSTNAME)
6853
6854     # Sanity check: exclude the dup entries
6855     RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)
6856
6857     clients="$SINGLECLIENT $HOSTNAME $RCLIENTS"
6858
6859     # Sanity check: exclude the dup entries from CLIENTS
6860     # for those configs which has SINGLCLIENT set to local client
6861     clients=$(for i in $clients; do echo $i; done | sort -u)
6862
6863     CLIENTS=$(comma_list $clients)
6864     local -a remoteclients=($RCLIENTS)
6865     for ((i=0; $i<${#remoteclients[@]}; i++)); do
6866             varname=CLIENT$((i + 2))
6867             eval $varname=${remoteclients[i]}
6868     done
6869
6870     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
6871 }
6872
6873 get_random_entry () {
6874     local rnodes=$1
6875
6876     rnodes=${rnodes//,/ }
6877
6878     local -a nodes=($rnodes)
6879     local num=${#nodes[@]}
6880     local i=$((RANDOM * num * 2 / 65536))
6881
6882     echo ${nodes[i]}
6883 }
6884
6885 client_only () {
6886         [ -n "$CLIENTONLY" ] || [ "x$CLIENTMODSONLY" = "xyes" ]
6887 }
6888
6889 check_versions () {
6890     [ "$(lustre_version_code client)" = "$(lustre_version_code $SINGLEMDS)" -a \
6891       "$(lustre_version_code client)" = "$(lustre_version_code ost1)" ]
6892 }
6893
6894 get_node_count() {
6895     local nodes="$@"
6896     echo $nodes | wc -w || true
6897 }
6898
6899 mixed_ost_devs () {
6900     local nodes=$(osts_nodes)
6901     local osscount=$(get_node_count "$nodes")
6902     [ ! "$OSTCOUNT" = "$osscount" ]
6903 }
6904
6905 mixed_mdt_devs () {
6906     local nodes=$(mdts_nodes)
6907     local mdtcount=$(get_node_count "$nodes")
6908     [ ! "$MDSCOUNT" = "$mdtcount" ]
6909 }
6910
6911 generate_machine_file() {
6912     local nodes=${1//,/ }
6913     local machinefile=$2
6914     rm -f $machinefile
6915     for node in $nodes; do
6916         echo $node >>$machinefile || \
6917             { echo "can not generate machinefile $machinefile" && return 1; }
6918     done
6919 }
6920
6921 get_stripe () {
6922         local file=$1/stripe
6923
6924         touch $file
6925         $LFS getstripe -v $file || error "getstripe $file failed"
6926         rm -f $file
6927 }
6928
6929 setstripe_nfsserver () {
6930         local dir=$1
6931         local nfsexportdir=$2
6932         shift
6933         shift
6934
6935         local -a nfsexport=($(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
6936                 { print $1 }' /proc/mounts | cut -f 1 -d :))
6937
6938         # check that only one nfs mounted
6939         [[ -z $nfsexport ]] && echo "$dir is not nfs mounted" && return 1
6940         (( ${#nfsexport[@]} == 1 )) ||
6941                 error "several nfs mounts found for $dir: ${nfsexport[@]} !"
6942
6943         do_nodev ${nfsexport[0]} lfs setstripe $nfsexportdir "$@"
6944 }
6945
6946 # Check and add a test group.
6947 add_group() {
6948         local group_id=$1
6949         local group_name=$2
6950         local rc=0
6951
6952         local gid=$(getent group $group_name | cut -d: -f3)
6953         if [[ -n "$gid" ]]; then
6954                 [[ "$gid" -eq "$group_id" ]] || {
6955                         error_noexit "inconsistent group ID:" \
6956                                      "new: $group_id, old: $gid"
6957                         rc=1
6958                 }
6959         else
6960                 groupadd -g $group_id $group_name
6961                 rc=${PIPESTATUS[0]}
6962         fi
6963
6964         return $rc
6965 }
6966
6967 # Check and add a test user.
6968 add_user() {
6969         local user_id=$1
6970         shift
6971         local user_name=$1
6972         shift
6973         local group_name=$1
6974         shift
6975         local home=$1
6976         shift
6977         local opts="$@"
6978         local rc=0
6979
6980         local uid=$(getent passwd $user_name | cut -d: -f3)
6981         if [[ -n "$uid" ]]; then
6982                 if [[ "$uid" -eq "$user_id" ]]; then
6983                         local dir=$(getent passwd $user_name | cut -d: -f6)
6984                         if [[ "$dir" != "$home" ]]; then
6985                                 mkdir -p $home
6986                                 usermod -d $home $user_name
6987                                 rc=${PIPESTATUS[0]}
6988                         fi
6989                 else
6990                         error_noexit "inconsistent user ID:" \
6991                                      "new: $user_id, old: $uid"
6992                         rc=1
6993                 fi
6994         else
6995                 mkdir -p $home
6996                 useradd -M -u $user_id -d $home -g $group_name $opts $user_name
6997                 rc=${PIPESTATUS[0]}
6998         fi
6999
7000         return $rc
7001 }
7002
7003 check_runas_id_ret() {
7004     local myRC=0
7005     local myRUNAS_UID=$1
7006     local myRUNAS_GID=$2
7007     shift 2
7008     local myRUNAS=$@
7009     if [ -z "$myRUNAS" ]; then
7010         error_exit "myRUNAS command must be specified for check_runas_id"
7011     fi
7012     if $GSS_KRB5; then
7013         $myRUNAS krb5_login.sh || \
7014             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
7015     fi
7016     mkdir $DIR/d0_runas_test
7017     chmod 0755 $DIR
7018     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
7019     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
7020     rm -rf $DIR/d0_runas_test
7021     return $myRC
7022 }
7023
7024 check_runas_id() {
7025     local myRUNAS_UID=$1
7026     local myRUNAS_GID=$2
7027     shift 2
7028     local myRUNAS=$@
7029     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
7030         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
7031         Please set RUNAS_ID to some UID which exists on MDS and client or
7032         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
7033 }
7034
7035 # obtain the UID/GID for MPI_USER
7036 get_mpiuser_id() {
7037     local mpi_user=$1
7038
7039     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
7040 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
7041
7042     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
7043 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
7044 }
7045
7046 # obtain and cache Kerberos ticket-granting ticket
7047 refresh_krb5_tgt() {
7048     local myRUNAS_UID=$1
7049     local myRUNAS_GID=$2
7050     shift 2
7051     local myRUNAS=$@
7052     if [ -z "$myRUNAS" ]; then
7053         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
7054     fi
7055
7056     CLIENTS=${CLIENTS:-$HOSTNAME}
7057     do_nodes $CLIENTS "set -x
7058 if ! $myRUNAS krb5_login.sh; then
7059     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
7060     exit 1
7061 fi"
7062 }
7063
7064 # Run multiop in the background, but wait for it to print
7065 # "PAUSING" to its stdout before returning from this function.
7066 multiop_bg_pause() {
7067     MULTIOP_PROG=${MULTIOP_PROG:-$MULTIOP}
7068     FILE=$1
7069     ARGS=$2
7070
7071     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
7072     mkfifo $TMPPIPE
7073
7074     echo "$MULTIOP_PROG $FILE v$ARGS"
7075     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
7076
7077     echo "TMPPIPE=${TMPPIPE}"
7078     read -t 60 multiop_output < $TMPPIPE
7079     if [ $? -ne 0 ]; then
7080         rm -f $TMPPIPE
7081         return 1
7082     fi
7083     rm -f $TMPPIPE
7084     if [ "$multiop_output" != "PAUSING" ]; then
7085         echo "Incorrect multiop output: $multiop_output"
7086         kill -9 $PID
7087         return 1
7088     fi
7089
7090     return 0
7091 }
7092
7093 do_and_time () {
7094     local cmd=$1
7095     local rc
7096
7097     SECONDS=0
7098     eval '$cmd'
7099
7100     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
7101
7102     echo $SECONDS
7103     return $rc
7104 }
7105
7106 inodes_available () {
7107         local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{ print $4 }' |
7108                 sort -un | head -n1) || return 1
7109         echo $((IFree))
7110 }
7111
7112 mdsrate_inodes_available () {
7113         local min_inodes=$(inodes_available)
7114         echo $((min_inodes * 99 / 100))
7115 }
7116
7117 # reset stat counters
7118 clear_stats() {
7119         local paramfile="$1"
7120         lctl set_param -n $paramfile=0
7121 }
7122
7123 # sum stat items
7124 calc_stats() {
7125         local paramfile="$1"
7126         local stat="$2"
7127         lctl get_param -n $paramfile |
7128                 awk '/^'$stat'/ { sum += $2 } END { printf("%0.0f", sum) }'
7129 }
7130
7131 calc_sum () {
7132         awk '{sum += $1} END { printf("%0.0f", sum) }'
7133 }
7134
7135 calc_osc_kbytes () {
7136         $LFS df $MOUNT > /dev/null
7137         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
7138 }
7139
7140 # save_lustre_params(comma separated facet list, parameter_mask)
7141 # generate a stream of formatted strings (<facet> <param name>=<param value>)
7142 save_lustre_params() {
7143         local facets=$1
7144         local facet
7145         local facet_svc
7146
7147         for facet in ${facets//,/ }; do
7148                 facet_svc=$(facet_svc $facet)
7149                 do_facet $facet \
7150                         "params=\\\$($LCTL get_param $2);
7151                          [[ -z \\\"$facet_svc\\\" ]] && param= ||
7152                          param=\\\$(grep $facet_svc <<< \\\"\\\$params\\\");
7153                          [[ -z \\\$param ]] && param=\\\"\\\$params\\\";
7154                          while read s; do echo $facet \\\$s;
7155                          done <<< \\\"\\\$param\\\""
7156         done
7157 }
7158
7159 # restore lustre parameters from input stream, produces by save_lustre_params
7160 restore_lustre_params() {
7161         local facet
7162         local name
7163         local val
7164
7165         while IFS=" =" read facet name val; do
7166                 do_facet $facet "$LCTL set_param -n $name=$val"
7167         done
7168 }
7169
7170 check_node_health() {
7171         local nodes=${1:-$(comma_list $(nodes_list))}
7172
7173         for node in ${nodes//,/ }; do
7174                 check_network "$node" 5
7175                 if [ $? -eq 0 ]; then
7176                         do_node $node "rc=0;
7177                         val=\\\$($LCTL get_param -n catastrophe 2>&1);
7178                         if [[ \\\$? -eq 0 && \\\$val -ne 0 ]]; then
7179                                 echo \\\$(hostname -s): \\\$val;
7180                                 rc=\\\$val;
7181                         fi;
7182                         exit \\\$rc" || error "$node:LBUG/LASSERT detected"
7183                 fi
7184         done
7185 }
7186
7187 mdsrate_cleanup () {
7188         if [ -d $4 ]; then
7189                 mpi_run ${MACHINEFILE_OPTION} $2 -np $1 ${MDSRATE} --unlink \
7190                         --nfiles $3 --dir $4 --filefmt $5 $6
7191                 rmdir $4
7192         fi
7193 }
7194
7195 delayed_recovery_enabled () {
7196     local var=${SINGLEMDS}_svc
7197     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
7198 }
7199
7200 ########################
7201
7202 convert_facet2label() {
7203         local facet=$1
7204
7205         if [ x$facet = xost ]; then
7206                 facet=ost1
7207         elif [ x$facet = xmgs ] && combined_mgs_mds ; then
7208                 facet=mds1
7209         fi
7210
7211         local varsvc=${facet}_svc
7212
7213         if [ -n ${!varsvc} ]; then
7214                 echo ${!varsvc}
7215         else
7216                 error "No label for $facet!"
7217         fi
7218 }
7219
7220 get_clientosc_proc_path() {
7221         echo "${1}-osc-[-0-9a-f]*"
7222 }
7223
7224 # If the 2.0 MDS was mounted on 1.8 device, then the OSC and LOV names
7225 # used by MDT would not be changed.
7226 # mdt lov: fsname-mdtlov
7227 # mdt osc: fsname-OSTXXXX-osc
7228 mds_on_old_device() {
7229     local mds=${1:-"$SINGLEMDS"}
7230
7231     if [ $(lustre_version_code $mds) -gt $(version_code 1.9.0) ]; then
7232         do_facet $mds "lctl list_param osc.$FSNAME-OST*-osc \
7233             > /dev/null 2>&1" && return 0
7234     fi
7235     return 1
7236 }
7237
7238 get_mdtosc_proc_path() {
7239         local mds_facet=$1
7240         local ost_label=${2:-"*OST*"}
7241
7242         [ "$mds_facet" = "mds" ] && mds_facet=$SINGLEMDS
7243         local mdt_label=$(convert_facet2label $mds_facet)
7244         local mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')
7245
7246         if [[ $ost_label = *OST* ]]; then
7247                 echo "${ost_label}-osc-${mdt_index}"
7248         else
7249                 echo "${ost_label}-osp-${mdt_index}"
7250         fi
7251 }
7252
7253 get_osc_import_name() {
7254     local facet=$1
7255     local ost=$2
7256     local label=$(convert_facet2label $ost)
7257
7258     if [ "${facet:0:3}" = "mds" ]; then
7259         get_mdtosc_proc_path $facet $label
7260         return 0
7261     fi
7262
7263     get_clientosc_proc_path $label
7264     return 0
7265 }
7266
7267 _wait_import_state () {
7268     local expected=$1
7269     local CONN_PROC=$2
7270     local maxtime=${3:-$(max_recovery_time)}
7271     local error_on_failure=${4:-1}
7272     local CONN_STATE
7273     local i=0
7274
7275         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
7276     while ! echo "${CONN_STATE}" | egrep -q "^${expected}\$" ; do
7277         if [ "${expected}" == "DISCONN" ]; then
7278             # for disconn we can check after proc entry is removed
7279             [ "x${CONN_STATE}" == "x" ] && return 0
7280             #  with AT enabled, we can have connect request timeout near of
7281             # reconnect timeout and test can't see real disconnect
7282             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
7283         fi
7284         if [ $i -ge $maxtime ]; then
7285             [ $error_on_failure -ne 0 ] && \
7286                 error "can't put import for $CONN_PROC into ${expected}" \
7287                       "state after $i sec, have ${CONN_STATE}"
7288             return 1
7289         fi
7290         sleep 1
7291         # Add uniq for multi-mount case
7292         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
7293         i=$(($i + 1))
7294     done
7295
7296     log "$CONN_PROC in ${CONN_STATE} state after $i sec"
7297     return 0
7298 }
7299
7300 wait_import_state() {
7301     local state=$1
7302     local params=$2
7303     local maxtime=${3:-$(max_recovery_time)}
7304     local error_on_failure=${4:-1}
7305     local param
7306
7307     for param in ${params//,/ }; do
7308         _wait_import_state $state $param $maxtime $error_on_failure || return
7309     done
7310 }
7311
7312 wait_import_state_mount() {
7313         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
7314                 return 0
7315         fi
7316
7317         wait_import_state $*
7318 }
7319
7320 # One client request could be timed out because server was not ready
7321 # when request was sent by client.
7322 # The request timeout calculation details :
7323 # ptl_send_rpc ()
7324 #      /* We give the server rq_timeout secs to process the req, and
7325 #      add the network latency for our local timeout. */
7326 #      request->rq_deadline = request->rq_sent + request->rq_timeout +
7327 #           ptlrpc_at_get_net_latency(request) ;
7328 #
7329 # ptlrpc_connect_import ()
7330 #      request->rq_timeout = INITIAL_CONNECT_TIMEOUT
7331 #
7332 # init_imp_at () ->
7333 #   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0
7334 # ptlrpc_at_get_net_latency(request) ->
7335 #       at_get (max (iat_net_latency=0, at_min)) = at_min
7336 #
7337 # i.e.:
7338 # request->rq_timeout + ptlrpc_at_get_net_latency(request) =
7339 # INITIAL_CONNECT_TIMEOUT + at_min
7340 #
7341 # We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT
7342 # because we can not get this value in runtime,
7343 # the value depends on configure options, and it is not stored in /proc.
7344 # obd_support.h:
7345 # #define CONNECTION_SWITCH_MIN 5U
7346 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
7347
7348 request_timeout () {
7349     local facet=$1
7350
7351     # request->rq_timeout = INITIAL_CONNECT_TIMEOUT
7352     local init_connect_timeout=$TIMEOUT
7353     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
7354
7355     local at_min=$(at_get $facet at_min)
7356
7357     echo $(( init_connect_timeout + at_min ))
7358 }
7359
7360 _wait_osc_import_state() {
7361         local facet=$1
7362         local ost_facet=$2
7363         local expected=$3
7364         local target=$(get_osc_import_name $facet $ost_facet)
7365         local param="os[cp].${target}.ost_server_uuid"
7366         local params=$param
7367         local i=0
7368
7369         # 1. wait the deadline of client 1st request (it could be skipped)
7370         # 2. wait the deadline of client 2nd request
7371         local maxtime=$(( 2 * $(request_timeout $facet)))
7372
7373         if [[ $facet == client* ]]; then
7374                 # During setup time, the osc might not be setup, it need wait
7375                 # until list_param can return valid value.
7376                 params=$($LCTL list_param $param 2>/dev/null || true)
7377                 while [ -z "$params" ]; do
7378                         if [ $i -ge $maxtime ]; then
7379                                 echo "can't get $param in $maxtime secs"
7380                                 return 1
7381                         fi
7382                         sleep 1
7383                         i=$((i + 1))
7384                         params=$($LCTL list_param $param 2>/dev/null || true)
7385                 done
7386         fi
7387
7388         if [[ $ost_facet = mds* ]]; then
7389                 # no OSP connection to itself
7390                 if [[ $facet = $ost_facet ]]; then
7391                         return 0
7392                 fi
7393                 param="osp.${target}.mdt_server_uuid"
7394                 params=$param
7395         fi
7396
7397         if ! do_rpc_nodes "$(facet_active_host $facet)" \
7398                         wait_import_state $expected "$params" $maxtime; then
7399                 error "$facet: import is not in $expected state after $maxtime"
7400                 return 1
7401         fi
7402
7403         return 0
7404 }
7405
7406 wait_osc_import_state() {
7407         local facet=$1
7408         local ost_facet=$2
7409         local expected=$3
7410         local num
7411
7412         if [[ $facet = mds ]]; then
7413                 for num in $(seq $MDSCOUNT); do
7414                         _wait_osc_import_state mds$num "$ost_facet" "$expected"
7415                 done
7416         else
7417                 _wait_osc_import_state "$facet" "$ost_facet" "$expected"
7418         fi
7419 }
7420
7421 wait_osc_import_ready() {
7422         wait_osc_import_state $1 $2 "\(FULL\|IDLE\)"
7423 }
7424
7425 _wait_mgc_import_state() {
7426         local facet=$1
7427         local expected=$2
7428         local error_on_failure=${3:-1}
7429         local param="mgc.*.mgs_server_uuid"
7430         local params=$param
7431         local i=0
7432
7433         # 1. wait the deadline of client 1st request (it could be skipped)
7434         # 2. wait the deadline of client 2nd request
7435         local maxtime=$(( 2 * $(request_timeout $facet)))
7436
7437         if [[ $facet == client* ]]; then
7438                 # During setup time, the osc might not be setup, it need wait
7439                 # until list_param can return valid value. And also if there
7440                 # are mulitple osc entries we should list all of them before
7441                 # go to wait.
7442                 params=$($LCTL list_param $param 2>/dev/null || true)
7443                 while [ -z "$params" ]; do
7444                         if [ $i -ge $maxtime ]; then
7445                                 echo "can't get $param in $maxtime secs"
7446                                 return 1
7447                         fi
7448                         sleep 1
7449                         i=$((i + 1))
7450                         params=$($LCTL list_param $param 2>/dev/null || true)
7451                 done
7452         fi
7453         if ! do_rpc_nodes "$(facet_active_host $facet)" \
7454                         wait_import_state $expected "$params" $maxtime \
7455                                           $error_on_failure; then
7456                 if [ $error_on_failure -ne 0 ]; then
7457                     error "import is not in ${expected} state"
7458                 fi
7459                 return 1
7460         fi
7461
7462         return 0
7463 }
7464
7465 wait_mgc_import_state() {
7466         local facet=$1
7467         local expected=$2
7468         local error_on_failure=${3:-1}
7469         local num
7470
7471         if [[ $facet = mds ]]; then
7472                 for num in $(seq $MDSCOUNT); do
7473                         _wait_mgc_import_state mds$num "$expected" \
7474                                                $error_on_failure || return
7475                 done
7476         else
7477                 _wait_mgc_import_state "$facet" "$expected"
7478                                        $error_on_failure || return
7479         fi
7480 }
7481
7482 wait_dne_interconnect() {
7483         local num
7484
7485         if [ $MDSCOUNT -gt 1 ]; then
7486                 for num in $(seq $MDSCOUNT); do
7487                         wait_osc_import_ready mds mds$num
7488                 done
7489         fi
7490 }
7491
7492 get_clientmdc_proc_path() {
7493     echo "${1}-mdc-*"
7494 }
7495
7496 get_clientmgc_proc_path() {
7497     echo "*"
7498 }
7499
7500 do_rpc_nodes () {
7501         local list=$1
7502         shift
7503
7504         [ -z "$list" ] && return 0
7505
7506         # Add paths to lustre tests for 32 and 64 bit systems.
7507         local LIBPATH="/usr/lib/lustre/tests:/usr/lib64/lustre/tests:"
7508         local TESTPATH="$RLUSTRE/tests:"
7509         local RPATH="PATH=${TESTPATH}${LIBPATH}${PATH}:/sbin:/bin:/usr/sbin:"
7510         do_nodesv $list "${RPATH} NAME=${NAME} bash rpc.sh $@ "
7511 }
7512
7513 wait_clients_import_state () {
7514         local list=$1
7515         local facet=$2
7516         local expected=$3
7517
7518         local facets=$facet
7519
7520         if [ "$FAILURE_MODE" = HARD ]; then
7521                 facets=$(facets_on_host $(facet_active_host $facet))
7522         fi
7523
7524         for facet in ${facets//,/ }; do
7525                 local label=$(convert_facet2label $facet)
7526                 local proc_path
7527                 case $facet in
7528                 ost* ) proc_path="osc.$(get_clientosc_proc_path \
7529                                   $label).ost_server_uuid" ;;
7530                 mds* ) proc_path="mdc.$(get_clientmdc_proc_path \
7531                                   $label).mds_server_uuid" ;;
7532                 mgs* ) proc_path="mgc.$(get_clientmgc_proc_path \
7533                                   $label).mgs_server_uuid" ;;
7534                 *) error "unknown facet!" ;;
7535                 esac
7536
7537                 local params=$(expand_list $params $proc_path)
7538         done
7539
7540         if ! do_rpc_nodes "$list" wait_import_state_mount "$expected" $params;
7541         then
7542                 error "import is not in ${expected} state"
7543                 return 1
7544         fi
7545 }
7546
7547 wait_osp_active() {
7548         local facet=$1
7549         local tgt_name=$2
7550         local tgt_idx=$3
7551         local expected=$4
7552         local num
7553
7554         # wait until all MDTs are in the expected state
7555         for ((num = 1; num <= $MDSCOUNT; num++)); do
7556                 local mdtosp=$(get_mdtosc_proc_path mds${num} ${tgt_name})
7557                 local wait=0
7558                 local mproc
7559
7560                 if [ $facet = "mds" ]; then
7561                         mproc="osp.$mdtosp.active"
7562                         [ $num -eq $((tgt_idx + 1)) ] && continue
7563                 else
7564                         mproc="osc.$mdtosp.active"
7565                 fi
7566
7567                 echo "check $mproc"
7568                 while [ 1 ]; do
7569                         sleep 5
7570                         local result=$(do_facet mds${num} "$LCTL get_param -n $mproc")
7571                         local max=30
7572
7573                         [ ${PIPESTATUS[0]} = 0 ] || error "Can't read $mproc"
7574                         if [ $result -eq $expected ]; then
7575                                 echo -n "target updated after "
7576                                 echo "$wait sec (got $result)"
7577                                 break
7578                         fi
7579                         wait=$((wait + 5))
7580                         if [ $wait -eq $max ]; then
7581                                 error "$tgt_name: wanted $expected got $result"
7582                         fi
7583                         echo "Waiting $((max - wait)) secs for $tgt_name"
7584                 done
7585         done
7586 }
7587
7588 oos_full() {
7589         local -a AVAILA
7590         local -a GRANTA
7591         local -a TOTALA
7592         local OSCFULL=1
7593         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
7594                   $LCTL get_param obdfilter.*.kbytesavail))
7595         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
7596                   $LCTL get_param -n obdfilter.*.tot_granted))
7597         TOTALA=($(do_nodes $(comma_list $(osts_nodes)) \
7598                   $LCTL get_param -n obdfilter.*.kbytestotal))
7599         for ((i=0; i<${#AVAILA[@]}; i++)); do
7600                 local -a AVAIL1=(${AVAILA[$i]//=/ })
7601                 local -a TOTAL=(${TOTALA[$i]//=/ })
7602                 GRANT=$((${GRANTA[$i]}/1024))
7603                 # allow 1% of total space in bavail because of delayed
7604                 # allocation with ZFS which might release some free space after
7605                 # txg commit.  For small devices, we set a mininum of 8MB
7606                 local LIMIT=$((${TOTAL} / 100 + 8000))
7607                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} \
7608                         grnt=$GRANT diff=$((AVAIL1[1] - GRANT)) limit=${LIMIT}
7609                 [ $((AVAIL1[1] - GRANT)) -lt $LIMIT ] && OSCFULL=0 && \
7610                         echo " FULL" || echo
7611         done
7612         return $OSCFULL
7613 }
7614
7615 list_pool() {
7616         echo -e "$(do_facet $SINGLEMDS $LCTL pool_list $1 | sed '1d')"
7617 }
7618
7619 check_pool_not_exist() {
7620         local fsname=${1%%.*}
7621         local poolname=${1##$fsname.}
7622         [[ $# -ne 1 ]] && return 0
7623         [[ x$poolname = x ]] &&  return 0
7624         list_pool $fsname | grep -w $1 && return 1
7625         return 0
7626 }
7627
7628 create_pool() {
7629         local fsname=${1%%.*}
7630         local poolname=${1##$fsname.}
7631
7632         stack_trap "destroy_test_pools $fsname" EXIT
7633         do_facet mgs lctl pool_new $1
7634         local RC=$?
7635         # get param should return err unless pool is created
7636         [[ $RC -ne 0 ]] && return $RC
7637
7638         for mds_id in $(seq $MDSCOUNT); do
7639                 local mdt_id=$((mds_id-1))
7640                 local lodname=$fsname-MDT$(printf "%04x" $mdt_id)-mdtlov
7641                 wait_update_facet mds$mds_id \
7642                         "lctl get_param -n lod.$lodname.pools.$poolname \
7643                                 2>/dev/null || echo foo" "" ||
7644                         error "mds$mds_id: pool_new failed $1"
7645         done
7646         wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
7647                 2>/dev/null || echo foo" "" || error "pool_new failed $1"
7648
7649         add_pool_to_list $1
7650         return $RC
7651 }
7652
7653 add_pool_to_list () {
7654         local fsname=${1%%.*}
7655         local poolname=${1##$fsname.}
7656
7657         local listvar=${fsname}_CREATED_POOLS
7658         local temp=${listvar}=$(expand_list ${!listvar} $poolname)
7659         eval export $temp
7660 }
7661
7662 remove_pool_from_list () {
7663         local fsname=${1%%.*}
7664         local poolname=${1##$fsname.}
7665
7666         local listvar=${fsname}_CREATED_POOLS
7667         local temp=${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
7668         eval export $temp
7669 }
7670
7671 destroy_pool_int() {
7672         local ost
7673         local OSTS=$(list_pool $1)
7674         for ost in $OSTS; do
7675                 do_facet mgs lctl pool_remove $1 $ost
7676         done
7677         wait_update_facet $SINGLEMDS "lctl pool_list $1 | wc -l" "1" ||
7678                 error "MDS: pool_list $1 failed"
7679         do_facet mgs lctl pool_destroy $1
7680 }
7681
7682 # <fsname>.<poolname> or <poolname>
7683 destroy_pool() {
7684         local fsname=${1%%.*}
7685         local poolname=${1##$fsname.}
7686
7687         [[ x$fsname = x$poolname ]] && fsname=$FSNAME
7688
7689         local RC
7690
7691         check_pool_not_exist $fsname.$poolname
7692         [[ $? -eq 0 ]] && return 0
7693
7694         destroy_pool_int $fsname.$poolname
7695         RC=$?
7696         [[ $RC -ne 0 ]] && return $RC
7697         for mds_id in $(seq $MDSCOUNT); do
7698                 local mdt_id=$((mds_id-1))
7699                 local lodname=$fsname-MDT$(printf "%04x" $mdt_id)-mdtlov
7700                 wait_update_facet mds$mds_id \
7701                         "lctl get_param -n lod.$lodname.pools.$poolname \
7702                                 2>/dev/null || echo foo" "foo" ||
7703                         error "mds$mds_id: destroy pool failed $1"
7704         done
7705         wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
7706                 2>/dev/null || echo foo" "foo" || error "destroy pool failed $1"
7707
7708         remove_pool_from_list $fsname.$poolname
7709
7710         return $RC
7711 }
7712
7713 destroy_pools () {
7714         local fsname=${1:-$FSNAME}
7715         local poolname
7716         local listvar=${fsname}_CREATED_POOLS
7717
7718         [ x${!listvar} = x ] && return 0
7719
7720         echo "Destroy the created pools: ${!listvar}"
7721         for poolname in ${!listvar//,/ }; do
7722                 destroy_pool $fsname.$poolname
7723         done
7724 }
7725
7726 destroy_test_pools () {
7727         trap 0
7728         local fsname=${1:-$FSNAME}
7729         destroy_pools $fsname || true
7730 }
7731
7732 gather_logs () {
7733     local list=$1
7734
7735     local ts=$(date +%s)
7736     local docp=true
7737
7738     if [[ ! -f "$YAML_LOG" ]]; then
7739         # init_logging is not performed before gather_logs,
7740         # so the $LOGDIR needs to be checked here
7741         check_shared_dir $LOGDIR && touch $LOGDIR/shared
7742     fi
7743
7744     [ -f $LOGDIR/shared ] && docp=false
7745
7746     # dump lustre logs, dmesg
7747
7748     prefix="$TESTLOG_PREFIX.$TESTNAME"
7749     suffix="$ts.log"
7750     echo "Dumping lctl log to ${prefix}.*.${suffix}"
7751
7752     if [ -n "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
7753         echo "Dumping logs only on local client."
7754         $LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}
7755         dmesg > ${prefix}.dmesg.$(hostname -s).${suffix}
7756         return
7757     fi
7758
7759     do_nodesv $list \
7760         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname -s).${suffix};
7761          dmesg > ${prefix}.dmesg.\\\$(hostname -s).${suffix}"
7762
7763     if [ ! -f $LOGDIR/shared ]; then
7764         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
7765     fi
7766 }
7767
7768 do_ls () {
7769     local mntpt_root=$1
7770     local num_mntpts=$2
7771     local dir=$3
7772     local i
7773     local cmd
7774     local pids
7775     local rc=0
7776
7777     for i in $(seq 0 $num_mntpts); do
7778         cmd="ls -laf ${mntpt_root}$i/$dir"
7779         echo + $cmd;
7780         $cmd > /dev/null &
7781         pids="$pids $!"
7782     done
7783     echo pids=$pids
7784     for pid in $pids; do
7785         wait $pid || rc=$?
7786     done
7787
7788     return $rc
7789 }
7790
7791 # check_and_start_recovery_timer()
7792 #       service_time = at_est2timeout(service_time);
7793 #       service_time += 2 * INITIAL_CONNECT_TIMEOUT;
7794 #       service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC);
7795
7796 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN, obd_timeout/20)
7797 #define CONNECTION_SWITCH_MAX min(50, max(CONNECTION_SWITCH_MIN, obd_timeout))
7798 #define CONNECTION_SWITCH_MIN 5
7799 #define CONNECTION_SWITCH_INC 5
7800 max_recovery_time() {
7801         local init_connect_timeout=$((TIMEOUT / 20))
7802         ((init_connect_timeout >= 5)) || init_connect_timeout=5
7803
7804         local service_time=$(($(at_max_get client) * 9 / 4 + 5))
7805         service_time=$((service_time + 2 * (init_connect_timeout + 50 + 5)))
7806
7807         echo -n $service_time
7808 }
7809
7810 recovery_time_min() {
7811         local connection_switch_min=5
7812         local connection_switch_inc=5
7813         local connection_switch_max
7814         local reconnect_delay_max
7815         local initial_connect_timeout
7816         local max
7817         local timout_20
7818
7819         #connection_switch_max=min(50, max($connection_switch_min,$TIMEOUT)
7820         (($connection_switch_min > $TIMEOUT)) &&
7821                 max=$connection_switch_min || max=$TIMEOUT
7822         (($max < 50)) && connection_switch_max=$max || connection_switch_max=50
7823
7824         #initial_connect_timeout = max(connection_switch_min, obd_timeout/20)
7825         timeout_20=$((TIMEOUT/20))
7826         (($connection_switch_min > $timeout_20)) &&
7827                 initial_connect_timeout=$connection_switch_min ||
7828                 initial_connect_timeout=$timeout_20
7829
7830         reconnect_delay_max=$((connection_switch_max + connection_switch_inc + \
7831                                initial_connect_timeout))
7832         echo $((2 * reconnect_delay_max))
7833 }
7834
7835 get_clients_mount_count () {
7836         local clients=${CLIENTS:-$HOSTNAME}
7837
7838         # we need to take into account the clients mounts and
7839         # exclude mds/ost mounts if any;
7840         do_nodes $clients cat /proc/mounts | grep lustre |
7841                 grep -w $MOUNT | wc -l
7842 }
7843
7844 # gss functions
7845 PROC_CLI="srpc_info"
7846 PROC_CON="srpc_contexts"
7847
7848 combination()
7849 {
7850     local M=$1
7851     local N=$2
7852     local R=1
7853
7854     if [ $M -lt $N ]; then
7855         R=0
7856     else
7857         N=$((N + 1))
7858         while [ $N -lt $M ]; do
7859             R=$((R * N))
7860             N=$((N + 1))
7861         done
7862     fi
7863
7864     echo $R
7865     return 0
7866 }
7867
7868 calc_connection_cnt() {
7869         local dir=$1
7870
7871         # MDT->MDT = 2 * C(M, 2)
7872         # MDT->OST = M * O
7873         # CLI->OST = C * O
7874         # CLI->MDT = C * M
7875         comb_m2=$(combination $MDSCOUNT 2)
7876
7877         local num_clients=$(get_clients_mount_count)
7878
7879         local cnt_mdt2mdt=$((comb_m2 * 2))
7880         local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
7881         local cnt_cli2ost=$((num_clients * OSTCOUNT))
7882         local cnt_cli2mdt=$((num_clients * MDSCOUNT))
7883         if is_mounted $MOUNT2; then
7884                 cnt_cli2mdt=$((cnt_cli2mdt * 2))
7885                 cnt_cli2ost=$((cnt_cli2ost * 2))
7886         fi
7887         if local_mode; then
7888                 cnt_mdt2mdt=0
7889                 cnt_mdt2ost=0
7890                 cnt_cli2ost=2
7891                 cnt_cli2mdt=1
7892         fi
7893         local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
7894         local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
7895         local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt \
7896                 + cnt_cli2ost + cnt_cli2mdt))
7897
7898         local var=cnt_$dir
7899         local res=${!var}
7900
7901         echo $res
7902 }
7903
7904 set_rule()
7905 {
7906     local tgt=$1
7907     local net=$2
7908     local dir=$3
7909     local flavor=$4
7910     local cmd="$tgt.srpc.flavor"
7911
7912     if [ $net == "any" ]; then
7913         net="default"
7914     fi
7915     cmd="$cmd.$net"
7916
7917     if [ $dir != "any" ]; then
7918         cmd="$cmd.$dir"
7919     fi
7920
7921     cmd="$cmd=$flavor"
7922     log "Setting sptlrpc rule: $cmd"
7923     do_facet mgs "$LCTL conf_param $cmd"
7924 }
7925
7926 count_contexts()
7927 {
7928         local output=$1
7929         local total_ctx=$(echo "$output" | grep -c "expire.*key.*hdl")
7930         echo $total_ctx
7931 }
7932
7933 count_flvr()
7934 {
7935     local output=$1
7936     local flavor=$2
7937     local count=0
7938
7939     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
7940     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
7941
7942     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
7943
7944     if [ "x$bulkspec" != "x" ]; then
7945         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
7946
7947         if [ "x$algs" != "x" ]; then
7948             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
7949         else
7950             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
7951             if [ $bulk == "bulkn" ]; then
7952                 bulk_count=`echo "$output" | grep "bulk flavor" \
7953                             | grep "null/null" | wc -l`
7954             elif [ $bulk == "bulki" ]; then
7955                 bulk_count=`echo "$output" | grep "bulk flavor" \
7956                             | grep "/null" | grep -v "null/" | wc -l`
7957             else
7958                 bulk_count=`echo "$output" | grep "bulk flavor" \
7959                             | grep -v "/null" | grep -v "null/" | wc -l`
7960             fi
7961         fi
7962
7963         [ $bulk_count -lt $count ] && count=$bulk_count
7964     fi
7965
7966     echo $count
7967 }
7968
7969 flvr_cnt_cli2mdt()
7970 {
7971     local flavor=$1
7972     local cnt
7973
7974     local clients=${CLIENTS:-$HOSTNAME}
7975
7976     for c in ${clients//,/ }; do
7977         local output=$(do_node $c lctl get_param -n \
7978                  mdc.*-*-mdc-*.$PROC_CLI 2>/dev/null)
7979         local tmpcnt=$(count_flvr "$output" $flavor)
7980         if $GSS_SK && [ $flavor != "null" ]; then
7981                 # tmpcnt=min(contexts,flavors) to ensure SK context is on
7982                 output=$(do_node $c lctl get_param -n \
7983                          mdc.*-MDT*-mdc-*.$PROC_CON 2>/dev/null)
7984                 local outcon=$(count_contexts "$output")
7985                 if [ "$outcon" -lt "$tmpcnt" ]; then
7986                         tmpcnt=$outcon
7987                 fi
7988         fi
7989         cnt=$((cnt + tmpcnt))
7990     done
7991     echo $cnt
7992 }
7993
7994 flvr_cnt_cli2ost()
7995 {
7996     local flavor=$1
7997     local cnt
7998
7999     local clients=${CLIENTS:-$HOSTNAME}
8000
8001     for c in ${clients//,/ }; do
8002         # reconnect if idle
8003         do_node $c lctl set_param osc.*.idle_connect=1 >/dev/null 2>&1
8004         local output=$(do_node $c lctl get_param -n \
8005                  osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null)
8006         local tmpcnt=$(count_flvr "$output" $flavor)
8007         if $GSS_SK && [ $flavor != "null" ]; then
8008                 # tmpcnt=min(contexts,flavors) to ensure SK context is on
8009                 output=$(do_node $c lctl get_param -n \
8010                          osc.*OST*-osc-[^M][^D][^T]*.$PROC_CON 2>/dev/null)
8011                 local outcon=$(count_contexts "$output")
8012                 if [ "$outcon" -lt "$tmpcnt" ]; then
8013                         tmpcnt=$outcon
8014                 fi
8015         fi
8016         cnt=$((cnt + tmpcnt))
8017     done
8018     echo $cnt
8019 }
8020
8021 flvr_cnt_mdt2mdt()
8022 {
8023     local flavor=$1
8024     local cnt=0
8025
8026     if [ $MDSCOUNT -le 1 ]; then
8027         echo 0
8028         return
8029     fi
8030
8031     for num in `seq $MDSCOUNT`; do
8032         local output=$(do_facet mds$num lctl get_param -n \
8033                 osp.*-MDT*osp-MDT*.$PROC_CLI 2>/dev/null)
8034         local tmpcnt=$(count_flvr "$output" $flavor)
8035         if $GSS_SK && [ $flavor != "null" ]; then
8036                 # tmpcnt=min(contexts,flavors) to ensure SK context is on
8037                 output=$(do_facet mds$num lctl get_param -n \
8038                         osp.*-MDT*osp-MDT*.$PROC_CON 2>/dev/null)
8039                 local outcon=$(count_contexts "$output")
8040                 if [ "$outcon" -lt "$tmpcnt" ]; then
8041                         tmpcnt=$outcon
8042                 fi
8043         fi
8044         cnt=$((cnt + tmpcnt))
8045     done
8046     echo $cnt;
8047 }
8048
8049 flvr_cnt_mdt2ost()
8050 {
8051     local flavor=$1
8052     local cnt=0
8053     local mdtosc
8054
8055     for num in `seq $MDSCOUNT`; do
8056         mdtosc=$(get_mdtosc_proc_path mds$num)
8057         mdtosc=${mdtosc/-MDT*/-MDT\*}
8058         local output=$(do_facet mds$num lctl get_param -n \
8059                        os[cp].$mdtosc.$PROC_CLI 2>/dev/null)
8060         local tmpcnt=$(count_flvr "$output" $flavor)
8061         if $GSS_SK && [ $flavor != "null" ]; then
8062                 # tmpcnt=min(contexts,flavors) to ensure SK context is on
8063                 output=$(do_facet mds$num lctl get_param -n \
8064                          os[cp].$mdtosc.$PROC_CON 2>/dev/null)
8065                 local outcon=$(count_contexts "$output")
8066                 if [ "$outcon" -lt "$tmpcnt" ]; then
8067                         tmpcnt=$outcon
8068                 fi
8069         fi
8070         cnt=$((cnt + tmpcnt))
8071     done
8072     echo $cnt;
8073 }
8074
8075 flvr_cnt_mgc2mgs()
8076 {
8077     local flavor=$1
8078
8079     local output=$(do_facet client lctl get_param -n mgc.*.$PROC_CLI \
8080                         2>/dev/null)
8081     count_flvr "$output" $flavor
8082 }
8083
8084 do_check_flavor()
8085 {
8086     local dir=$1        # from to
8087     local flavor=$2     # flavor expected
8088     local res=0
8089
8090     if [ $dir == "cli2mdt" ]; then
8091         res=`flvr_cnt_cli2mdt $flavor`
8092     elif [ $dir == "cli2ost" ]; then
8093         res=`flvr_cnt_cli2ost $flavor`
8094     elif [ $dir == "mdt2mdt" ]; then
8095         res=`flvr_cnt_mdt2mdt $flavor`
8096     elif [ $dir == "mdt2ost" ]; then
8097         res=`flvr_cnt_mdt2ost $flavor`
8098     elif [ $dir == "all2ost" ]; then
8099         res1=`flvr_cnt_mdt2ost $flavor`
8100         res2=`flvr_cnt_cli2ost $flavor`
8101         res=$((res1 + res2))
8102     elif [ $dir == "all2mdt" ]; then
8103         res1=`flvr_cnt_mdt2mdt $flavor`
8104         res2=`flvr_cnt_cli2mdt $flavor`
8105         res=$((res1 + res2))
8106     elif [ $dir == "all2all" ]; then
8107         res1=`flvr_cnt_mdt2ost $flavor`
8108         res2=`flvr_cnt_cli2ost $flavor`
8109         res3=`flvr_cnt_mdt2mdt $flavor`
8110         res4=`flvr_cnt_cli2mdt $flavor`
8111         res=$((res1 + res2 + res3 + res4))
8112     fi
8113
8114     echo $res
8115 }
8116
8117 wait_flavor()
8118 {
8119         local dir=$1        # from to
8120         local flavor=$2     # flavor expected
8121         local expect=${3:-$(calc_connection_cnt $dir)} # number expected
8122         local WAITFLAVOR_MAX=20 # how many retries before abort?
8123
8124         local res=0
8125         for ((i = 0; i < $WAITFLAVOR_MAX; i++)); do
8126                 echo -n "checking $dir..."
8127                 res=$(do_check_flavor $dir $flavor)
8128                 echo "found $res/$expect $flavor connections"
8129                 [ $res -ge $expect ] && return 0
8130                 sleep 4
8131         done
8132
8133         echo "Error checking $flavor of $dir: expect $expect, actual $res"
8134 #       echo "Dumping additional logs for SK debug.."
8135         do_nodes $(comma_list $(all_server_nodes)) "keyctl show"
8136         if $dump; then
8137                 gather_logs $(comma_list $(nodes_list))
8138         fi
8139         return 1
8140 }
8141
8142 restore_to_default_flavor()
8143 {
8144         local proc="mgs.MGS.live.$FSNAME"
8145
8146         echo "restoring to default flavor..."
8147
8148         local nrule=$(do_facet mgs lctl get_param -n $proc 2>/dev/null |
8149                 grep ".srpc.flavor" | wc -l)
8150
8151         # remove all existing rules if any
8152         if [ $nrule -ne 0 ]; then
8153                 echo "$nrule existing rules"
8154                 for rule in $(do_facet mgs lctl get_param -n $proc 2>/dev/null |
8155                     grep ".srpc.flavor."); do
8156                         echo "remove rule: $rule"
8157                         spec=`echo $rule | awk -F = '{print $1}'`
8158                         do_facet mgs "$LCTL conf_param -d $spec"
8159                 done
8160         fi
8161
8162         # verify no rules left
8163         nrule=$(do_facet mgs lctl get_param -n $proc 2>/dev/null |
8164                 grep ".srpc.flavor." | wc -l)
8165         [ $nrule -ne 0 ] && error "still $nrule rules left"
8166
8167         # wait for default flavor to be applied
8168         if $GSS_SK; then
8169                 if $SK_S2S; then
8170                         set_rule $FSNAME any any $SK_FLAVOR
8171                         wait_flavor all2all $SK_FLAVOR
8172                 else
8173                         set_rule $FSNAME any cli2mdt $SK_FLAVOR
8174                         set_rule $FSNAME any cli2ost $SK_FLAVOR
8175                         wait_flavor cli2mdt $SK_FLAVOR
8176                         wait_flavor cli2ost $SK_FLAVOR
8177                 fi
8178                 echo "GSS_SK now at default flavor: $SK_FLAVOR"
8179         else
8180                 wait_flavor all2all null
8181         fi
8182 }
8183
8184 set_flavor_all()
8185 {
8186         local flavor=${1:-null}
8187
8188         echo "setting all flavor to $flavor"
8189
8190         # FIXME need parameter to this fn
8191         # and remove global vars
8192         local cnt_all2all=$(calc_connection_cnt all2all)
8193
8194         local res=$(do_check_flavor all2all $flavor)
8195         if [ $res -eq $cnt_all2all ]; then
8196                 echo "already have total $res $flavor connections"
8197                 return
8198         fi
8199
8200         echo "found $res $flavor out of total $cnt_all2all connections"
8201         restore_to_default_flavor
8202
8203         [[ $flavor = null ]] && return 0
8204
8205         if $GSS_SK && [ $flavor != "null" ]; then
8206                 if $SK_S2S; then
8207                         set_rule $FSNAME any any $flavor
8208                         wait_flavor all2all $flavor
8209                 else
8210                         set_rule $FSNAME any cli2mdt $flavor
8211                         set_rule $FSNAME any cli2ost $flavor
8212                         set_rule $FSNAME any mdt2ost null
8213                         set_rule $FSNAME any mdt2mdt null
8214                         wait_flavor cli2mdt $flavor
8215                         wait_flavor cli2ost $flavor
8216                 fi
8217                 echo "GSS_SK now at flavor: $flavor"
8218         else
8219                 set_rule $FSNAME any any $flavor
8220                 wait_flavor all2all $flavor
8221         fi
8222 }
8223
8224
8225 check_logdir() {
8226     local dir=$1
8227     # Checking for shared logdir
8228     if [ ! -d $dir ]; then
8229         # Not found. Create local logdir
8230         mkdir -p $dir
8231     else
8232         touch $dir/check_file.$(hostname -s)
8233     fi
8234     return 0
8235 }
8236
8237 check_write_access() {
8238         local dir=$1
8239         local list=${2:-$(comma_list $(nodes_list))}
8240         local node
8241         local file
8242
8243         for node in ${list//,/ }; do
8244                 file=$dir/check_file.$(short_nodename $node)
8245                 if [[ ! -f "$file" ]]; then
8246                         # Logdir not accessible/writable from this node.
8247                         return 1
8248                 fi
8249                 rm -f $file || return 1
8250         done
8251         return 0
8252 }
8253
8254 init_logging() {
8255         [[ -n $YAML_LOG ]] && return
8256         local save_umask=$(umask)
8257         umask 0000
8258
8259         export YAML_LOG=${LOGDIR}/results.yml
8260         mkdir -p $LOGDIR
8261         init_clients_lists
8262
8263         # If the yaml log already exists then we will just append to it
8264         if [ ! -f $YAML_LOG ]; then
8265                 if check_shared_dir $LOGDIR; then
8266                         touch $LOGDIR/shared
8267                         echo "Logging to shared log directory: $LOGDIR"
8268                 else
8269                         echo "Logging to local directory: $LOGDIR"
8270                 fi
8271
8272                 yml_nodes_file $LOGDIR >> $YAML_LOG
8273                 yml_results_file >> $YAML_LOG
8274         fi
8275
8276         umask $save_umask
8277
8278         # If modules are not yet loaded then older "lctl lustre_build_version"
8279         # will fail.  Use lctl build version instead.
8280         log "Client: $($LCTL lustre_build_version)"
8281         log "MDS: $(do_facet $SINGLEMDS $LCTL lustre_build_version 2>/dev/null||
8282                     do_facet $SINGLEMDS $LCTL --version)"
8283         log "OSS: $(do_facet ost1 $LCTL lustre_build_version 2> /dev/null ||
8284                     do_facet ost1 $LCTL --version)"
8285 }
8286
8287 log_test() {
8288     yml_log_test $1 >> $YAML_LOG
8289 }
8290
8291 log_test_status() {
8292      yml_log_test_status $@ >> $YAML_LOG
8293 }
8294
8295 log_sub_test_begin() {
8296     yml_log_sub_test_begin "$@" >> $YAML_LOG
8297 }
8298
8299 log_sub_test_end() {
8300     yml_log_sub_test_end "$@" >> $YAML_LOG
8301 }
8302
8303 run_llverdev()
8304 {
8305         local dev=$1
8306         local llverdev_opts=$2
8307         local devname=$(basename $1)
8308         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
8309         # loop devices aren't in /proc/partitions
8310         [ "x$size" == "x" ] && local size=$(ls -l $dev | awk '{print $5}')
8311
8312         size=$(($size / 1024 / 1024)) # Gb
8313
8314         local partial_arg=""
8315         # Run in partial (fast) mode if the size
8316         # of a partition > 1 GB
8317         [ $size -gt 1 ] && partial_arg="-p"
8318
8319         llverdev --force $partial_arg $llverdev_opts $dev
8320 }
8321
8322 run_llverfs()
8323 {
8324         local dir=$1
8325         local llverfs_opts=$2
8326         local use_partial_arg=$3
8327         local partial_arg=""
8328         local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB
8329
8330         # Run in partial (fast) mode if the size
8331         # of a partition > 1 GB
8332         [ "x$use_partial_arg" != "xno" ] && [ $size -gt 1 ] && partial_arg="-p"
8333
8334         llverfs $partial_arg $llverfs_opts $dir
8335 }
8336
8337 #Remove objects from OST
8338 remove_ost_objects() {
8339         local facet=$1
8340         local ostdev=$2
8341         local group=$3
8342         shift 3
8343         local objids="$@"
8344         local mntpt=$(facet_mntpt $facet)
8345         local opts=$OST_MOUNT_OPTS
8346         local i
8347         local rc
8348
8349         echo "removing objects from $ostdev on $facet: $objids"
8350         if ! test -b $ostdev; then
8351                 opts=$(csa_add "$opts" -o loop)
8352         fi
8353         mount -t $(facet_fstype $facet) $opts $ostdev $mntpt ||
8354                 return $?
8355         rc=0
8356         for i in $objids; do
8357                 rm $mntpt/O/$group/d$((i % 32))/$i || { rc=$?; break; }
8358         done
8359         umount -f $mntpt || return $?
8360         return $rc
8361 }
8362
8363 #Remove files from MDT
8364 remove_mdt_files() {
8365         local facet=$1
8366         local mdtdev=$2
8367         shift 2
8368         local files="$@"
8369         local mntpt=$(facet_mntpt $facet)
8370         local opts=$MDS_MOUNT_OPTS
8371
8372         echo "removing files from $mdtdev on $facet: $files"
8373         if [ $(facet_fstype $facet) == ldiskfs ] &&
8374            ! do_facet $facet test -b $mdtdev; then
8375                 opts=$(csa_add "$opts" -o loop)
8376         fi
8377         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
8378                 return $?
8379         rc=0
8380         for f in $files; do
8381                 rm $mntpt/ROOT/$f || { rc=$?; break; }
8382         done
8383         umount -f $mntpt || return $?
8384         return $rc
8385 }
8386
8387 duplicate_mdt_files() {
8388         local facet=$1
8389         local mdtdev=$2
8390         shift 2
8391         local files="$@"
8392         local mntpt=$(facet_mntpt $facet)
8393         local opts=$MDS_MOUNT_OPTS
8394
8395         echo "duplicating files on $mdtdev on $facet: $files"
8396         mkdir -p $mntpt || return $?
8397         if [ $(facet_fstype $facet) == ldiskfs ] &&
8398            ! do_facet $facet test -b $mdtdev; then
8399                 opts=$(csa_add "$opts" -o loop)
8400         fi
8401         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
8402                 return $?
8403
8404     do_umount() {
8405         trap 0
8406         popd > /dev/null
8407         rm $tmp
8408         umount -f $mntpt
8409     }
8410     trap do_umount EXIT
8411
8412     tmp=$(mktemp $TMP/setfattr.XXXXXXXXXX)
8413     pushd $mntpt/ROOT > /dev/null || return $?
8414     rc=0
8415     for f in $files; do
8416         touch $f.bad || return $?
8417         getfattr -n trusted.lov $f | sed "s#$f#&.bad#" > $tmp
8418         rc=${PIPESTATUS[0]}
8419         [ $rc -eq 0 ] || return $rc
8420         setfattr --restore $tmp || return $?
8421     done
8422     do_umount
8423 }
8424
8425 run_sgpdd () {
8426     local devs=${1//,/ }
8427     shift
8428     local params=$@
8429     local rslt=$TMP/sgpdd_survey
8430
8431     # sgpdd-survey cleanups ${rslt}.* files
8432
8433     local cmd="rslt=$rslt $params scsidevs=\"$devs\" $SGPDDSURVEY"
8434     echo + $cmd
8435     eval $cmd
8436     cat ${rslt}.detail
8437 }
8438
8439 # returns the canonical name for an ldiskfs device
8440 ldiskfs_canon() {
8441         local dev="$1"
8442         local facet="$2"
8443
8444         do_facet $facet "dv=\\\$($LCTL get_param -n $dev);
8445                          if foo=\\\$(lvdisplay -c \\\$dv 2>/dev/null); then
8446                                 echo dm-\\\${foo##*:};
8447                          else
8448                                 name=\\\$(basename \\\$dv);
8449                                 if [[ \\\$name = *flakey* ]]; then
8450                                         name=\\\$(lsblk -o NAME,KNAME |
8451                                                 awk /\\\$name/'{print \\\$NF}');
8452                                 fi;
8453                                 echo \\\$name;
8454                          fi;"
8455 }
8456
8457 is_sanity_benchmark() {
8458     local benchmarks="dbench bonnie iozone fsx"
8459     local suite=$1
8460     for b in $benchmarks; do
8461         if [ "$b" == "$suite" ]; then
8462             return 0
8463         fi
8464     done
8465     return 1
8466 }
8467
8468 min_ost_size () {
8469         $LFS df | grep OST | awk '{print $4}' | sort -un | head -1
8470 }
8471
8472 #
8473 # Get the available size (KB) of a given obd target.
8474 #
8475 get_obd_size() {
8476         local facet=$1
8477         local obd=$2
8478         local size
8479
8480         [[ $facet != client ]] || return 0
8481
8482         size=$(do_facet $facet $LCTL get_param -n *.$obd.kbytesavail | head -n1)
8483         echo -n $size
8484 }
8485
8486 #
8487 # Get the page size (bytes) on a given facet node.
8488 # The local client page_size is directly available in PAGE_SIZE.
8489 #
8490 get_page_size() {
8491         local facet=$1
8492         local page_size=$(getconf PAGE_SIZE 2>/dev/null)
8493
8494         [ -z "$CLIENTONLY" -a "$facet" != "client" ] &&
8495                 page_size=$(do_facet $facet getconf PAGE_SIZE)
8496         echo -n ${page_size:-4096}
8497 }
8498
8499 #
8500 # Get the block count of the filesystem.
8501 #
8502 get_block_count() {
8503         local facet=$1
8504         local device=$2
8505         local count
8506
8507         [ -z "$CLIENTONLY" ] && count=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
8508                 awk '/^Block count:/ {print $3}')
8509         echo -n ${count:-0}
8510 }
8511
8512 # Get the block size of the filesystem.
8513 get_block_size() {
8514         local facet=$1
8515         local device=$2
8516         local size
8517
8518         [ -z "$CLIENTONLY" ] && size=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
8519                 awk '/^Block size:/ {print $3}')
8520         echo -n ${size:-0}
8521 }
8522
8523 # Check whether the "ea_inode" feature is enabled or not, to allow
8524 # ldiskfs xattrs over one block in size.  Allow both the historical
8525 # Lustre feature name (large_xattr) and the upstream name (ea_inode).
8526 large_xattr_enabled() {
8527         [[ $(facet_fstype $SINGLEMDS) == zfs ]] && return 1
8528
8529         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
8530
8531         do_facet $SINGLEMDS "$DUMPE2FS -h $mds_dev 2>&1 |
8532                 grep -E -q '(ea_inode|large_xattr)'"
8533         return ${PIPESTATUS[0]}
8534 }
8535
8536 # Get the maximum xattr size supported by the filesystem.
8537 max_xattr_size() {
8538         $LCTL get_param -n llite.*.max_easize
8539 }
8540
8541 # Dump the value of the named xattr from a file.
8542 get_xattr_value() {
8543     local xattr_name=$1
8544     local file=$2
8545
8546     echo "$(getfattr -n $xattr_name --absolute-names --only-values $file)"
8547 }
8548
8549 # Generate a string with size of $size bytes.
8550 generate_string() {
8551     local size=${1:-1024} # in bytes
8552
8553     echo "$(head -c $size < /dev/zero | tr '\0' y)"
8554 }
8555
8556 reformat_external_journal() {
8557         local facet=$1
8558         local var
8559
8560         var=${facet}_JRN
8561         if [ -n "${!var}" ]; then
8562                 local rcmd="do_facet $facet"
8563
8564                 echo "reformat external journal on $facet:${!var}"
8565                 ${rcmd} mke2fs -O journal_dev ${!var} || return 1
8566         fi
8567 }
8568
8569 # MDT file-level backup/restore
8570 mds_backup_restore() {
8571         local facet=$1
8572         local igif=$2
8573         local devname=$(mdsdevname $(facet_number $facet))
8574         local mntpt=$(facet_mntpt brpt)
8575         local rcmd="do_facet $facet"
8576         local metaea=${TMP}/backup_restore.ea
8577         local metadata=${TMP}/backup_restore.tgz
8578         local opts=${MDS_MOUNT_FS_OPTS}
8579         local svc=${facet}_svc
8580
8581         if ! ${rcmd} test -b ${devname}; then
8582                 opts=$(csa_add "$opts" -o loop)
8583         fi
8584
8585         echo "file-level backup/restore on $facet:${devname}"
8586
8587         # step 1: build mount point
8588         ${rcmd} mkdir -p $mntpt
8589         # step 2: cleanup old backup
8590         ${rcmd} rm -f $metaea $metadata
8591         # step 3: mount dev
8592         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
8593         if [ ! -z $igif ]; then
8594                 # step 3.5: rm .lustre
8595                 ${rcmd} rm -rf $mntpt/ROOT/.lustre || return 1
8596         fi
8597         # step 4: backup metaea
8598         echo "backup EA"
8599         ${rcmd} "cd $mntpt && getfattr -R -d -m '.*' -P . > $metaea && cd -" ||
8600                 return 2
8601         # step 5: backup metadata
8602         echo "backup data"
8603         ${rcmd} tar zcf $metadata -C $mntpt/ . > /dev/null 2>&1 || return 3
8604         # step 6: umount
8605         ${rcmd} $UMOUNT $mntpt || return 4
8606         # step 8: reformat dev
8607         echo "reformat new device"
8608         format_mdt $(facet_number $facet)
8609         # step 9: mount dev
8610         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 7
8611         # step 10: restore metadata
8612         echo "restore data"
8613         ${rcmd} tar zxfp $metadata -C $mntpt > /dev/null 2>&1 || return 8
8614         # step 11: restore metaea
8615         echo "restore EA"
8616         ${rcmd} "cd $mntpt && setfattr --restore=$metaea && cd - " || return 9
8617         # step 12: remove recovery logs
8618         echo "remove recovery logs"
8619         ${rcmd} rm -fv $mntpt/OBJECTS/* $mntpt/CATALOGS
8620         # step 13: umount dev
8621         ${rcmd} $UMOUNT $mntpt || return 10
8622         # step 14: cleanup tmp backup
8623         ${rcmd} rm -f $metaea $metadata
8624         # step 15: reset device label - it's not virgin on
8625         ${rcmd} e2label $devname ${!svc}
8626 }
8627
8628 # remove OI files
8629 mds_remove_ois() {
8630         local facet=$1
8631         local idx=$2
8632         local devname=$(mdsdevname $(facet_number $facet))
8633         local mntpt=$(facet_mntpt brpt)
8634         local rcmd="do_facet $facet"
8635         local opts=${MDS_MOUNT_FS_OPTS}
8636
8637         if ! ${rcmd} test -b ${devname}; then
8638                 opts=$(csa_add "$opts" -o loop)
8639         fi
8640
8641         echo "removing OI files on $facet: idx=${idx}"
8642
8643         # step 1: build mount point
8644         ${rcmd} mkdir -p $mntpt
8645         # step 2: mount dev
8646         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
8647         if [ -z $idx ]; then
8648                 # step 3: remove all OI files
8649                 ${rcmd} rm -fv $mntpt/oi.16*
8650         elif [ $idx -lt 2 ]; then
8651                 ${rcmd} rm -fv $mntpt/oi.16.${idx}
8652         else
8653                 local i
8654
8655                 # others, rm oi.16.[idx, idx * idx, idx ** ...]
8656                 for ((i=${idx}; i<64; i=$((i * idx)))); do
8657                         ${rcmd} rm -fv $mntpt/oi.16.${i}
8658                 done
8659         fi
8660         # step 4: umount
8661         ${rcmd} $UMOUNT $mntpt || return 2
8662         # OI files will be recreated when mounted as lustre next time.
8663 }
8664
8665 # generate maloo upload-able log file name
8666 # \param logname specify unique part of file name
8667 generate_logname() {
8668         local logname=${1:-"default_logname"}
8669
8670         echo "$TESTLOG_PREFIX.$TESTNAME.$logname.$(hostname -s).log"
8671 }
8672
8673 # make directory on different MDTs
8674 test_mkdir() {
8675         local path
8676         local p_option
8677         local dirstripe_count=${DIRSTRIPE_COUNT:-"2"}
8678         local dirstripe_index=${DIRSTRIPE_INDEX:-$((base % $MDSCOUNT))}
8679         local OPTIND=1
8680
8681         while getopts "c:i:p" opt; do
8682                 case $opt in
8683                         c) dirstripe_count=$OPTARG;;
8684                         i) dirstripe_index=$OPTARG;;
8685                         p) p_option="-p";;
8686                         \?) error "only support -i -c -p";;
8687                 esac
8688         done
8689
8690         shift $((OPTIND - 1))
8691         [ $# -eq 1 ] || error "Only creating single directory is supported"
8692         path="$*"
8693
8694         if [ "$p_option" == "-p" ]; then
8695                 local parent=$(dirname $path)
8696
8697                 [ -d $path ] && return 0
8698                 if [ ! -d ${parent} ]; then
8699                         mkdir -p ${parent} ||
8700                                 error "mkdir parent '$parent' failed"
8701                 fi
8702         fi
8703
8704         if [ $MDSCOUNT -le 1 ]; then
8705                 mkdir $path || error "mkdir '$path' failed"
8706         else
8707                 local mdt_index
8708
8709                 if [ $dirstripe_index -eq -1 ]; then
8710                         mdt_index=$((base % MDSCOUNT))
8711                 else
8712                         mdt_index=$dirstripe_index
8713                 fi
8714
8715                 if (($MDS1_VERSION >= $(version_code 2.8.0))); then
8716                         if [ $dirstripe_count -eq -1 ]; then
8717                                 dirstripe_count=$((RANDOM % MDSCOUNT + 1))
8718                         fi
8719                 else
8720                         dirstripe_count=1
8721                 fi
8722
8723                 echo "striped dir -i$mdt_index -c$dirstripe_count $path"
8724                 $LFS mkdir -i$mdt_index -c$dirstripe_count $path ||
8725                         error "mkdir -i $mdt_index -c$dirstripe_count $path failed"
8726         fi
8727 }
8728
8729 # free_fd: find the smallest and not in use file descriptor [above @last_fd]
8730 #
8731 # If called many times, passing @last_fd will avoid repeated searching
8732 # already-open FDs repeatedly if we know they are still in use.
8733 #
8734 # usage: free_fd [last_fd]
8735 free_fd()
8736 {
8737         local max_fd=$(ulimit -n)
8738         local fd=$((${1:-2} + 1))
8739
8740         while [[ $fd -le $max_fd && -e /proc/self/fd/$fd ]]; do
8741                 ((++fd))
8742         done
8743         [ $fd -lt $max_fd ] || error "finding free file descriptor failed"
8744         echo $fd
8745 }
8746
8747 check_mount_and_prep()
8748 {
8749         is_mounted $MOUNT || setupall
8750
8751         rm -rf $DIR/[df][0-9]* || error "Fail to cleanup the env!"
8752         mkdir $DIR/$tdir || error "Fail to mkdir $DIR/$tdir."
8753         for idx in $(seq $MDSCOUNT); do
8754                 local name="MDT$(printf '%04x' $((idx - 1)))"
8755                 rm -rf $MOUNT/.lustre/lost+found/$name/*
8756         done
8757 }
8758
8759 # calcule how many ost-objects to be created.
8760 precreated_ost_obj_count()
8761 {
8762         local mdt_idx=$1
8763         local ost_idx=$2
8764         local mdt_name="MDT$(printf '%04x' $mdt_idx)"
8765         local ost_name="OST$(printf '%04x' $ost_idx)"
8766         local proc_path="${FSNAME}-${ost_name}-osc-${mdt_name}"
8767         local last_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \
8768                         osp.$proc_path.prealloc_last_id)
8769         local next_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \
8770                         osp.$proc_path.prealloc_next_id)
8771         echo $((last_id - next_id + 1))
8772 }
8773
8774 check_file_in_pool()
8775 {
8776         local file=$1
8777         local pool=$2
8778         local tlist="$3"
8779         local res=$($LFS getstripe $file | grep 0x | cut -f2)
8780         for i in $res
8781         do
8782                 for t in $tlist ; do
8783                         [ "$i" -eq "$t" ] && continue 2
8784                 done
8785
8786                 echo "pool list: $tlist"
8787                 echo "striping: $res"
8788                 error_noexit "$file not allocated in $pool"
8789                 return 1
8790         done
8791         return 0
8792 }
8793
8794 pool_add() {
8795         echo "Creating new pool"
8796         local pool=$1
8797
8798         create_pool $FSNAME.$pool ||
8799                 { error_noexit "No pool created, result code $?"; return 1; }
8800         [ $($LFS pool_list $FSNAME | grep -c "$FSNAME.${pool}\$") -eq 1 ] ||
8801                 { error_noexit "$pool not in lfs pool_list"; return 2; }
8802 }
8803
8804 pool_add_targets() {
8805         echo "Adding targets to pool"
8806         local pool=$1
8807         local first=$2
8808         local last=$3
8809         local step=${4:-1}
8810
8811         if [ -z $last ]; then
8812                 local list=$first
8813         else
8814                 local list=$(seq $first $step $last)
8815         fi
8816
8817         local t=$(for i in $list; do printf "$FSNAME-OST%04x_UUID " $i; done)
8818         do_facet mgs $LCTL pool_add \
8819                         $FSNAME.$pool $FSNAME-OST[$first-$last/$step]
8820
8821         # wait for OSTs to be added to the pool
8822         for mds_id in $(seq $MDSCOUNT); do
8823                 local mdt_id=$((mds_id-1))
8824                 local lodname=$FSNAME-MDT$(printf "%04x" $mdt_id)-mdtlov
8825                 wait_update_facet mds$mds_id \
8826                         "lctl get_param -n lod.$lodname.pools.$pool |
8827                                 sort -u | tr '\n' ' ' " "$t" || {
8828                         error_noexit "mds$mds_id: Add to pool failed"
8829                         return 3
8830                 }
8831         done
8832         wait_update $HOSTNAME "lctl get_param -n lov.$FSNAME-*.pools.$pool \
8833                         | sort -u | tr '\n' ' ' " "$t" || {
8834                 error_noexit "Add to pool failed"
8835                 return 1
8836         }
8837         local lfscount=$($LFS pool_list $FSNAME.$pool | grep -c "\-OST")
8838         local addcount=$(((last - first) / step + 1))
8839         [ $lfscount -eq $addcount ] || {
8840                 error_noexit "lfs pool_list bad ost count" \
8841                                                 "$lfscount != $addcount"
8842                 return 2
8843         }
8844 }
8845
8846 pool_set_dir() {
8847         local pool=$1
8848         local tdir=$2
8849         echo "Setting pool on directory $tdir"
8850
8851         $LFS setstripe -c 2 -p $pool $tdir && return 0
8852
8853         error_noexit "Cannot set pool $pool to $tdir"
8854         return 1
8855 }
8856
8857 pool_check_dir() {
8858         local pool=$1
8859         local tdir=$2
8860         echo "Checking pool on directory $tdir"
8861
8862         local res=$($LFS getstripe --pool $tdir | sed "s/\s*$//")
8863         [ "$res" = "$pool" ] && return 0
8864
8865         error_noexit "Pool on '$tdir' is '$res', not '$pool'"
8866         return 1
8867 }
8868
8869 pool_dir_rel_path() {
8870         echo "Testing relative path works well"
8871         local pool=$1
8872         local tdir=$2
8873         local root=$3
8874
8875         mkdir -p $root/$tdir/$tdir
8876         cd $root/$tdir
8877         pool_set_dir $pool $tdir          || return 1
8878         pool_set_dir $pool ./$tdir        || return 2
8879         pool_set_dir $pool ../$tdir       || return 3
8880         pool_set_dir $pool ../$tdir/$tdir || return 4
8881         rm -rf $tdir; cd - > /dev/null
8882 }
8883
8884 pool_alloc_files() {
8885         echo "Checking files allocation from directory pool"
8886         local pool=$1
8887         local tdir=$2
8888         local count=$3
8889         local tlist="$4"
8890
8891         local failed=0
8892         for i in $(seq -w 1 $count)
8893         do
8894                 local file=$tdir/file-$i
8895                 touch $file
8896                 check_file_in_pool $file $pool "$tlist" || \
8897                         failed=$((failed + 1))
8898         done
8899         [ "$failed" = 0 ] && return 0
8900
8901         error_noexit "$failed files not allocated in $pool"
8902         return 1
8903 }
8904
8905 pool_create_files() {
8906         echo "Creating files in pool"
8907         local pool=$1
8908         local tdir=$2
8909         local count=$3
8910         local tlist="$4"
8911
8912         mkdir -p $tdir
8913         local failed=0
8914         for i in $(seq -w 1 $count)
8915         do
8916                 local file=$tdir/spoo-$i
8917                 $LFS setstripe -p $pool $file
8918                 check_file_in_pool $file $pool "$tlist" || \
8919                         failed=$((failed + 1))
8920         done
8921         [ "$failed" = 0 ] && return 0
8922
8923         error_noexit "$failed files not allocated in $pool"
8924         return 1
8925 }
8926
8927 pool_lfs_df() {
8928         echo "Checking 'lfs df' output"
8929         local pool=$1
8930
8931         local t=$($LCTL get_param -n lov.$FSNAME-clilov-*.pools.$pool |
8932                         tr '\n' ' ')
8933         local res=$($LFS df --pool $FSNAME.$pool |
8934                         awk '{print $1}' |
8935                         grep "$FSNAME-OST" |
8936                         tr '\n' ' ')
8937         [ "$res" = "$t" ] && return 0
8938
8939         error_noexit "Pools OSTs '$t' is not '$res' that lfs df reports"
8940         return 1
8941 }
8942
8943 pool_file_rel_path() {
8944         echo "Creating files in a pool with relative pathname"
8945         local pool=$1
8946         local tdir=$2
8947
8948         mkdir -p $tdir ||
8949                 { error_noexit "unable to create $tdir"; return 1 ; }
8950         local file="/..$tdir/$tfile-1"
8951         $LFS setstripe -p $pool $file ||
8952                 { error_noexit "unable to create $file" ; return 2 ; }
8953
8954         cd $tdir
8955         $LFS setstripe -p $pool $tfile-2 || {
8956                 error_noexit "unable to create $tfile-2 in $tdir"
8957                 return 3
8958         }
8959 }
8960
8961 pool_remove_first_target() {
8962         echo "Removing first target from a pool"
8963         local pool=$1
8964
8965         local pname="lov.$FSNAME-*.pools.$pool"
8966         local t=$($LCTL get_param -n $pname | head -1)
8967         do_facet mgs $LCTL pool_remove $FSNAME.$pool $t
8968         for mds_id in $(seq $MDSCOUNT); do
8969                 local mdt_id=$((mds_id-1))
8970                 local lodname=$FSNAME-MDT$(printf "%04x" $mdt_id)-mdtlov
8971                 wait_update_facet mds$mds_id \
8972                         "lctl get_param -n lod.$lodname.pools.$pool |
8973                                 grep $t" "" || {
8974                         error_noexit "mds$mds_id: $t not removed from" \
8975                         "$FSNAME.$pool"
8976                         return 2
8977                 }
8978         done
8979         wait_update $HOSTNAME "lctl get_param -n $pname | grep $t" "" || {
8980                 error_noexit "$t not removed from $FSNAME.$pool"
8981                 return 1
8982         }
8983 }
8984
8985 pool_remove_all_targets() {
8986         echo "Removing all targets from pool"
8987         local pool=$1
8988         local file=$2
8989         local pname="lov.$FSNAME-*.pools.$pool"
8990         for t in $($LCTL get_param -n $pname | sort -u)
8991         do
8992                 do_facet mgs $LCTL pool_remove $FSNAME.$pool $t
8993         done
8994         for mds_id in $(seq $MDSCOUNT); do
8995                 local mdt_id=$((mds_id-1))
8996                 local lodname=$FSNAME-MDT$(printf "%04x" $mdt_id)-mdtlov
8997                 wait_update_facet mds$mds_id "lctl get_param -n \
8998                         lod.$lodname.pools.$pool" "" || {
8999                         error_noexit "mds$mds_id: Pool $pool not drained"
9000                         return 4
9001                 }
9002         done
9003         wait_update $HOSTNAME "lctl get_param -n $pname" "" || {
9004                 error_noexit "Pool $FSNAME.$pool cannot be drained"
9005                 return 1
9006         }
9007         # striping on an empty/nonexistant pool should fall back
9008         # to "pool of everything"
9009         touch $file || {
9010                 error_noexit "failed to use fallback striping for empty pool"
9011                 return 2
9012         }
9013         # setstripe on an empty pool should fail
9014         $LFS setstripe -p $pool $file 2>/dev/null && {
9015                 error_noexit "expected failure when creating file" \
9016                                                         "with empty pool"
9017                 return 3
9018         }
9019         return 0
9020 }
9021
9022 pool_remove() {
9023         echo "Destroying pool"
9024         local pool=$1
9025         local file=$2
9026
9027         do_facet mgs $LCTL pool_destroy $FSNAME.$pool
9028
9029         sleep 2
9030         # striping on an empty/nonexistant pool should fall back
9031         # to "pool of everything"
9032         touch $file || {
9033                 error_noexit "failed to use fallback striping for missing pool"
9034                 return 1
9035         }
9036         # setstripe on an empty pool should fail
9037         $LFS setstripe -p $pool $file 2>/dev/null && {
9038                 error_noexit "expected failure when creating file" \
9039                                                         "with missing pool"
9040                 return 2
9041         }
9042
9043         # get param should return err once pool is gone
9044         if wait_update $HOSTNAME "lctl get_param -n \
9045                 lov.$FSNAME-*.pools.$pool 2>/dev/null || echo foo" "foo"
9046         then
9047                 remove_pool_from_list $FSNAME.$pool
9048                 return 0
9049         fi
9050         error_noexit "Pool $FSNAME.$pool is not destroyed"
9051         return 3
9052 }
9053
9054 # Get and check the actual stripe count of one file.
9055 # Usage: check_stripe_count <file> <expected_stripe_count>
9056 check_stripe_count() {
9057         local file=$1
9058         local expected=$2
9059         local actual
9060
9061         [[ -z "$file" || -z "$expected" ]] &&
9062                 error "check_stripe_count: invalid argument"
9063
9064         local cmd="$LFS getstripe -c $file"
9065         actual=$($cmd) || error "$cmd failed"
9066         actual=${actual%% *}
9067
9068         if [[ $actual -ne $expected ]]; then
9069                 [[ $expected -eq -1 ]] || { $LFS getstripe $file;
9070                         error "$cmd not expected ($expected): found $actual"; }
9071                 [[ $actual -eq $OSTCOUNT ]] || { $LFS getstripe $file;
9072                         error "$cmd not OST count ($OSTCOUNT): found $actual"; }
9073         fi
9074 }
9075
9076 # Get and check the actual list of OST indices on one file.
9077 # Usage: check_obdidx <file> <expected_comma_separated_list_of_ost_indices>
9078 check_obdidx() {
9079         local file=$1
9080         local expected=$2
9081         local obdidx
9082
9083         [[ -z "$file" || -z "$expected" ]] &&
9084                 error "check_obdidx: invalid argument!"
9085
9086         obdidx=$(comma_list $($LFS getstripe $file | grep -A $OSTCOUNT obdidx |
9087                               grep -v obdidx | awk '{print $1}' | xargs))
9088
9089         [[ $obdidx = $expected ]] ||
9090                 error "list of OST indices on $file is $obdidx," \
9091                       "should be $expected"
9092 }
9093
9094 # Get and check the actual OST index of the first stripe on one file.
9095 # Usage: check_start_ost_idx <file> <expected_start_ost_idx>
9096 check_start_ost_idx() {
9097         local file=$1
9098         local expected=$2
9099         local start_ost_idx
9100
9101         [[ -z "$file" || -z "$expected" ]] &&
9102                 error "check_start_ost_idx: invalid argument!"
9103
9104         start_ost_idx=$($LFS getstripe $file | grep -A 1 obdidx |
9105                          grep -v obdidx | awk '{print $1}')
9106
9107         [[ $start_ost_idx = $expected ]] ||
9108                 error "OST index of the first stripe on $file is" \
9109                       "$start_ost_idx, should be $expected"
9110 }
9111
9112 killall_process () {
9113         local clients=${1:-$(hostname)}
9114         local name=$2
9115         local signal=$3
9116         local rc=0
9117
9118         do_nodes $clients "killall $signal $name"
9119 }
9120
9121 lsnapshot_create()
9122 {
9123         do_facet mgs "$LCTL snapshot_create -F $FSNAME $*"
9124 }
9125
9126 lsnapshot_destroy()
9127 {
9128         do_facet mgs "$LCTL snapshot_destroy -F $FSNAME $*"
9129 }
9130
9131 lsnapshot_modify()
9132 {
9133         do_facet mgs "$LCTL snapshot_modify -F $FSNAME $*"
9134 }
9135
9136 lsnapshot_list()
9137 {
9138         do_facet mgs "$LCTL snapshot_list -F $FSNAME $*"
9139 }
9140
9141 lsnapshot_mount()
9142 {
9143         do_facet mgs "$LCTL snapshot_mount -F $FSNAME $*"
9144 }
9145
9146 lsnapshot_umount()
9147 {
9148         do_facet mgs "$LCTL snapshot_umount -F $FSNAME $*"
9149 }
9150
9151 lss_err()
9152 {
9153         local msg=$1
9154
9155         do_facet mgs "cat $LSNAPSHOT_LOG"
9156         error $msg
9157 }
9158
9159 lss_cleanup()
9160 {
9161         echo "Cleaning test environment ..."
9162
9163         # Every lsnapshot command takes exclusive lock with others,
9164         # so can NOT destroy the snapshot during list with 'xargs'.
9165         while true; do
9166                 local ssname=$(lsnapshot_list | grep snapshot_name |
9167                         grep lss_ | awk '{ print $2 }' | head -n 1)
9168                 [ -z "$ssname" ] && break
9169
9170                 lsnapshot_destroy -n $ssname -f ||
9171                         lss_err "Fail to destroy $ssname by force"
9172         done
9173 }
9174
9175 lss_gen_conf_one()
9176 {
9177         local facet=$1
9178         local role=$2
9179         local idx=$3
9180
9181         local host=$(facet_active_host $facet)
9182         local dir=$(dirname $(facet_vdevice $facet))
9183         local pool=$(zpool_name $facet)
9184         local lfsname=$(zfs_local_fsname $facet)
9185         local label=${FSNAME}-${role}$(printf '%04x' $idx)
9186
9187         do_facet mgs \
9188                 "echo '$host - $label zfs:${dir}/${pool}/${lfsname} - -' >> \
9189                 $LSNAPSHOT_CONF"
9190 }
9191
9192 lss_gen_conf()
9193 {
9194         do_facet mgs "rm -f $LSNAPSHOT_CONF"
9195         echo "Generating $LSNAPSHOT_CONF on MGS ..."
9196
9197         if ! combined_mgs_mds ; then
9198                 [ $(facet_fstype mgs) != zfs ] &&
9199                         skip "Lustre snapshot 1 only works for ZFS backend"
9200
9201                 local host=$(facet_active_host mgs)
9202                 local dir=$(dirname $(facet_vdevice mgs))
9203                 local pool=$(zpool_name mgs)
9204                 local lfsname=$(zfs_local_fsname mgs)
9205
9206                 do_facet mgs \
9207                         "echo '$host - MGS zfs:${dir}/${pool}/${lfsname} - -' \
9208                         >> $LSNAPSHOT_CONF" || lss_err "generate lss conf (mgs)"
9209         fi
9210
9211         for num in `seq $MDSCOUNT`; do
9212                 [ $(facet_fstype mds$num) != zfs ] &&
9213                         skip "Lustre snapshot 1 only works for ZFS backend"
9214
9215                 lss_gen_conf_one mds$num MDT $((num - 1)) ||
9216                         lss_err "generate lss conf (mds$num)"
9217         done
9218
9219         for num in `seq $OSTCOUNT`; do
9220                 [ $(facet_fstype ost$num) != zfs ] &&
9221                         skip "Lustre snapshot 1 only works for ZFS backend"
9222
9223                 lss_gen_conf_one ost$num OST $((num - 1)) ||
9224                         lss_err "generate lss conf (ost$num)"
9225         done
9226
9227         do_facet mgs "cat $LSNAPSHOT_CONF"
9228 }
9229
9230 # Parse 'lfs getstripe -d <path_with_dir_name>' for non-composite dir
9231 parse_plain_dir_param()
9232 {
9233         local invalues=($1)
9234         local param=""
9235
9236         if [[ ${invalues[0]} =~ "stripe_count:" ]]; then
9237                 param="-c ${invalues[1]}"
9238         fi
9239         if [[ ${invalues[2]} =~ "stripe_size:" ]]; then
9240                 param="$param -S ${invalues[3]}"
9241         fi
9242         if [[ ${invalues[4]} =~ "pattern:" ]]; then
9243                 if [[ ${invalues[5]} =~ "stripe_offset:" ]]; then
9244                         param="$param -i ${invalues[6]}"
9245                 else
9246                         param="$param -L ${invalues[5]} -i ${invalues[7]}"
9247                 fi
9248         elif [[ ${invalues[4]} =~ "stripe_offset:" ]]; then
9249                 param="$param -i ${invalues[5]}"
9250         fi
9251         echo "$param"
9252 }
9253
9254 parse_plain_param()
9255 {
9256         local line=$1
9257         local val=$(awk '{print $2}' <<< $line)
9258
9259         if [[ $line =~ ^"lmm_stripe_count:" ]]; then
9260                 echo "-c $val"
9261         elif [[ $line =~ ^"lmm_stripe_size:" ]]; then
9262                 echo "-S $val"
9263         elif [[ $line =~ ^"lmm_stripe_offset:" ]]; then
9264                 echo "-i $val"
9265         elif [[ $line =~ ^"lmm_pattern:" ]]; then
9266                 echo "-L $val"
9267         fi
9268 }
9269
9270 parse_layout_param()
9271 {
9272         local mode=""
9273         local val=""
9274         local param=""
9275
9276         while read line; do
9277                 if [[ ! -z $line ]]; then
9278                         if [[ -z $mode ]]; then
9279                                 if [[ $line =~ ^"stripe_count:" ]]; then
9280                                         mode="plain_dir"
9281                                 elif [[ $line =~ ^"lmm_stripe_count:" ]]; then
9282                                         mode="plain_file"
9283                                 elif [[ $line =~ ^"lcm_layout_gen:" ]]; then
9284                                         mode="pfl"
9285                                 fi
9286                         fi
9287
9288                         if [[ $mode = "plain_dir" ]]; then
9289                                 param=$(parse_plain_dir_param "$line")
9290                         elif [[ $mode = "plain_file" ]]; then
9291                                 val=$(parse_plain_param "$line")
9292                                 [[ ! -z $val ]] && param="$param $val"
9293                         elif [[ $mode = "pfl" ]]; then
9294                                 val=$(echo $line | awk '{print $2}')
9295                                 if [[ $line =~ ^"lcme_extent.e_end:" ]]; then
9296                                         if [[ $val = "EOF" ]]; then
9297                                                 param="$param -E -1"
9298                                         else
9299                                                 param="$param -E $val"
9300                                         fi
9301                                 elif [[ $line =~ ^"stripe_count:" ]]; then
9302                                         # pfl dir
9303                                         val=$(parse_plain_dir_param "$line")
9304                                         param="$param $val"
9305                                 else
9306                                         #pfl file
9307                                         val=$(parse_plain_param "$line")
9308                                         [[ ! -z $val ]] && param="$param $val"
9309                                 fi
9310                         fi
9311                 fi
9312         done
9313         echo "$param"
9314 }
9315
9316 get_layout_param()
9317 {
9318         local param=$($LFS getstripe -d $1 | parse_layout_param)
9319         echo "$param"
9320 }
9321
9322 lfsck_verify_pfid()
9323 {
9324         local f
9325         local rc=0
9326
9327         # Cancel locks before setting lfsck_verify_pfid so that errors are more
9328         # controllable
9329         cancel_lru_locks mdc
9330         cancel_lru_locks osc
9331
9332         # make sure PFID is set correctly for files
9333         do_nodes $(comma_list $(osts_nodes)) \
9334                "$LCTL set_param -n obdfilter.${FSNAME}-OST*.lfsck_verify_pfid=1"
9335
9336         for f in "$@"; do
9337                 cat $f &> /dev/nullA ||
9338                         { rc=$?; echo "verify $f failed"; break; }
9339         done
9340
9341         do_nodes $(comma_list $(osts_nodes)) \
9342                "$LCTL set_param -n obdfilter.${FSNAME}-OST*.lfsck_verify_pfid=0"
9343         return $rc
9344 }
9345
9346 # check that clients "oscs" was evicted after "before"
9347 check_clients_evicted() {
9348         local before=$1
9349         shift
9350         local oscs=${@}
9351         local osc
9352         local rc=0
9353
9354         for osc in $oscs; do
9355                 ((rc++))
9356                 echo "Check state for $osc"
9357                 local evicted=$(do_facet client $LCTL get_param osc.$osc.state |
9358                         tail -n 3 | awk -F"[ [,]" \
9359                         '/EVICTED ]$/ { if (mx<$5) {mx=$5;} } END { print mx }')
9360                 if (($? == 0)) && (($evicted > $before)); then
9361                         echo "$osc is evicted at $evicted"
9362                         ((rc--))
9363                 fi
9364         done
9365
9366         [ $rc -eq 0 ] || error "client not evicted from OST"
9367 }
9368
9369 # check that clients OSCS current_state is FULL
9370 check_clients_full() {
9371         local timeout=$1
9372         shift
9373         local oscs=${@}
9374
9375         for osc in $oscs; do
9376                 wait_update_facet client \
9377                         "lctl get_param -n osc.$osc.state |
9378                         grep 'current_state: FULL'" \
9379                         "current_state: FULL" $timeout
9380                 [ $? -eq 0 ] || error "$osc state is not FULL"
9381         done
9382 }
9383
9384 #Changelogs
9385 __changelog_deregister() {
9386         local facet=$1
9387         local mdt="$(facet_svc $facet)"
9388         local cl_user=$2
9389         local rc=0
9390
9391         # skip cleanup if no user registered for this MDT
9392         [ -z "$cl_user" ] && echo "$mdt: no changelog user" && return 0
9393         # user is no longer registered, skip cleanup
9394         changelog_users "$facet" | grep -q "$cl_user" ||
9395                 { echo "$mdt: changelog user '$cl_user' not found"; return 0; }
9396
9397         # From this point, if any operation fails, it is an error
9398         __changelog_clear $facet $cl_user 0 ||
9399                 error_noexit "$mdt: changelog_clear $cl_user 0 fail: $rc"
9400         do_facet $facet $LCTL --device $mdt changelog_deregister $cl_user ||
9401                 error_noexit "$mdt: changelog_deregister '$cl_user' fail: $rc"
9402 }
9403
9404 declare -Ax CL_USERS
9405 changelog_register() {
9406         for M in $(seq $MDSCOUNT); do
9407                 local facet=mds$M
9408                 local mdt="$(facet_svc $facet)"
9409                 local cl_mask
9410
9411                 cl_mask=$(do_facet $facet $LCTL get_param \
9412                              mdd.${mdt}.changelog_mask -n)
9413                 stack_trap "do_facet $facet $LCTL \
9414                         set_param mdd.$mdt.changelog_mask=\'$cl_mask\' -n" EXIT
9415                 do_facet $facet $LCTL set_param mdd.$mdt.changelog_mask=+hsm ||
9416                         error "$mdt: changelog_mask=+hsm failed: $?"
9417
9418                 local cl_user
9419                 cl_user=$(do_facet $facet \
9420                                   $LCTL --device $mdt changelog_register -n) ||
9421                         error "$mdt: register changelog user failed: $?"
9422                 stack_trap "__changelog_deregister $facet $cl_user" EXIT
9423
9424                 stack_trap "CL_USERS[$facet]='${CL_USERS[$facet]}'" EXIT
9425                 # Bash does not support nested arrays, but the format of a
9426                 # cl_user is constrained enough to use whitespaces as separators
9427                 CL_USERS[$facet]+="$cl_user "
9428         done
9429         echo "Registered $MDSCOUNT changelog users: '${CL_USERS[@]% }'"
9430 }
9431
9432 changelog_deregister() {
9433         local cl_user
9434         # bash assoc arrays do not guarantee to list keys in created order
9435         # so reorder to get same order than in changelog_register()
9436         local cl_facets=$(echo "${!CL_USERS[@]}" | tr " " "\n" | sort |
9437                           tr "\n" " ")
9438
9439         for facet in $cl_facets; do
9440                 for cl_user in ${CL_USERS[$facet]}; do
9441                         __changelog_deregister $facet $cl_user || return $?
9442                 done
9443                 unset CL_USERS[$facet]
9444         done
9445 }
9446
9447 changelog_users() {
9448         local facet=$1
9449         local service=$(facet_svc $facet)
9450
9451         do_facet $facet $LCTL get_param -n mdd.$service.changelog_users
9452 }
9453
9454 changelog_user_rec() {
9455         local facet=$1
9456         local cl_user=$2
9457         local service=$(facet_svc $facet)
9458
9459         changelog_users $facet | awk '$1 == "'$cl_user'" { print $2 }'
9460 }
9461
9462 changelog_chmask() {
9463         local mask=$1
9464
9465         do_nodes $(comma_list $(mdts_nodes)) \
9466                 $LCTL set_param mdd.*.changelog_mask="$mask"
9467 }
9468
9469 # usage: __changelog_clear FACET CL_USER [+]INDEX
9470 __changelog_clear()
9471 {
9472         local facet=$1
9473         local mdt="$(facet_svc $facet)"
9474         local cl_user=$2
9475         local -i rec
9476
9477         case "$3" in
9478         +*)
9479                 # Remove the leading '+'
9480                 rec=${3:1}
9481                 rec+=$(changelog_user_rec $facet $cl_user)
9482                 ;;
9483         *)
9484                 rec=$3
9485                 ;;
9486         esac
9487
9488         if [ $rec -eq 0 ]; then
9489                 echo "$mdt: clear the changelog for $cl_user of all records"
9490         else
9491                 echo "$mdt: clear the changelog for $cl_user to record #$rec"
9492         fi
9493         $LFS changelog_clear $mdt $cl_user $rec
9494 }
9495
9496 # usage: changelog_clear [+]INDEX
9497 #
9498 # If INDEX is prefixed with '+', increment every changelog user's record index
9499 # by INDEX. Otherwise, clear the changelog up to INDEX for every changelog
9500 # users.
9501 changelog_clear() {
9502         local rc
9503         # bash assoc arrays do not guarantee to list keys in created order
9504         # so reorder to get same order than in changelog_register()
9505         local cl_facets=$(echo "${!CL_USERS[@]}" | tr " " "\n" | sort |
9506                           tr "\n" " ")
9507
9508         for facet in $cl_facets; do
9509                 for cl_user in ${CL_USERS[$facet]}; do
9510                         __changelog_clear $facet $cl_user $1 || rc=${rc:-$?}
9511                 done
9512         done
9513
9514         return ${rc:-0}
9515 }
9516
9517 changelog_dump() {
9518         for M in $(seq $MDSCOUNT); do
9519                 local facet=mds$M
9520                 local mdt="$(facet_svc $facet)"
9521
9522                 $LFS changelog $mdt | sed -e 's/^/'$mdt'./'
9523         done
9524 }
9525
9526 changelog_extract_field() {
9527         local cltype=$1
9528         local file=$2
9529         local identifier=$3
9530
9531         changelog_dump | gawk "/$cltype.*$file$/ {
9532                 print gensub(/^.* "$identifier'(\[[^\]]*\]).*$/,"\\1",1)}' |
9533                 tail -1
9534 }
9535
9536 # Prints a changelog record produced by "lfs changelog" as an associative array
9537 #
9538 # Example:
9539 # $> changelog2array 16 01CREAT 10:28:46.968438800 2018.03.09 0x0 \
9540 #                    t=[0x200000401:0x10:0x0] j=touch.501 ef=0xf u=501:501 \
9541 #                    nid=0@lo p=[0x200000007:0x1:0x0] blob
9542 # ([index]='16' [type]='CREAT' [time]='10:28:46.968438800'
9543 #  [date]='2018.03.09' [flags]=0x0 ['target-fid']='[0x200000401:0x10:0x0]'
9544 #  ['jobid']='touch.501' ['extra-flags']='0x0f' [uid]='0' ['gid']='0'
9545 #  ['nid']='0@lo' ['parent-fid']='[0x200000007:0x1:0x0]')
9546 #
9547 # Note that the changelog record is not quoted
9548 # Also note that the line breaks in the output were only added for readability
9549 #
9550 # Typically, you want to eval the output of the command to fill an actual
9551 # associative array, like this:
9552 # $> eval declare -A changelog=$(changelog2array $entry)
9553 #
9554 # It can then be accessed like any bash associative array:
9555 # $> echo "${changelog[index]}" "${changelog[type]}" "${changelog[flags]}"
9556 # 16 CREAT 0x0
9557 # $> echo "${changelog[uid]}":"${changelog[gid]}"
9558 # 501:501
9559 #
9560 changelog2array()
9561 {
9562         # Start the array
9563         printf '('
9564
9565         # A changelog, as printed by "lfs changelog" typically looks like this:
9566         # <index> <type> <time> <date> <flags> <key1=value1> <key2=value2> ...
9567
9568         # Parse the positional part of the changelog
9569
9570         # changelog_dump() prefixes records with their mdt's name
9571         local index="${1##*.}"
9572
9573         printf "[index]='%s' [type]='%s' [time]='%s' [date]='%s' [flags]='%s'" \
9574                "$index" "${2:2}" "$3" "$4" "$5"
9575
9576         # Parse the key/value part of the changelog
9577         for arg in "${@:5}"; do
9578                 # Check it matches a key=value syntax
9579                 [[ "$arg" =~ ^[[:alpha:]]+= ]] || continue
9580
9581                 local key="${arg%%=*}"
9582                 local value="${arg#*=}"
9583
9584                 case "$key" in
9585                 u)
9586                         # u is actually for uid AND gid: u=UID:GID
9587                         printf " [uid]='%s'" "${value%:*}"
9588                         key=gid
9589                         value="${value#*:}"
9590                         ;;
9591                 t)
9592                         key=target-fid
9593                         value="${value#[}"
9594                         value="${value%]}"
9595                         ;;
9596                 j)
9597                         key=jobid
9598                         ;;
9599                 p)
9600                         key=parent-fid
9601                         value="${value#[}"
9602                         value="${value%]}"
9603                         ;;
9604                 ef)
9605                         key=extra-flags
9606                         ;;
9607                 m)
9608                         key=mode
9609                         ;;
9610                 x)
9611                         key=xattr
9612                         ;;
9613                 *)
9614                         ;;
9615                 esac
9616
9617                 printf " ['%s']='%s'" "$key" "$value"
9618         done
9619
9620         # end the array
9621         printf ')'
9622 }
9623
9624 # Format and print a changelog record
9625 #
9626 # Interpreted sequences are:
9627 #       %%      a single %
9628 #       %f      the "flags" attribute of a changelog record
9629 __changelog_printf()
9630 {
9631         local format="$1"
9632
9633         local -i i
9634         for ((i = 0; i < ${#format}; i++)); do
9635                 local char="${format:$i:1}"
9636                 if [ "$char" != % ]; then
9637                         printf '%c' "$char"
9638                         continue
9639                 fi
9640
9641                 i+=1
9642                 char="${format:$i:1}"
9643                 case "$char" in
9644                 f)
9645                         printf '%s' "${changelog[flags]}"
9646                         ;;
9647                 %)
9648                         printf '%'
9649                         ;;
9650                 esac
9651         done
9652         printf '\n'
9653 }
9654
9655 # Filter changelog records
9656 changelog_find()
9657 {
9658         local -A filter
9659         local action='print'
9660         local format
9661
9662         while [ $# -gt 0 ]; do
9663                 case "$1" in
9664                 -print)
9665                         action='print'
9666                         ;;
9667                 -printf)
9668                         action='printf'
9669                         format="$2"
9670                         shift
9671                         ;;
9672                 -*)
9673                         filter[${1#-}]="$2"
9674                         shift
9675                         ;;
9676                 esac
9677                 shift
9678         done
9679
9680         local found=false
9681         local record
9682         changelog_dump | { while read -r record; do
9683                 eval local -A changelog=$(changelog2array $record)
9684                 for key in "${!filter[@]}"; do
9685                         case "$key" in
9686                         *)
9687                                 [ "${changelog[$key]}" == "${filter[$key]}" ]
9688                                 ;;
9689                         esac || continue 2
9690                 done
9691
9692                 found=true
9693
9694                 case "${action:-print}" in
9695                 print)
9696                         printf '%s\n' "$record"
9697                         ;;
9698                 printf)
9699                         __changelog_printf "$format"
9700                         ;;
9701                 esac
9702         done; $found; }
9703 }
9704
9705 restore_layout() {
9706         local dir=$1
9707         local layout=$2
9708
9709         [ ! -d "$dir" ] && return
9710
9711         [ -z "$layout" ] && {
9712                 $LFS setstripe -d $dir || error "error deleting stripe '$dir'"
9713                 return
9714         }
9715
9716         setfattr -n trusted.lov -v $layout $dir ||
9717                 error "error restoring layout '$layout' to '$dir'"
9718 }
9719
9720 # save the layout of a directory, the returned string will be used by
9721 # restore_layout() to restore the layout
9722 save_layout() {
9723         local dir=$1
9724         local str=$(getfattr -n trusted.lov --absolute-names -e hex $dir \
9725                     2> /dev/null | awk -F'=' '/trusted.lov/{ print $2 }')
9726         echo "$str"
9727 }
9728
9729 # save layout of a directory and restore it at exit
9730 save_layout_restore_at_exit() {
9731         local dir=$1
9732         local layout=$(save_layout $dir)
9733
9734         stack_trap "restore_layout $dir $layout" EXIT
9735 }
9736
9737 verify_yaml_layout() {
9738         local src=$1
9739         local dst=$2
9740         local temp=$3
9741         local msg_prefix=$4
9742
9743         echo "getstripe --yaml $src"
9744         $LFS getstripe --yaml $src > $temp || error "getstripe $src failed"
9745         echo "setstripe --yaml=$temp $dst"
9746         $LFS setstripe --yaml=$temp $dst|| error "setstripe $dst failed"
9747
9748         echo "compare"
9749         local layout1=$(get_layout_param $src)
9750         local layout2=$(get_layout_param $dst)
9751         # compare their layout info
9752         [ "$layout1" == "$layout2" ] ||
9753                 error "$msg_prefix $src/$dst layouts are not equal"
9754 }
9755
9756 is_project_quota_supported() {
9757         $ENABLE_PROJECT_QUOTAS || return 1
9758
9759         [[ "$(facet_fstype $SINGLEMDS)" == "ldiskfs" &&
9760            $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.9.55) ]] &&
9761                 do_facet mds1 lfs --help |& grep -q project && return 0
9762
9763         [[ "$(facet_fstype $SINGLEMDS)" == "zfs" &&
9764            $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.10.53) ]] &&
9765                 do_facet mds1 $ZPOOL get all | grep -q project_quota && return 0
9766
9767         return 1
9768 }
9769
9770 # ZFS project quota enable/disable:
9771 #   This  feature  will  become  active as soon as it is enabled and will never
9772 #   return to being disabled. Each filesystem will be upgraded automatically
9773 #   when remounted or when [a] new file is created under that filesystem. The
9774 #   upgrade can also be triggered on filesystems via `zfs set version=current
9775 #   <pool/fs>`. The upgrade process runs in the background and may take a
9776 #   while to complete for the filesystems containing a large number of files.
9777 enable_project_quota() {
9778         is_project_quota_supported || return 0
9779         local zkeeper=${KEEP_ZPOOL}
9780         stack_trap "KEEP_ZPOOL=$zkeeper" EXIT
9781         KEEP_ZPOOL="true"
9782         stopall || error "failed to stopall (1)"
9783
9784         local zfeat_en="feature@project_quota=enabled"
9785         for facet in $(seq -f mds%g $MDSCOUNT) $(seq -f ost%g $OSTCOUNT); do
9786                 local facet_fstype=${facet:0:3}1_FSTYPE
9787                 local devname
9788
9789                 if [ "${!facet_fstype}" = "zfs" ]; then
9790                         devname=$(zpool_name ${facet})
9791                         do_facet ${facet} $ZPOOL set "$zfeat_en" $devname ||
9792                                 error "$ZPOOL set $zfeat_en $devname"
9793                 else
9794                         [ ${facet:0:3} == "mds" ] &&
9795                                 devname=$(mdsdevname ${facet:3}) ||
9796                                 devname=$(ostdevname ${facet:3})
9797                         do_facet ${facet} $TUNE2FS -O project $devname ||
9798                                 error "tune2fs $devname failed"
9799                 fi
9800         done
9801
9802         KEEP_ZPOOL="${zkeeper}"
9803         mount
9804         setupall
9805 }
9806
9807 disable_project_quota() {
9808         is_project_quota_supported || return 0
9809         [ "$mds1_FSTYPE" != "ldiskfs" ] && return 0
9810         stopall || error "failed to stopall (1)"
9811
9812         for num in $(seq $MDSCOUNT); do
9813                 do_facet mds$num $TUNE2FS -Q ^prj $(mdsdevname $num) ||
9814                         error "tune2fs $(mdsdevname $num) failed"
9815         done
9816
9817         for num in $(seq $OSTCOUNT); do
9818                 do_facet ost$num $TUNE2FS -Q ^prj $(ostdevname $num) ||
9819                         error "tune2fs $(ostdevname $num) failed"
9820         done
9821
9822         mount
9823         setupall
9824 }
9825
9826 #
9827 # In order to test multiple remote HSM agents, a new facet type named "AGT" and
9828 # the following associated variables are added:
9829 #
9830 # AGTCOUNT: number of agents
9831 # AGTDEV{N}: target HSM mount point (root path of the backend)
9832 # agt{N}_HOST: hostname of the agent agt{N}
9833 # SINGLEAGT: facet of the single agent
9834 #
9835 # The number of agents is initialized as the number of remote client nodes.
9836 # By default, only single copytool is started on a remote client/agent. If there
9837 # was no remote client, then the copytool will be started on the local client.
9838 #
9839 init_agt_vars() {
9840         local n
9841         local agent
9842
9843         export AGTCOUNT=${AGTCOUNT:-$((CLIENTCOUNT - 1))}
9844         [[ $AGTCOUNT -gt 0 ]] || AGTCOUNT=1
9845
9846         export SHARED_DIRECTORY=${SHARED_DIRECTORY:-$TMP}
9847         if [[ $CLIENTCOUNT -gt 1 ]] &&
9848                 ! check_shared_dir $SHARED_DIRECTORY $CLIENTS; then
9849                 skip_env "SHARED_DIRECTORY should be accessible"\
9850                          "on all client nodes"
9851                 exit 0
9852         fi
9853
9854         # We used to put the HSM archive in $SHARED_DIRECTORY but that
9855         # meant NFS issues could hose sanity-hsm sessions. So now we
9856         # use $TMP instead.
9857         for n in $(seq $AGTCOUNT); do
9858                 eval export AGTDEV$n=\$\{AGTDEV$n:-"$TMP/arc$n"\}
9859                 agent=CLIENT$((n + 1))
9860                 if [[ -z "${!agent}" ]]; then
9861                         [[ $CLIENTCOUNT -eq 1 ]] && agent=CLIENT1 ||
9862                                 agent=CLIENT2
9863                 fi
9864                 eval export agt${n}_HOST=\$\{agt${n}_HOST:-${!agent}\}
9865                 local var=agt${n}_HOST
9866                 [[ ! -z "${!var}" ]] || error "agt${n}_HOST is empty!"
9867         done
9868
9869         export SINGLEAGT=${SINGLEAGT:-agt1}
9870
9871         export HSMTOOL=${HSMTOOL:-"lhsmtool_posix"}
9872         export HSMTOOL_VERBOSE=${HSMTOOL_VERBOSE:-""}
9873         export HSMTOOL_UPDATE_INTERVAL=${HSMTOOL_UPDATE_INTERVAL:=""}
9874         export HSMTOOL_EVENT_FIFO=${HSMTOOL_EVENT_FIFO:=""}
9875         export HSMTOOL_TESTDIR
9876         export HSMTOOL_BASE=$(basename "$HSMTOOL" | cut -f1 -d" ")
9877
9878         HSM_ARCHIVE_NUMBER=2
9879
9880         # The test only support up to 10 MDTs
9881         MDT_PREFIX="mdt.$FSNAME-MDT000"
9882         HSM_PARAM="${MDT_PREFIX}0.hsm"
9883
9884         # archive is purged at copytool setup
9885         HSM_ARCHIVE_PURGE=true
9886
9887         # Don't allow copytool error upon start/setup
9888         HSMTOOL_NOERROR=false
9889 }
9890
9891 # Get the backend root path for the given agent facet.
9892 copytool_device() {
9893         local facet=$1
9894         local dev=AGTDEV$(facet_number $facet)
9895
9896         echo -n ${!dev}
9897 }
9898
9899 get_mdt_devices() {
9900         local mdtno
9901         # get MDT device for each mdc
9902         for mdtno in $(seq 1 $MDSCOUNT); do
9903                 local idx=$(($mdtno - 1))
9904                 MDT[$idx]=$($LCTL get_param -n \
9905                         mdc.$FSNAME-MDT000${idx}-mdc-*.mds_server_uuid |
9906                         awk '{gsub(/_UUID/,""); print $1}' | head -n1)
9907         done
9908 }
9909
9910 search_copytools() {
9911         local hosts=${1:-$(facet_active_host $SINGLEAGT)}
9912         do_nodesv $hosts "pgrep -x $HSMTOOL_BASE"
9913 }
9914
9915 kill_copytools() {
9916         local hosts=${1:-$(facet_active_host $SINGLEAGT)}
9917
9918         echo "Killing existing copytools on $hosts"
9919         do_nodesv $hosts "killall -q $HSMTOOL_BASE" || true
9920 }
9921
9922 wait_copytools() {
9923         local hosts=${1:-$(facet_active_host $SINGLEAGT)}
9924         local wait_timeout=200
9925         local wait_start=$SECONDS
9926         local wait_end=$((wait_start + wait_timeout))
9927         local sleep_time=100000 # 0.1 second
9928
9929         while ((SECONDS < wait_end)); do
9930                 if ! search_copytools $hosts; then
9931                         echo "copytools stopped in $((SECONDS - wait_start))s"
9932                         return 0
9933                 fi
9934
9935                 echo "copytools still running on $hosts"
9936                 usleep $sleep_time
9937                 [ $sleep_time -lt 32000000 ] && # 3.2 seconds
9938                         sleep_time=$(bc <<< "$sleep_time * 2")
9939         done
9940
9941         # try to dump Copytool's stack
9942         do_nodesv $hosts "echo 1 >/proc/sys/kernel/sysrq ; " \
9943                          "echo t >/proc/sysrq-trigger"
9944
9945         echo "copytools failed to stop in ${wait_timeout}s"
9946
9947         return 1
9948 }
9949
9950 copytool_monitor_cleanup() {
9951         local facet=${1:-$SINGLEAGT}
9952         local agent=$(facet_active_host $facet)
9953
9954         if [ -n "$HSMTOOL_MONITOR_DIR" ]; then
9955                 # Should die when the copytool dies, but just in case.
9956                 local cmd="kill \\\$(cat $HSMTOOL_MONITOR_DIR/monitor_pid)"
9957                 cmd+=" 2>/dev/null || true"
9958                 do_node $agent "$cmd"
9959                 do_node $agent "rm -fr $HSMTOOL_MONITOR_DIR"
9960                 export HSMTOOL_MONITOR_DIR=
9961         fi
9962
9963         # The pdsh should die on its own when the monitor dies. Just
9964         # in case, though, try to clean up to avoid any cruft.
9965         if [ -n "$HSMTOOL_MONITOR_PDSH" ]; then
9966                 kill $HSMTOOL_MONITOR_PDSH 2>/dev/null || true
9967                 export HSMTOOL_MONITOR_PDSH=
9968         fi
9969 }
9970
9971 copytool_logfile()
9972 {
9973         local host="$(facet_host "$1")"
9974         local prefix=$TESTLOG_PREFIX
9975         [ -n "$TESTNAME" ] && prefix+=.$TESTNAME
9976
9977         printf "${prefix}.copytool${archive_id}_log.${host}.log"
9978 }
9979
9980 __lhsmtool_rebind()
9981 {
9982         do_facet $facet $HSMTOOL -p "$hsm_root" --rebind "$@" "$mountpoint"
9983 }
9984
9985 __lhsmtool_import()
9986 {
9987         mkdir -p "$(dirname "$2")" ||
9988                 error "cannot create directory '$(dirname "$2")'"
9989         do_facet $facet $HSMTOOL -p "$hsm_root" --import "$@" "$mountpoint"
9990 }
9991
9992 __lhsmtool_setup()
9993 {
9994         local cmd="$HSMTOOL $HSMTOOL_VERBOSE --daemon --hsm-root \"$hsm_root\""
9995         [ -n "$bandwidth" ] && cmd+=" --bandwidth $bandwidth"
9996         [ -n "$archive_id" ] && cmd+=" --archive $archive_id"
9997         [ ${#misc_options[@]} -gt 0 ] &&
9998                 cmd+=" $(IFS=" " echo "$@")"
9999         cmd+=" \"$mountpoint\""
10000
10001         echo "Starting copytool $facet on $(facet_host $facet)"
10002         stack_trap "do_facet $facet libtool execute pkill -x '$HSMTOOL' || true" EXIT
10003         do_facet $facet "$cmd < /dev/null > \"$(copytool_logfile $facet)\" 2>&1"
10004 }
10005
10006 hsm_root() {
10007         local facet="${1:-$SINGLEAGT}"
10008
10009         printf "$(copytool_device "$facet")/${TESTSUITE}.${TESTNAME}/"
10010 }
10011
10012 # Main entry point to perform copytool related operations
10013 #
10014 # Sub-commands:
10015 #
10016 #       setup   setup a copytool to run in the background, that copytool will be
10017 #               killed on EXIT
10018 #       import  import a file from an HSM backend
10019 #       rebind  rebind an archived file to a new fid
10020 #
10021 # Although the semantics might suggest otherwise, one does not need to 'setup'
10022 # a copytool before a call to 'copytool import' or 'copytool rebind'.
10023 #
10024 copytool()
10025 {
10026         local action=$1
10027         shift
10028
10029         # Use default values
10030         local facet=$SINGLEAGT
10031         local mountpoint="${MOUNT2:-$MOUNT}"
10032         local hsm_root="${hsm_root:-$(hsm_root "$facet")}"
10033
10034         # Parse arguments
10035         local fail_on_error=true
10036         local -a misc_options
10037         while [ $# -gt 0 ]; do
10038                 case "$1" in
10039                 -f|--facet)
10040                         shift
10041                         facet="$1"
10042                         ;;
10043                 -m|--mountpoint)
10044                         shift
10045                         mountpoint="$1"
10046                         ;;
10047                 -a|--archive-id)
10048                         shift
10049                         local archive_id="$1"
10050                         ;;
10051                 -h|--hsm-root)
10052                         shift
10053                         hsm_root="$1"
10054                         ;;
10055                 -b|--bwlimit)
10056                         shift
10057                         local bandwidth="$1" # in MB/s
10058                         ;;
10059                 -n|--no-fail)
10060                         local fail_on_error=false
10061                         ;;
10062                 *)
10063                         # Uncommon(/copytool dependent) option
10064                         misc_options+=("$1")
10065                         ;;
10066                 esac
10067                 shift
10068         done
10069
10070         stack_trap "do_facet $facet rm -rf '$hsm_root'" EXIT
10071         do_facet $facet mkdir -p "$hsm_root" ||
10072                 error "mkdir '$hsm_root' failed"
10073
10074         case "$HSMTOOL" in
10075         lhsmtool_posix)
10076                 local copytool=lhsmtool
10077                 ;;
10078         esac
10079
10080         __${copytool}_${action} "${misc_options[@]}"
10081         if [ $? -ne 0 ]; then
10082                 local error_msg
10083
10084                 case $action in
10085                 setup)
10086                         local host="$(facet_host $facet)"
10087                         error_msg="Failed to start copytool $facet on '$host'"
10088                         ;;
10089                 import)
10090                         local src="${misc_options[0]}"
10091                         local dest="${misc_options[1]}"
10092                         error_msg="Failed to import '$src' to '$dest'"
10093                         ;;
10094                 rebind)
10095                         error_msg="could not rebind file"
10096                         ;;
10097                 esac
10098
10099                 $fail_on_error && error "$error_msg" || echo "$error_msg"
10100         fi
10101 }
10102
10103 needclients() {
10104         local client_count=$1
10105         if [[ $CLIENTCOUNT -lt $client_count ]]; then
10106                 skip "Need $client_count or more clients, have $CLIENTCOUNT"
10107                 return 1
10108         fi
10109         return 0
10110 }
10111
10112 path2fid() {
10113         $LFS path2fid $1 | tr -d '[]'
10114         return ${PIPESTATUS[0]}
10115 }
10116
10117 get_hsm_flags() {
10118         local f=$1
10119         local u=$2
10120         local st
10121
10122         if [[ $u == "user" ]]; then
10123                 st=$($RUNAS $LFS hsm_state $f)
10124         else
10125                 u=root
10126                 st=$($LFS hsm_state $f)
10127         fi
10128
10129         [[ $? == 0 ]] || error "$LFS hsm_state $f failed (run as $u)"
10130
10131         st=$(echo $st | cut -f 2 -d" " | tr -d "()," )
10132         echo $st
10133 }
10134
10135 check_hsm_flags() {
10136         local f=$1
10137         local fl=$2
10138
10139         local st=$(get_hsm_flags $f)
10140         [[ $st == $fl ]] || error "hsm flags on $f are $st != $fl"
10141 }
10142
10143 mdts_set_param() {
10144         local arg=$1
10145         local key=$2
10146         local value=$3
10147         local mdtno
10148         local rc=0
10149         if [[ "$value" != "" ]]; then
10150                 value="=$value"
10151         fi
10152         for mdtno in $(seq 1 $MDSCOUNT); do
10153                 local idx=$(($mdtno - 1))
10154                 local facet=mds${mdtno}
10155                 # if $arg include -P option, run 1 set_param per MDT on the MGS
10156                 # else, run set_param on each MDT
10157                 [[ $arg = *"-P"* ]] && facet=mgs
10158                 do_facet $facet $LCTL set_param $arg mdt.${MDT[$idx]}.$key$value
10159                 [[ $? != 0 ]] && rc=1
10160         done
10161         return $rc
10162 }
10163
10164 wait_result() {
10165         local facet=$1
10166         shift
10167         wait_update --verbose $(facet_active_host $facet) "$@"
10168 }
10169
10170 mdts_check_param() {
10171         local key="$1"
10172         local target="$2"
10173         local timeout="$3"
10174         local mdtno
10175         for mdtno in $(seq 1 $MDSCOUNT); do
10176                 local idx=$(($mdtno - 1))
10177                 wait_result mds${mdtno} \
10178                         "$LCTL get_param -n $MDT_PREFIX${idx}.$key" "$target" \
10179                         $timeout ||
10180                         error "$key state is not '$target' on mds${mdtno}"
10181         done
10182 }
10183
10184 cdt_set_mount_state() {
10185         mdts_set_param "-P" hsm_control "$1"
10186         # set_param -P is asynchronous operation and could race with set_param.
10187         # In such case configs could be retrieved and applied at mgc after
10188         # set_param -P completion. Sleep here to avoid race with set_param.
10189         # We need at least 20 seconds. 10 for mgc_requeue_thread to wake up
10190         # MGC_TIMEOUT_MIN_SECONDS + MGC_TIMEOUT_RAND_CENTISEC(5 + 5)
10191         # and 10 seconds to retrieve config from server.
10192         sleep 20
10193 }
10194
10195 cdt_check_state() {
10196         mdts_check_param hsm_control "$1" 20
10197 }
10198
10199 cdt_set_sanity_policy() {
10200         if [[ "$CDT_POLICY_HAD_CHANGED" ]]
10201         then
10202                 # clear all
10203                 mdts_set_param "" hsm.policy "+NRA"
10204                 mdts_set_param "" hsm.policy "-NBR"
10205                 CDT_POLICY_HAD_CHANGED=
10206         fi
10207 }
10208
10209 set_hsm_param() {
10210         local param=$1
10211         local value=$2
10212         local opt=$3
10213         mdts_set_param "$opt -n" "hsm.$param" "$value"
10214         return $?
10215 }
10216
10217 wait_request_state() {
10218         local fid=$1
10219         local request=$2
10220         local state=$3
10221         # 4th arg (mdt index) is optional
10222         local mdtidx=${4:-0}
10223         local mds=mds$(($mdtidx + 1))
10224
10225         local cmd="$LCTL get_param -n ${MDT_PREFIX}${mdtidx}.hsm.actions"
10226         cmd+=" | awk '/'$fid'.*action='$request'/ {print \\\$13}' | cut -f2 -d="
10227
10228         wait_result $mds "$cmd" "$state" 200 ||
10229                 error "request on $fid is not $state on $mds"
10230 }
10231
10232
10233 rmultiop_start() {
10234         local client=$1
10235         local file=$2
10236         local cmds=$3
10237         local WAIT_MAX=${4:-60}
10238         local wait_time=0
10239
10240         # We need to run do_node in bg, because pdsh does not exit
10241         # if child process of run script exists.
10242         # I.e. pdsh does not exit when runmultiop_bg_pause exited,
10243         # because of multiop_bg_pause -> $MULTIOP_PROG &
10244         # By the same reason we need sleep a bit after do_nodes starts
10245         # to let runmultiop_bg_pause start muliop and
10246         # update /tmp/multiop_bg.pid ;
10247         # The rm /tmp/multiop_bg.pid guarantees here that
10248         # we have the updated by runmultiop_bg_pause
10249         # /tmp/multiop_bg.pid file
10250
10251         local pid_file=$TMP/multiop_bg.pid.$$
10252
10253         do_node $client "MULTIOP_PID_FILE=$pid_file LUSTRE= \
10254                         runmultiop_bg_pause $file $cmds" &
10255         local pid=$!
10256         local multiop_pid
10257
10258         while [[ $wait_time -lt $WAIT_MAX ]]; do
10259                 sleep 3
10260                 wait_time=$((wait_time + 3))
10261                 multiop_pid=$(do_node $client cat $pid_file)
10262                 if [ -n "$multiop_pid" ]; then
10263                         break
10264                 fi
10265         done
10266
10267         [ -n "$multiop_pid" ] ||
10268                 error "$client : Can not get multiop_pid from $pid_file "
10269
10270         eval export $(node_var_name $client)_multiop_pid=$multiop_pid
10271         eval export $(node_var_name $client)_do_node_pid=$pid
10272         local var=$(node_var_name $client)_multiop_pid
10273         echo client $client multiop_bg started multiop_pid=${!var}
10274         return $?
10275 }
10276
10277 rmultiop_stop() {
10278         local client=$1
10279         local multiop_pid=$(node_var_name $client)_multiop_pid
10280         local do_node_pid=$(node_var_name $client)_do_node_pid
10281
10282         echo "Stopping multiop_pid=${!multiop_pid} (kill ${!multiop_pid} on $client)"
10283         do_node $client kill -USR1 ${!multiop_pid}
10284
10285         wait ${!do_node_pid}
10286 }
10287
10288 sleep_maxage() {
10289         local delay=$(do_facet $SINGLEMDS lctl get_param -n lo[vd].*.qos_maxage |
10290                       awk '{ print $1 * 2; exit; }')
10291         sleep $delay
10292 }
10293
10294 check_component_count() {
10295         local comp_cnt=$($LFS getstripe --component-count $1)
10296         [ $comp_cnt -eq $2 ] || error "$1, component count $comp_cnt != $2"
10297 }
10298
10299 # Verify there are no init components with "extension" flag
10300 verify_no_init_extension() {
10301         local flg_opts="--component-flags init,extension"
10302         local found=$($LFS find $flg_opts $1 | wc -l)
10303         [ $found -eq 0 ] || error "$1 has component with initialized extension"
10304 }
10305
10306 # Verify there is at least one component starting at 0
10307 verify_comp_at_zero() {
10308         flg_opts="--component-flags init"
10309         found=$($LFS find --component-start 0M $flg_opts $1 | wc -l)
10310         [ $found -eq 1 ] ||
10311                 error "No component starting at zero(!)"
10312 }
10313
10314 # version after which Self-Extending Layouts are available
10315 SEL_VER="2.12.55"
10316
10317 sel_layout_sanity() {
10318         local file=$1
10319         local comp_cnt=$2
10320
10321         verify_no_init_extension $file
10322         verify_comp_at_zero $file
10323         check_component_count $file $comp_cnt
10324 }
10325