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