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