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