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