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