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