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