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