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