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