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