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