Whamcloud - gitweb
LU-15474 test: facet_failover() should mount all facets concurrently
[fs/lustre-release.git] / lustre / tests / test-framework.sh
1 #!/bin/bash
2
3 trap 'print_summary && print_stack_trace | tee $TF_FAIL && \
4     echo "$TESTSUITE: FAIL: test-framework exiting on error"' ERR
5 set -e
6
7 export LANG=en_US
8 export REFORMAT=${REFORMAT:-""}
9 export WRITECONF=${WRITECONF:-""}
10 export VERBOSE=${VERBOSE:-false}
11 export GSS=${GSS:-false}
12 export GSS_SK=${GSS_SK:-false}
13 export GSS_KRB5=false
14 export GSS_PIPEFS=false
15 export SHARED_KEY=${SHARED_KEY:-false}
16 export SK_PATH=${SK_PATH:-/tmp/test-framework-keys}
17 export SK_OM_PATH=$SK_PATH'/tmp-request-mount'
18 export SK_MOUNTED=${SK_MOUNTED:-false}
19 export SK_FLAVOR=${SK_FLAVOR:-ski}
20 export SK_NO_KEY=${SK_NO_KEY:-true}
21 export SK_UNIQUE_NM=${SK_UNIQUE_NM:-false}
22 export SK_S2S=${SK_S2S:-false}
23 export SK_S2SNM=${SK_S2SNM:-TestFrameNM}
24 export SK_S2SNMCLI=${SK_S2SNMCLI:-TestFrameNMCli}
25 export SK_SKIPFIRST=${SK_SKIPFIRST:-true}
26 export IDENTITY_UPCALL=default
27 export QUOTA_AUTO=1
28 export FLAKEY=${FLAKEY:-true}
29 # specify environment variable containing batch job name for server statistics
30 export JOBID_VAR=${JOBID_VAR:-"procname_uid"}  # or "existing" or "disable"
31
32 #export PDSH="pdsh -S -Rssh -w"
33 export MOUNT_CMD=${MOUNT_CMD:-"mount -t lustre"}
34 export UMOUNT=${UMOUNT:-"umount -d"}
35
36 export LSNAPSHOT_CONF="/etc/ldev.conf"
37 export LSNAPSHOT_LOG="/var/log/lsnapshot.log"
38
39 # sles12 umount has a issue with -d option
40 [ -e /etc/SuSE-release ] && grep -w VERSION /etc/SuSE-release | grep -wq 12 && {
41         export UMOUNT="umount"
42 }
43
44 # function used by scripts run on remote nodes
45 LUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}
46 . $LUSTRE/tests/functions.sh
47 . $LUSTRE/tests/yaml.sh
48
49 export LD_LIBRARY_PATH=${LUSTRE}/utils/.libs:${LUSTRE}/utils:${LD_LIBRARY_PATH}
50
51 LUSTRE_TESTS_CFG_DIR=${LUSTRE_TESTS_CFG_DIR:-${LUSTRE}/tests/cfg}
52
53 EXCEPT_LIST_FILE=${EXCEPT_LIST_FILE:-${LUSTRE_TESTS_CFG_DIR}/tests-to-skip.sh}
54
55 if [ -f "$EXCEPT_LIST_FILE" ]; then
56     echo "Reading test skip list from $EXCEPT_LIST_FILE"
57     cat $EXCEPT_LIST_FILE
58     . $EXCEPT_LIST_FILE
59 fi
60
61 # check config files for options in decreasing order of preference
62 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/lustre.conf ] &&
63     MODPROBECONF=/etc/modprobe.d/lustre.conf
64 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/Lustre ] &&
65     MODPROBECONF=/etc/modprobe.d/Lustre
66 [ -z "$MODPROBECONF" -a -f /etc/modprobe.conf ] &&
67     MODPROBECONF=/etc/modprobe.conf
68
69 sanitize_parameters() {
70         for i in DIR DIR1 DIR2 MOUNT MOUNT1 MOUNT2
71         do
72                 local path=${!i}
73                 if [ -d "$path" ]; then
74                         eval export $i=$(echo $path | sed -r 's/\/+$//g')
75                 fi
76         done
77 }
78 assert_DIR () {
79         local failed=""
80         [[ $DIR/ = $MOUNT/* ]] ||
81                 { failed=1 && echo "DIR=$DIR not in $MOUNT. Aborting."; }
82         [[ $DIR1/ = $MOUNT1/* ]] ||
83                 { failed=1 && echo "DIR1=$DIR1 not in $MOUNT1. Aborting."; }
84         [[ $DIR2/ = $MOUNT2/* ]] ||
85                 { failed=1 && echo "DIR2=$DIR2 not in $MOUNT2. Aborting"; }
86
87         [ -n "$failed" ] && exit 99 || true
88 }
89
90 usage() {
91     echo "usage: $0 [-r] [-f cfgfile]"
92     echo "       -r: reformat"
93
94     exit
95 }
96
97 print_summary () {
98         trap 0
99         [ -z "$DEFAULT_SUITES" ] && return 0
100         [ -n "$ONLY" ] && echo "WARNING: ONLY is set to $(echo $ONLY)"
101         local details
102         local form="%-13s %-17s %-9s %s %s\n"
103
104         printf "$form" "status" "script" "Total(sec)" "E(xcluded) S(low)"
105         echo "---------------------------------------------------------------"
106     for O in $DEFAULT_SUITES; do
107         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
108         [ "${!O}" = "no" ] && continue || true
109         local o=$(echo $O  | tr "[:upper:]_" "[:lower:]-")
110         local log=${TMP}/${o}.log
111         if is_sanity_benchmark $o; then
112             log=${TMP}/sanity-benchmark.log
113         fi
114         local slow=
115         local skipped=
116         local total=
117         local status=Unfinished
118         if [ -f $log ]; then
119                 skipped=$(grep excluded $log | awk '{ printf " %s", $3 }' |
120                         sed 's/test_//g')
121                 slow=$(egrep "^PASS|^FAIL" $log | tr -d "("| sed s/s\)$//g |
122                         sort -nr -k 3  | head -n5 |  awk '{ print $2":"$3"s" }')
123                 total=$(grep duration $log | awk '{ print $2 }')
124                 if [ "${!O}" = "done" ]; then
125                         status=Done
126                 fi
127                 if $DDETAILS; then
128                         local durations=$(egrep "^PASS|^FAIL" $log |
129                                 tr -d "("| sed s/s\)$//g |
130                                 awk '{ print $2":"$3"|" }')
131                         details=$(printf "%s\n%s %s %s\n" "$details" \
132                                 "DDETAILS" "$O" "$(echo $durations)")
133                 fi
134         fi
135         printf "$form" $status "$O" "${total}" "E=$skipped"
136         printf "$form" "-" "-" "-" "S=$(echo $slow)"
137     done
138
139     for O in $DEFAULT_SUITES; do
140         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
141         if [ "${!O}" = "no" ]; then
142             printf "$form" "Skipped" "$O" ""
143         fi
144     done
145
146     # print the detailed tests durations if DDETAILS=true
147     if $DDETAILS; then
148         echo "$details"
149     fi
150 }
151
152 # Get information about the Lustre environment. The information collected
153 # will be used in Lustre tests.
154 # usage: get_lustre_env
155 # input: No required or optional arguments
156 # output: No return values, environment variables are exported
157
158 get_lustre_env() {
159
160         export mds1_FSTYPE=${mds1_FSTYPE:-$(facet_fstype mds1)}
161         export ost1_FSTYPE=${ost1_FSTYPE:-$(facet_fstype ost1)}
162
163         export MGS_VERSION=$(lustre_version_code mgs)
164         export MDS1_VERSION=$(lustre_version_code mds1)
165         export OST1_VERSION=$(lustre_version_code ost1)
166         export CLIENT_VERSION=$(lustre_version_code client)
167
168         # Prefer using "mds1" directly instead of SINGLEMDS.
169         # Keep this for compat until it is removed from scripts.
170         export SINGLEMDS=${SINGLEMDS:-mds1}
171 }
172
173 init_test_env() {
174         export LUSTRE=$(absolute_path $LUSTRE)
175         export TESTSUITE=$(basename $0 .sh)
176         export TEST_FAILED=false
177         export FAIL_ON_SKIP_ENV=${FAIL_ON_SKIP_ENV:-false}
178         export RPC_MODE=${RPC_MODE:-false}
179         export DO_CLEANUP=${DO_CLEANUP:-true}
180         export KEEP_ZPOOL=${KEEP_ZPOOL:-false}
181         export CLEANUP_DM_DEV=false
182         export PAGE_SIZE=$(get_page_size client)
183
184         export MKE2FS=$MKE2FS
185         if [ -z "$MKE2FS" ]; then
186                 if which mkfs.ldiskfs >/dev/null 2>&1; then
187                         export MKE2FS=mkfs.ldiskfs
188                 else
189                         export MKE2FS=mke2fs
190                 fi
191         fi
192
193         export DEBUGFS=$DEBUGFS
194         if [ -z "$DEBUGFS" ]; then
195                 if which debugfs.ldiskfs >/dev/null 2>&1; then
196                         export DEBUGFS=debugfs.ldiskfs
197                 else
198                         export DEBUGFS=debugfs
199                 fi
200         fi
201
202         export TUNE2FS=$TUNE2FS
203         if [ -z "$TUNE2FS" ]; then
204                 if which tunefs.ldiskfs >/dev/null 2>&1; then
205                         export TUNE2FS=tunefs.ldiskfs
206                 else
207                         export TUNE2FS=tune2fs
208                 fi
209         fi
210
211         export E2LABEL=$E2LABEL
212         if [ -z "$E2LABEL" ]; then
213                 if which label.ldiskfs >/dev/null 2>&1; then
214                         export E2LABEL=label.ldiskfs
215                 else
216                         export E2LABEL=e2label
217                 fi
218         fi
219
220         export DUMPE2FS=$DUMPE2FS
221         if [ -z "$DUMPE2FS" ]; then
222                 if which dumpfs.ldiskfs >/dev/null 2>&1; then
223                         export DUMPE2FS=dumpfs.ldiskfs
224                 else
225                         export DUMPE2FS=dumpe2fs
226                 fi
227         fi
228
229         export E2FSCK=$E2FSCK
230         if [ -z "$E2FSCK" ]; then
231                 if which fsck.ldiskfs >/dev/null 2>&1; then
232                         export E2FSCK=fsck.ldiskfs
233                 else
234                          export E2FSCK=e2fsck
235                 fi
236         fi
237
238         export RESIZE2FS=$RESIZE2FS
239         if [ -z "$RESIZE2FS" ]; then
240                 if which resizefs.ldiskfs >/dev/null 2>&1; then
241                         export RESIZE2FS=resizefs.ldiskfs
242                 else
243                         export RESIZE2FS=resize2fs
244                 fi
245         fi
246
247         export LFSCK_ALWAYS=${LFSCK_ALWAYS:-"no"} # check fs after test suite
248         export FSCK_MAX_ERR=4   # File system errors left uncorrected
249
250         export ZFS=${ZFS:-zfs}
251         export ZPOOL=${ZPOOL:-zpool}
252         export ZDB=${ZDB:-zdb}
253         export PARTPROBE=${PARTPROBE:-partprobe}
254
255         #[ -d /r ] && export ROOT=${ROOT:-/r}
256         export TMP=${TMP:-$ROOT/tmp}
257         export TESTSUITELOG=${TMP}/${TESTSUITE}.log
258         export LOGDIR=${LOGDIR:-${TMP}/test_logs/$(date +%s)}
259         export TESTLOG_PREFIX=$LOGDIR/$TESTSUITE
260
261         export HOSTNAME=${HOSTNAME:-$(hostname -s)}
262         if ! echo $PATH | grep -q $LUSTRE/utils; then
263                 export PATH=$LUSTRE/utils:$PATH
264         fi
265         if ! echo $PATH | grep -q $LUSTRE/utils/gss; then
266                 export PATH=$LUSTRE/utils/gss:$PATH
267         fi
268         if ! echo $PATH | grep -q $LUSTRE/tests; then
269                 export PATH=$LUSTRE/tests:$PATH
270         fi
271         if ! echo $PATH | grep -q $LUSTRE/../lustre-iokit/sgpdd-survey; then
272                 export PATH=$LUSTRE/../lustre-iokit/sgpdd-survey:$PATH
273         fi
274         export LST=${LST:-"$LUSTRE/../lnet/utils/lst"}
275         [ ! -f "$LST" ] && export LST=$(which lst)
276         export SGPDDSURVEY=${SGPDDSURVEY:-"$LUSTRE/../lustre-iokit/sgpdd-survey/sgpdd-survey")}
277         [ ! -f "$SGPDDSURVEY" ] && export SGPDDSURVEY=$(which sgpdd-survey)
278         export MCREATE=${MCREATE:-mcreate}
279         export MULTIOP=${MULTIOP:-multiop}
280         export MMAP_CAT=${MMAP_CAT:-mmap_cat}
281         export STATX=${STATX:-statx}
282         # Ubuntu, at least, has a truncate command in /usr/bin
283         # so fully path our truncate command.
284         export TRUNCATE=${TRUNCATE:-$LUSTRE/tests/truncate}
285         export FSX=${FSX:-$LUSTRE/tests/fsx}
286         export MDSRATE=${MDSRATE:-"$LUSTRE/tests/mpi/mdsrate"}
287         [ ! -f "$MDSRATE" ] && export MDSRATE=$(which mdsrate 2> /dev/null)
288         if ! echo $PATH | grep -q $LUSTRE/tests/racer; then
289                 export PATH=$LUSTRE/tests/racer:$PATH:
290         fi
291         if ! echo $PATH | grep -q $LUSTRE/tests/mpi; then
292                 export PATH=$LUSTRE/tests/mpi:$PATH
293         fi
294         export RSYNC_RSH=${RSYNC_RSH:-rsh}
295
296         export LNETCTL=${LNETCTL:-"$LUSTRE/../lnet/utils/lnetctl"}
297         [ ! -f "$LNETCTL" ] && export LNETCTL=$(which lnetctl 2> /dev/null)
298         export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
299         [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
300         export LFS=${LFS:-"$LUSTRE/utils/lfs"}
301         [ ! -f "$LFS" ] && export LFS=$(which lfs)
302         export KSOCKLND_CONFIG=${KSOCKLND_CONFIG:-"$LUSTRE/scripts/ksocklnd-config"}
303         [ ! -f "$KSOCKLND_CONFIG" ] &&
304                 export KSOCKLND_CONFIG=$(which ksocklnd-config 2> /dev/null)
305
306         export PERM_CMD=$(echo ${PERM_CMD:-"$LCTL conf_param"})
307
308         export L_GETIDENTITY=${L_GETIDENTITY:-"$LUSTRE/utils/l_getidentity"}
309         if [ ! -f "$L_GETIDENTITY" ]; then
310                 if `which l_getidentity > /dev/null 2>&1`; then
311                         export L_GETIDENTITY=$(which l_getidentity)
312                 else
313                         export L_GETIDENTITY=NONE
314                 fi
315         fi
316         export LL_DECODE_FILTER_FID=${LL_DECODE_FILTER_FID:-"$LUSTRE/utils/ll_decode_filter_fid"}
317         [ ! -f "$LL_DECODE_FILTER_FID" ] && export LL_DECODE_FILTER_FID="ll_decode_filter_fid"
318         export LL_DECODE_LINKEA=${LL_DECODE_LINKEA:-"$LUSTRE/utils/ll_decode_linkea"}
319         [ ! -f "$LL_DECODE_LINKEA" ] && export LL_DECODE_LINKEA="ll_decode_linkea"
320         export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
321         [ ! -f "$MKFS" ] && export MKFS="mkfs.lustre"
322         export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
323         [ ! -f "$TUNEFS" ] && export TUNEFS="tunefs.lustre"
324         export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
325         export LUSTRE_RMMOD=${LUSTRE_RMMOD:-$LUSTRE/scripts/lustre_rmmod}
326         [ ! -f "$LUSTRE_RMMOD" ] &&
327                 export LUSTRE_RMMOD=$(which lustre_rmmod 2> /dev/null)
328         export LUSTRE_ROUTES_CONVERSION=${LUSTRE_ROUTES_CONVERSION:-$LUSTRE/scripts/lustre_routes_conversion}
329         [ ! -f "$LUSTRE_ROUTES_CONVERSION" ] &&
330                 export LUSTRE_ROUTES_CONVERSION=$(which lustre_routes_conversion 2> /dev/null)
331         export LFS_MIGRATE=${LFS_MIGRATE:-$LUSTRE/scripts/lfs_migrate}
332         [ ! -f "$LFS_MIGRATE" ] &&
333                 export LFS_MIGRATE=$(which lfs_migrate 2> /dev/null)
334         export LR_READER=${LR_READER:-"$LUSTRE/utils/lr_reader"}
335         [ ! -f "$LR_READER" ] &&
336                 export LR_READER=$(which lr_reader 2> /dev/null)
337         [ -z "$LR_READER" ] && export LR_READER="/usr/sbin/lr_reader"
338         export LSOM_SYNC=${LSOM_SYNC:-"$LUSTRE/utils/llsom_sync"}
339         [ ! -f "$LSOM_SYNC" ] &&
340                 export LSOM_SYNC=$(which llsom_sync 2> /dev/null)
341         [ -z "$LSOM_SYNC" ] && export LSOM_SYNC="/usr/sbin/llsom_sync"
342         export NAME=${NAME:-local}
343         export LGSSD=${LGSSD:-"$LUSTRE/utils/gss/lgssd"}
344         [ "$GSS_PIPEFS" = "true" ] && [ ! -f "$LGSSD" ] &&
345                 export LGSSD=$(which lgssd)
346         export LSVCGSSD=${LSVCGSSD:-"$LUSTRE/utils/gss/lsvcgssd"}
347         [ ! -f "$LSVCGSSD" ] && export LSVCGSSD=$(which lsvcgssd 2> /dev/null)
348         export KRB5DIR=${KRB5DIR:-"/usr/kerberos"}
349         export DIR2
350         export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
351         export AT_MAX_PATH
352         export LDEV=${LDEV:-"$LUSTRE/scripts/ldev"}
353         [ ! -f "$LDEV" ] && export LDEV=$(which ldev 2> /dev/null)
354
355         export DMSETUP=${DMSETUP:-dmsetup}
356         export DM_DEV_PATH=${DM_DEV_PATH:-/dev/mapper}
357         export LOSETUP=${LOSETUP:-losetup}
358
359         if [ "$ACCEPTOR_PORT" ]; then
360                 export PORT_OPT="--port $ACCEPTOR_PORT"
361         fi
362
363         if $SHARED_KEY; then
364                 $RPC_MODE || echo "Using GSS shared-key feature"
365                 which lgss_sk > /dev/null 2>&1 ||
366                         error_exit "built with lgss_sk disabled! SEC=$SEC"
367                 GSS=true
368                 GSS_SK=true
369                 SEC=$SK_FLAVOR
370         fi
371
372         case "x$SEC" in
373                 xkrb5*)
374                 $RPC_MODE || echo "Using GSS/krb5 ptlrpc security flavor"
375                 which lgss_keyring > /dev/null 2>&1 ||
376                         error_exit "built with gss disabled! SEC=$SEC"
377                 GSS=true
378                 GSS_KRB5=true
379                 ;;
380         esac
381
382         case "x$IDUP" in
383                 xtrue)
384                         IDENTITY_UPCALL=true
385                         ;;
386                 xfalse)
387                         IDENTITY_UPCALL=false
388                         ;;
389         esac
390
391         export LOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}
392
393         # Paths on remote nodes, if different
394         export RLUSTRE=${RLUSTRE:-$LUSTRE}
395         export RPWD=${RPWD:-$PWD}
396         export I_MOUNTED=${I_MOUNTED:-"no"}
397         export AUSTER_CLEANUP=${AUSTER_CLEANUP:-false}
398         if [ ! -f /lib/modules/$(uname -r)/kernel/fs/lustre/mdt.ko -a \
399              ! -f /lib/modules/$(uname -r)/updates/kernel/fs/lustre/mdt.ko -a \
400              ! -f /lib/modules/$(uname -r)/extra/kernel/fs/lustre/mdt.ko -a \
401              ! -f $LUSTRE/mdt/mdt.ko ]; then
402             export CLIENTMODSONLY=yes
403         fi
404
405         export SHUTDOWN_ATTEMPTS=${SHUTDOWN_ATTEMPTS:-3}
406         export OSD_TRACK_DECLARES_LBUG=${OSD_TRACK_DECLARES_LBUG:-"yes"}
407
408         # command line
409
410         while getopts "rvwf:" opt $*; do
411                 case $opt in
412                         f) CONFIG=$OPTARG;;
413                         r) REFORMAT=yes;;
414                         v) VERBOSE=true;;
415                         w) WRITECONF=writeconf;;
416                         \?) usage;;
417                 esac
418         done
419
420         shift $((OPTIND - 1))
421         ONLY=${ONLY:-$*}
422
423         # print the durations of each test if "true"
424         DDETAILS=${DDETAILS:-false}
425         [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
426         if ! $RPC_MODE; then
427                 rm -f $TMP/*active
428         fi
429
430         export TF_FAIL=${TF_FAIL:-$TMP/tf.fail}
431
432         # Constants used in more than one test script
433         export LOV_MAX_STRIPE_COUNT=2000
434         export DELETE_OLD_POOLS=${DELETE_OLD_POOLS:-false}
435         export KEEP_POOLS=${KEEP_POOLS:-false}
436         export PARALLEL=${PARALLEL:-"no"}
437
438         export MACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}
439         . ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}
440         get_lustre_env
441
442         # use localrecov to enable recovery for local clients, LU-12722
443         [[ $MDS1_VERSION -lt $(version_code 2.13.52) ]] || {
444                 export MDS_MOUNT_OPTS=${MDS_MOUNT_OPTS:-"-o localrecov"}
445                 export MGS_MOUNT_OPTS=${MGS_MOUNT_OPTS:-"-o localrecov"}
446         }
447
448         [[ $OST1_VERSION -lt $(version_code 2.13.52) ]] ||
449                 export OST_MOUNT_OPTS=${OST_MOUNT_OPTS:-"-o localrecov"}
450 }
451
452 check_cpt_number() {
453         local facet=$1
454         local ncpts
455
456         ncpts=$(do_facet $facet "lctl get_param -n " \
457                 "cpu_partition_table 2>/dev/null| wc -l" || echo 1)
458
459         if [ $ncpts -eq 0 ]; then
460                 echo "1"
461         else
462                 echo $ncpts
463         fi
464 }
465
466 # Return a numeric version code based on a version string.  The version
467 # code is useful for comparison two version strings to see which is newer.
468 version_code() {
469         # split arguments like "1.8.6-wc3" into "1", "8", "6", "3"
470         eval set -- $(tr "[:punct:][a-z]" " " <<< $*)
471
472         echo -n $(((${1:-0}<<24) | (${2:-0}<<16) | (${3:-0}<<8) | (${4:-0})))
473 }
474
475 export LINUX_VERSION=$(uname -r | sed -e "s/\([0-9]*\.[0-9]*\.[0-9]*\).*/\1/")
476 export LINUX_VERSION_CODE=$(version_code ${LINUX_VERSION//\./ })
477
478 # Report the Lustre build version string (e.g. 1.8.7.3 or 2.4.1).
479 #
480 # usage: lustre_build_version
481 #
482 # All Lustre versions support "lctl get_param" to report the version of the
483 # code running in the kernel (what our tests are interested in), but it
484 # doesn't work without modules loaded.  After 2.9.53 and in upstream kernels
485 # the "version" parameter doesn't include "lustre: " at the beginning.
486 # If that fails, call "lctl lustre_build_version" which prints either (or both)
487 # the userspace and kernel build versions, but until 2.8.55 required root
488 # access to get the Lustre kernel version.  If that also fails, fall back to
489 # using "lctl --version", which is easy to parse and works without the kernel
490 # modules, but was only added in 2.6.50 and only prints the lctl tool version,
491 # not the module version, though they are usually the same.
492 #
493 # Various commands and their output format for different Lustre versions:
494 # lctl get_param version:       2.9.55
495 # lctl get_param version:       lustre: 2.8.53
496 # lctl get_param version:       lustre: 2.6.52
497 #                               kernel: patchless_client
498 #                               build: v2_6_92_0-2.6.32-431.el6_lustre.x86_64
499 # lctl lustre_build_version:    Lustre version: 2.8.53_27_gae67fc01
500 # lctl lustre_build_version:    error: lustre_build_version: Permission denied
501 #       (as non-root user)      lctl   version: v2_6_92_0-2.6.32-431.el6.x86_64
502 # lctl lustre_build_version:    Lustre version: 2.5.3-2.6.32.26-175.fc12.x86_64
503 #                               lctl   version: 2.5.3-2.6.32..26-175fc12.x86_64
504 # lctl --version:               lctl 2.6.50
505 #
506 # output: prints version string to stdout in (up to 4) dotted-decimal values
507 lustre_build_version() {
508         local facet=${1:-client}
509         local facet_version=${facet}_VERSION
510
511         # if the global variable is already set, then use that
512         [ -n "${!facet_version}" ] && echo ${!facet_version} && return
513
514         # this is the currently-running version of the kernel modules
515         local ver=$(do_facet $facet "$LCTL get_param -n version 2>/dev/null")
516         # we mostly test 2.10+ systems, only try others if the above fails
517         if [ -z "$ver" ]; then
518                 ver=$(do_facet $facet "$LCTL lustre_build_version 2>/dev/null")
519         fi
520         if [ -z "$ver" ]; then
521                 ver=$(do_facet $facet "$LCTL --version 2>/dev/null" |
522                       cut -d' ' -f2)
523         fi
524         local lver=$(egrep -i "lustre: |version: " <<<"$ver" | head -n 1)
525         [ -n "$lver" ] && ver="$lver"
526
527         lver=$(sed -e 's/[^:]*: //' -e 's/^v//' -e 's/[ -].*//' <<<$ver |
528                tr _ . | cut -d. -f1-4)
529
530         # save in global variable for the future
531         export $facet_version=$lver
532
533         echo $lver
534 }
535
536 # Report the Lustre numeric build version code for the supplied facet.
537 lustre_version_code() {
538         version_code $(lustre_build_version $1)
539 }
540
541 module_loaded () {
542         /sbin/lsmod | grep -q "^\<$1\>"
543 }
544
545 check_lfs_df_ret_val() {
546         # Ignore only EOPNOTSUPP (which is 95; Operation not supported) error
547         # returned by 'lfs df' for valid dentry but not a lustrefs.
548         #
549         # 'lfs df' historically always returned success(0) instead of
550         # EOPNOTSUPP. This function for compatibility reason, ignores and
551         # masquerades EOPNOTSUPP as success.
552         [[ $1 -eq 95 ]] && return 0
553         return $1
554 }
555
556 PRLFS=false
557 lustre_insmod() {
558         local module=$1
559         shift
560         local args="$@"
561         local msg
562         local rc=0
563
564         if ! $PRLFS; then
565                 msg="$(insmod $module $args 2>&1)" && return 0 || rc=$?
566         fi
567
568         # parallels can't load modules directly from prlfs, use /tmp instead
569         if $PRLFS || [[ "$(stat -f -c%t $module)" == "7c7c6673" ]]; then
570                 local target="$(mktemp)"
571
572                 cp "$module" "$target"
573                 insmod $target $args
574                 rc=$?
575                 [[ $rc == 0 ]] && PRLFS=true
576                 rm -f $target
577         else
578                 echo "$msg"
579         fi
580         return $rc
581 }
582
583 # Load a module on the system where this is running.
584 #
585 # usage: load_module module_name [module arguments for insmod/modprobe]
586 #
587 # If module arguments are not given but MODOPTS_<MODULE> is set, then its value
588 # will be used as the arguments.  Otherwise arguments will be obtained from
589 # /etc/modprobe.conf, from /etc/modprobe.d/Lustre, or else none will be used.
590 #
591 load_module() {
592         local module=$1 # '../libcfs/libcfs/libcfs', 'obdclass/obdclass', ...
593         shift
594         local ext=".ko"
595         local base=$(basename $module $ext)
596         local path
597         local -A module_is_loaded_aa
598         local optvar
599         local mod
600
601         for mod in $(lsmod | awk '{ print $1; }'); do
602                 module_is_loaded_aa[${mod//-/_}]=true
603         done
604
605         module_is_loaded() {
606                 ${module_is_loaded_aa[${1//-/_}]:-false}
607         }
608
609         if module_is_loaded $base; then
610                 return
611         fi
612
613         if [[ -f $LUSTRE/$module$ext ]]; then
614                 path=$LUSTRE/$module$ext
615         elif [[ "$base" == lnet_selftest ]] &&
616              [[ -f $LUSTRE/../lnet/selftest/$base$ext ]]; then
617                 path=$LUSTRE/../lnet/selftest/$base$ext
618         else
619                 path=''
620         fi
621
622         if [[ -n "$path" ]]; then
623                 # Try to load any non-Lustre modules that $module depends on.
624                 for mod in $(modinfo --field=depends $path | tr ',' ' '); do
625                         if ! module_is_loaded $mod; then
626                                 modprobe $mod
627                         fi
628                 done
629         fi
630
631         # If no module arguments were passed then get them from
632         # $MODOPTS_<MODULE>, otherwise from modprobe.conf.
633         if [ $# -eq 0 ]; then
634                 # $MODOPTS_<MODULE>; we could use associative arrays, but that's
635                 # not in Bash until 4.x, so we resort to eval.
636                 optvar="MODOPTS_$(basename $module | tr a-z A-Z)"
637                 eval set -- \$$optvar
638                 if [ $# -eq 0 -a -n "$MODPROBECONF" ]; then
639                         # Nothing in $MODOPTS_<MODULE>; try modprobe.conf
640                         local opt
641                         opt=$(awk -v var="^options $base" '$0 ~ var \
642                               {gsub("'"options $base"'",""); print}' \
643                                 $MODPROBECONF)
644                         set -- $(echo -n $opt)
645
646                         # Ensure we have accept=all for lnet
647                         if [[ "$base" == lnet ]]; then
648                                 # OK, this is a bit wordy...
649                                 local arg accept_all_present=false
650
651                                 for arg in "$@"; do
652                                         [[ "$arg" == accept=all ]] &&
653                                                 accept_all_present=true
654                                 done
655
656                                 $accept_all_present || set -- "$@" accept=all
657                         fi
658
659                         export $optvar="$*"
660                 fi
661         fi
662
663         [ $# -gt 0 ] && echo "${module} options: '$*'"
664
665         # Note that insmod will ignore anything in modprobe.conf, which is why
666         # we're passing options on the command-line. If $path does not exist
667         # then we must be testing a "make install" or"rpm" installation. Also
668         # note that failing to load ptlrpc_gss is not considered fatal.
669         if [[ -n "$path" ]]; then
670                 lustre_insmod $path "$@"
671         elif [[ "$base" == ptlrpc_gss ]]; then
672                 if ! modprobe $base "$@" 2>/dev/null; then
673                         echo "gss/krb5 is not supported"
674                 fi
675         else
676                 modprobe $base "$@"
677         fi
678 }
679
680 do_lnetctl() {
681         $LCTL mark "$LNETCTL $*"
682         echo "$LNETCTL $*"
683         $LNETCTL "$@"
684 }
685
686 load_lnet() {
687         # For kmemleak-enabled kernels we need clear all past state
688         # that obviously has nothing to do with this Lustre run
689         # Disable automatic memory scanning to avoid perf hit.
690         if [ -f /sys/kernel/debug/kmemleak ] ; then
691                 echo scan=off > /sys/kernel/debug/kmemleak || true
692                 echo scan > /sys/kernel/debug/kmemleak || true
693                 echo clear > /sys/kernel/debug/kmemleak || true
694         fi
695
696         echo Loading modules from $LUSTRE
697
698         local ncpus
699
700         if [ -f /sys/devices/system/cpu/online ]; then
701                 ncpus=$(($(cut -d "-" -f 2 /sys/devices/system/cpu/online) + 1))
702                 echo "detected $ncpus online CPUs by sysfs"
703         else
704                 ncpus=$(getconf _NPROCESSORS_CONF 2>/dev/null)
705                 local rc=$?
706                 if [ $rc -eq 0 ]; then
707                         echo "detected $ncpus online CPUs by getconf"
708                 else
709                         echo "Can't detect number of CPUs"
710                         ncpus=1
711                 fi
712         fi
713
714         # if there is only one CPU core, libcfs can only create one partition
715         # if there is more than 4 CPU cores, libcfs should create multiple CPU
716         # partitions. So we just force libcfs to create 2 partitions for
717         # system with 2 or 4 cores
718         local saved_opts="$MODOPTS_LIBCFS"
719         if [ $ncpus -le 4 ] && [ $ncpus -gt 1 ]; then
720                 # force to enable multiple CPU partitions
721                 echo "Force libcfs to create 2 CPU partitions"
722                 MODOPTS_LIBCFS="cpu_npartitions=2 $MODOPTS_LIBCFS"
723         else
724                 echo "libcfs will create CPU partition based on online CPUs"
725         fi
726
727         load_module ../libcfs/libcfs/libcfs
728         # Prevent local MODOPTS_LIBCFS being passed as part of environment
729         # variable to remote nodes
730         unset MODOPTS_LIBCFS
731
732         set_default_debug "neterror net nettrace malloc"
733         if [ "$1" = "config_on_load=1" ]; then
734                 load_module ../lnet/lnet/lnet
735         else
736                 load_module ../lnet/lnet/lnet "$@"
737         fi
738
739         LNDPATH=${LNDPATH:-"../lnet/klnds"}
740         if [ -z "$LNETLND" ]; then
741                 case $NETTYPE in
742                 o2ib*)  LNETLND="o2iblnd/ko2iblnd" ;;
743                 tcp*)   LNETLND="socklnd/ksocklnd" ;;
744                 *)      local lnd="${NETTYPE%%[0-9]}lnd"
745                         [ -f "$LNDPATH/$lnd/k$lnd.ko" ] &&
746                                 LNETLND="$lnd/k$lnd" ||
747                                 LNETLND="socklnd/ksocklnd"
748                 esac
749         fi
750         load_module ../lnet/klnds/$LNETLND
751
752         if [ "$1" = "config_on_load=1" ]; then
753                 do_lnetctl lnet configure --all ||
754                         return $?
755         fi
756 }
757
758 load_modules_local() {
759         if [ -n "$MODPROBE" ]; then
760                 # use modprobe
761                 echo "Using modprobe to load modules"
762                 return 0
763         fi
764
765         # Create special udev test rules on every node
766         if [ -f $LUSTRE/lustre/conf/99-lustre.rules ]; then {
767                 sed -e 's|/usr/sbin/lctl|$LCTL|g' $LUSTRE/lustre/conf/99-lustre.rules > /etc/udev/rules.d/99-lustre-test.rules
768         } else {
769                 echo "SUBSYSTEM==\"lustre\", ACTION==\"change\", ENV{PARAM}==\"?*\", RUN+=\"$LCTL set_param '\$env{PARAM}=\$env{SETTING}'\"" > /etc/udev/rules.d/99-lustre-test.rules
770         } fi
771         udevadm control --reload-rules
772         udevadm trigger
773
774         load_lnet
775
776         load_module obdclass/obdclass
777         if ! client_only; then
778                 MODOPTS_PTLRPC=${MODOPTS_PTLRPC:-"lbug_on_grant_miscount=1"}
779         fi
780         load_module ptlrpc/ptlrpc
781         load_module ptlrpc/gss/ptlrpc_gss
782         load_module fld/fld
783         load_module fid/fid
784         load_module lmv/lmv
785         load_module osc/osc
786         load_module lov/lov
787         load_module mdc/mdc
788         load_module mgc/mgc
789         load_module obdecho/obdecho
790         if ! client_only; then
791                 load_module lfsck/lfsck
792                 [ "$LQUOTA" != "no" ] &&
793                         load_module quota/lquota $LQUOTAOPTS
794                 if [[ $(node_fstypes $HOSTNAME) == *zfs* ]]; then
795                         load_module osd-zfs/osd_zfs
796                 elif [[ $(node_fstypes $HOSTNAME) == *ldiskfs* ]]; then
797                         load_module ../ldiskfs/ldiskfs
798                         load_module osd-ldiskfs/osd_ldiskfs
799                 fi
800                 load_module mgs/mgs
801                 load_module mdd/mdd
802                 load_module mdt/mdt
803                 load_module ost/ost
804                 load_module lod/lod
805                 load_module osp/osp
806                 load_module ofd/ofd
807                 load_module osp/osp
808         fi
809
810         load_module llite/lustre
811         [ -d /r ] && OGDB=${OGDB:-"/r/tmp"}
812         OGDB=${OGDB:-$TMP}
813         rm -f $OGDB/ogdb-$HOSTNAME
814         $LCTL modules > $OGDB/ogdb-$HOSTNAME
815
816         # 'mount' doesn't look in $PATH, just sbin
817         local mount_lustre=$LUSTRE/utils/mount.lustre
818         if [ -f $mount_lustre ]; then
819                 local sbin_mount=$(readlink -f /sbin)/mount.lustre
820                 if grep -qw "$sbin_mount" /proc/mounts; then
821                         cmp -s $mount_lustre $sbin_mount || umount $sbin_mount
822                 fi
823                 if ! grep -qw "$sbin_mount" /proc/mounts; then
824                         [ ! -f "$sbin_mount" ] && touch "$sbin_mount"
825                         if [ ! -s "$sbin_mount" -a -w "$sbin_mount" ]; then
826                                 cat <<- EOF > "$sbin_mount"
827                                 #!/bin/sh
828                                 #STUB MARK
829                                 echo "This $sbin_mount just a mountpoint." 1>&2
830                                 echo "It is never supposed to be run." 1>&2
831                                 logger -p emerg -- "using stub $sbin_mount $@"
832                                 exit 1
833                                 EOF
834                                 chmod a+x $sbin_mount
835                         fi
836                         mount --bind $mount_lustre $sbin_mount ||
837                                 error "can't bind $mount_lustre to $sbin_mount"
838                 fi
839         fi
840 }
841
842 load_modules () {
843         local facets
844         local facet
845         local failover
846         load_modules_local
847         # bug 19124
848         # load modules on remote nodes optionally
849         # lustre-tests have to be installed on these nodes
850         if $LOAD_MODULES_REMOTE; then
851                 local list=$(comma_list $(remote_nodes_list))
852
853                 # include failover nodes in case they are not in the list yet
854                 facets=$(get_facets)
855                 for facet in ${facets//,/ }; do
856                         failover=$(facet_failover_host $facet)
857                         [ -n "$list" ] && [[ ! "$list" =~ "$failover" ]] &&
858                                 list="$list,$failover"
859                 done
860
861                 if [ -n "$list" ]; then
862                         echo "loading modules on: '$list'"
863                         do_rpc_nodes "$list" load_modules_local
864                 fi
865         fi
866 }
867
868 check_mem_leak () {
869         LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
870         LEAK_PORTALS=$(dmesg | tail -n 20 | egrep -i "libcfs.*memory leaked" || true)
871         if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
872                 echo "$LEAK_LUSTRE" 1>&2
873                 echo "$LEAK_PORTALS" 1>&2
874                 mv $TMP/debug $TMP/debug-leak.`date +%s` || true
875                 echo "Memory leaks detected"
876                 [ -n "$IGNORE_LEAK" ] && { echo "ignoring leaks" && return 0; } || true
877                 return 1
878         fi
879 }
880
881 unload_modules_local() {
882         $LUSTRE_RMMOD ldiskfs || return 2
883
884         [ -f /etc/udev/rules.d/99-lustre-test.rules ] &&
885                 rm /etc/udev/rules.d/99-lustre-test.rules
886         udevadm control --reload-rules
887         udevadm trigger
888
889         check_mem_leak || return 254
890
891         return 0
892 }
893
894 unload_modules() {
895         local rc=0
896
897         wait_exit_ST client # bug 12845
898
899         unload_modules_local || rc=$?
900
901         if $LOAD_MODULES_REMOTE; then
902                 local list=$(comma_list $(remote_nodes_list))
903                 if [ -n "$list" ]; then
904                         echo "unloading modules on: '$list'"
905                         do_rpc_nodes "$list" unload_modules_local
906                 fi
907         fi
908
909         local sbin_mount=$(readlink -f /sbin)/mount.lustre
910         if grep -qe "$sbin_mount " /proc/mounts; then
911                 umount $sbin_mount || true
912                 [ -s $sbin_mount ] && ! grep -q "STUB MARK" $sbin_mount ||
913                         rm -f $sbin_mount
914         fi
915
916         [[ $rc -eq 0 ]] && echo "modules unloaded."
917
918         return $rc
919 }
920
921 fs_log_size() {
922         local facet=${1:-$SINGLEMDS}
923         local size=0
924
925         case $(facet_fstype $facet) in
926                 ldiskfs) size=72;; # largest seen is 64, leave some headroom
927                 # grant_block_size is in bytes, allow at least 2x max blocksize
928                 zfs)     size=$(lctl get_param osc.$FSNAME*.import |
929                                 awk '/grant_block_size:/ {print $2/512; exit;}')
930                           ;;
931         esac
932
933         echo -n $((size * MDSCOUNT))
934 }
935
936 fs_inode_ksize() {
937         local facet=${1:-$SINGLEMDS}
938         local fstype=$(facet_fstype $facet)
939         local size=0
940         case $fstype in
941                 ldiskfs) size=4;;  # ~4KB per inode
942                 zfs)     size=11;; # 10 to 11KB per inode
943         esac
944
945         echo -n $size
946 }
947
948 check_gss_daemon_nodes() {
949     local list=$1
950     dname=$2
951
952     do_nodesv $list "num=\\\$(ps -o cmd -C $dname | grep $dname | wc -l);
953 if [ \\\"\\\$num\\\" -ne 1 ]; then
954     echo \\\$num instance of $dname;
955     exit 1;
956 fi; "
957 }
958
959 check_gss_daemon_facet() {
960     facet=$1
961     dname=$2
962
963     num=`do_facet $facet ps -o cmd -C $dname | grep $dname | wc -l`
964     if [ $num -ne 1 ]; then
965         echo "$num instance of $dname on $facet"
966         return 1
967     fi
968     return 0
969 }
970
971 send_sigint() {
972     local list=$1
973     shift
974     echo Stopping $@ on $list
975     do_nodes $list "killall -2 $@ 2>/dev/null || true"
976 }
977
978 # start gss daemons on all nodes, or "daemon" on "nodes" if set
979 start_gss_daemons() {
980         local nodes=$1
981         local daemon=$2
982
983         if [ "$nodes" ] && [ "$daemon" ] ; then
984                 echo "Starting gss daemon on nodes: $nodes"
985                 do_nodes $nodes "$daemon" || return 8
986                 return 0
987         fi
988
989         nodes=$(comma_list $(mdts_nodes))
990         echo "Starting gss daemon on mds: $nodes"
991         if $GSS_SK; then
992                 # Start all versions, in case of switching
993                 do_nodes $nodes "$LSVCGSSD -vvv -s -m -o -z" || return 1
994         else
995                 do_nodes $nodes "$LSVCGSSD -v" || return 1
996         fi
997         if $GSS_PIPEFS; then
998                 do_nodes $nodes "$LGSSD -v" || return 2
999         fi
1000
1001         nodes=$(comma_list $(osts_nodes))
1002         echo "Starting gss daemon on ost: $nodes"
1003         if $GSS_SK; then
1004                 # Start all versions, in case of switching
1005                 do_nodes $nodes "$LSVCGSSD -vvv -s -m -o -z" || return 3
1006         else
1007                 do_nodes $nodes "$LSVCGSSD -v" || return 3
1008         fi
1009         # starting on clients
1010
1011         local clients=${CLIENTS:-$HOSTNAME}
1012         if $GSS_PIPEFS; then
1013                 echo "Starting $LGSSD on clients $clients "
1014                 do_nodes $clients  "$LGSSD -v" || return 4
1015         fi
1016
1017         # wait daemons entering "stable" status
1018         sleep 5
1019
1020         #
1021         # check daemons are running
1022         #
1023         nodes=$(comma_list $(mdts_nodes) $(osts_nodes))
1024         check_gss_daemon_nodes $nodes lsvcgssd || return 5
1025         if $GSS_PIPEFS; then
1026                 nodes=$(comma_list $(mdts_nodes))
1027                 check_gss_daemon_nodes $nodes lgssd || return 6
1028         fi
1029         if $GSS_PIPEFS; then
1030                 check_gss_daemon_nodes $clients lgssd || return 7
1031         fi
1032 }
1033
1034 stop_gss_daemons() {
1035         local nodes=$(comma_list $(mdts_nodes))
1036
1037         send_sigint $nodes lsvcgssd lgssd
1038
1039         nodes=$(comma_list $(osts_nodes))
1040         send_sigint $nodes lsvcgssd
1041
1042         nodes=${CLIENTS:-$HOSTNAME}
1043         send_sigint $nodes lgssd
1044 }
1045
1046 add_sk_mntflag() {
1047         # Add mount flags for shared key
1048         local mt_opts=$@
1049         if grep -q skpath <<< "$mt_opts" ; then
1050                 mt_opts=$(echo $mt_opts |
1051                         sed -e "s#skpath=[^ ,]*#skpath=$SK_PATH#")
1052         else
1053                 if [ -z "$mt_opts" ]; then
1054                         mt_opts="-o skpath=$SK_PATH"
1055                 else
1056                         mt_opts="$mt_opts,skpath=$SK_PATH"
1057                 fi
1058         fi
1059         echo -n $mt_opts
1060 }
1061
1062 from_build_tree() {
1063         local from_tree
1064
1065         case $LUSTRE in
1066         /usr/lib/lustre/* | /usr/lib64/lustre/* | /usr/lib/lustre | \
1067         /usr/lib64/lustre )
1068                 from_tree=false
1069                 ;;
1070         *)
1071                 from_tree=true
1072                 ;;
1073         esac
1074
1075         [ $from_tree = true ]
1076 }
1077
1078 init_gss() {
1079         if $SHARED_KEY; then
1080                 GSS=true
1081                 GSS_SK=true
1082         fi
1083
1084         if ! $GSS; then
1085                 return
1086         fi
1087
1088         if ! module_loaded ptlrpc_gss; then
1089                 load_module ptlrpc/gss/ptlrpc_gss
1090                 module_loaded ptlrpc_gss ||
1091                         error_exit "init_gss: GSS=$GSS, but gss/krb5 missing"
1092         fi
1093
1094         if $GSS_KRB5 || $GSS_SK; then
1095                 start_gss_daemons || error_exit "start gss daemon failed! rc=$?"
1096         fi
1097
1098         if $GSS_SK && ! $SK_NO_KEY; then
1099                 echo "Loading basic SSK keys on all servers"
1100                 do_nodes $(comma_list $(all_server_nodes)) \
1101                         "lgss_sk -t server -l $SK_PATH/$FSNAME.key || true"
1102                 do_nodes $(comma_list $(all_server_nodes)) \
1103                                 "keyctl show | grep lustre | cut -c1-11 |
1104                                 sed -e 's/ //g;' |
1105                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
1106         fi
1107
1108         if $GSS_SK && $SK_NO_KEY; then
1109                 local numclients=${1:-$CLIENTCOUNT}
1110                 local clients=${CLIENTS:-$HOSTNAME}
1111
1112                 # security ctx config for keyring
1113                 SK_NO_KEY=false
1114                 local lgssc_conf_file="/etc/request-key.d/lgssc.conf"
1115
1116                 if from_build_tree; then
1117                         mkdir -p $SK_OM_PATH
1118                         if grep -q request-key /proc/mounts > /dev/null; then
1119                                 echo "SSK: Request key already mounted."
1120                         else
1121                                 mount -o bind $SK_OM_PATH /etc/request-key.d/
1122                         fi
1123                         local lgssc_conf_line='create lgssc * * '
1124                         lgssc_conf_line+=$(which lgss_keyring)
1125                         lgssc_conf_line+=' %o %k %t %d %c %u %g %T %P %S'
1126                         echo "$lgssc_conf_line" > $lgssc_conf_file
1127                 fi
1128
1129                 [ -e $lgssc_conf_file ] ||
1130                         error_exit "Could not find key options in $lgssc_conf_file"
1131                 echo "$lgssc_conf_file content is:"
1132                 cat $lgssc_conf_file
1133
1134                 if ! local_mode; then
1135                         if from_build_tree; then
1136                                 do_nodes $(comma_list $(all_nodes)) "mkdir -p \
1137                                         $SK_OM_PATH"
1138                                 do_nodes $(comma_list $(all_nodes)) "mount \
1139                                         -o bind $SK_OM_PATH \
1140                                         /etc/request-key.d/"
1141                                 do_nodes $(comma_list $(all_nodes)) "rsync \
1142                                         -aqv $HOSTNAME:$lgssc_conf_file \
1143                                         $lgssc_conf_file >/dev/null 2>&1"
1144                         else
1145                                 do_nodes $(comma_list $(all_nodes)) \
1146                                         "echo $lgssc_conf_file: ; \
1147                                         cat $lgssc_conf_file"
1148                         fi
1149                 fi
1150
1151                 # create shared key on all nodes
1152                 mkdir -p $SK_PATH/nodemap
1153                 rm -f $SK_PATH/$FSNAME.key $SK_PATH/nodemap/c*.key \
1154                         $SK_PATH/$FSNAME-*.key
1155                 # for nodemap testing each client may need own key,
1156                 # and S2S now requires keys as well, both for "client"
1157                 # and for "server"
1158                 if $SK_S2S; then
1159                         lgss_sk -t server -f$FSNAME -n $SK_S2SNMCLI \
1160                                 -w $SK_PATH/$FSNAME-nmclient.key \
1161                                 -d /dev/urandom >/dev/null 2>&1
1162                         lgss_sk -t mgs,server -f$FSNAME -n $SK_S2SNM \
1163                                 -w $SK_PATH/$FSNAME-s2s-server.key \
1164                                 -d /dev/urandom >/dev/null 2>&1
1165                 fi
1166                 # basic key create
1167                 lgss_sk -t server -f$FSNAME -w $SK_PATH/$FSNAME.key \
1168                         -d /dev/urandom >/dev/null 2>&1
1169                 # per-nodemap keys
1170                 for i in $(seq 0 $((numclients - 1))); do
1171                         lgss_sk -t server -f$FSNAME -n c$i \
1172                                 -w $SK_PATH/nodemap/c$i.key -d /dev/urandom \
1173                                 >/dev/null 2>&1
1174                 done
1175                 # Distribute keys
1176                 if ! local_mode; then
1177                         for lnode in $(all_nodes); do
1178                                 scp -r $SK_PATH ${lnode}:$(dirname $SK_PATH)/
1179                         done
1180                 fi
1181                 # Set client keys to client type to generate prime P
1182                 if local_mode; then
1183                         do_nodes $(all_nodes) "lgss_sk -t client,server -m \
1184                                 $SK_PATH/$FSNAME.key >/dev/null 2>&1"
1185                 else
1186                         do_nodes $clients "lgss_sk -t client -m \
1187                                 $SK_PATH/$FSNAME.key >/dev/null 2>&1"
1188                         do_nodes $clients "find $SK_PATH/nodemap -name \*.key | \
1189                                 xargs -IX lgss_sk -t client -m X >/dev/null 2>&1"
1190                 fi
1191                 # This is required for servers as well, if S2S in use
1192                 if $SK_S2S; then
1193                         do_nodes $(comma_list $(mdts_nodes)) \
1194                                 "cp $SK_PATH/$FSNAME-s2s-server.key \
1195                                 $SK_PATH/$FSNAME-s2s-client.key; lgss_sk \
1196                                 -t client -m $SK_PATH/$FSNAME-s2s-client.key \
1197                                 >/dev/null 2>&1"
1198                         do_nodes $(comma_list $(osts_nodes)) \
1199                                 "cp $SK_PATH/$FSNAME-s2s-server.key \
1200                                 $SK_PATH/$FSNAME-s2s-client.key; lgss_sk \
1201                                 -t client -m $SK_PATH/$FSNAME-s2s-client.key \
1202                                 >/dev/null 2>&1"
1203                         do_nodes $clients "lgss_sk -t client \
1204                                 -m $SK_PATH/$FSNAME-nmclient.key \
1205                                  >/dev/null 2>&1"
1206                 fi
1207         fi
1208         if $GSS_SK; then
1209                 # mount options for servers and clients
1210                 MGS_MOUNT_OPTS=$(add_sk_mntflag $MGS_MOUNT_OPTS)
1211                 MDS_MOUNT_OPTS=$(add_sk_mntflag $MDS_MOUNT_OPTS)
1212                 OST_MOUNT_OPTS=$(add_sk_mntflag $OST_MOUNT_OPTS)
1213                 MOUNT_OPTS=$(add_sk_mntflag $MOUNT_OPTS)
1214                 SEC=$SK_FLAVOR
1215                 if [ -z "$LGSS_KEYRING_DEBUG" ]; then
1216                         LGSS_KEYRING_DEBUG=4
1217                 fi
1218         fi
1219
1220         if [ -n "$LGSS_KEYRING_DEBUG" ] && \
1221                ( local_mode || from_build_tree ); then
1222                 lctl set_param -n \
1223                      sptlrpc.gss.lgss_keyring.debug_level=$LGSS_KEYRING_DEBUG
1224         elif [ -n "$LGSS_KEYRING_DEBUG" ]; then
1225                 do_nodes $(comma_list $(all_nodes)) "modprobe ptlrpc_gss && \
1226                 lctl set_param -n \
1227                    sptlrpc.gss.lgss_keyring.debug_level=$LGSS_KEYRING_DEBUG"
1228         fi
1229 }
1230
1231 cleanup_gss() {
1232         if $GSS; then
1233                 stop_gss_daemons
1234                 # maybe cleanup credential cache?
1235         fi
1236 }
1237
1238 cleanup_sk() {
1239         if $GSS_SK; then
1240                 if $SK_S2S; then
1241                         do_node $(mgs_node) "$LCTL nodemap_del $SK_S2SNM"
1242                         do_node $(mgs_node) "$LCTL nodemap_del $SK_S2SNMCLI"
1243                         $RPC_MODE || echo "Sleeping for 10 sec for Nodemap.."
1244                         sleep 10
1245                 fi
1246                 stop_gss_daemons
1247                 $RPC_MODE || echo "Cleaning up Shared Key.."
1248                 do_nodes $(comma_list $(all_nodes)) "rm -f \
1249                         $SK_PATH/$FSNAME*.key $SK_PATH/nodemap/$FSNAME*.key"
1250                 do_nodes $(comma_list $(all_nodes)) "keyctl show | \
1251                   awk '/lustre/ { print \\\$1 }' | xargs -IX keyctl unlink X"
1252                 if from_build_tree; then
1253                         # Remove the mount and clean up the files we added to
1254                         # SK_PATH
1255                         do_nodes $(comma_list $(all_nodes)) "while grep -q \
1256                                 request-key.d /proc/mounts; do umount \
1257                                 /etc/request-key.d/; done"
1258                         do_nodes $(comma_list $(all_nodes)) "rm -f \
1259                                 $SK_OM_PATH/lgssc.conf"
1260                         do_nodes $(comma_list $(all_nodes)) "rmdir $SK_OM_PATH"
1261                 fi
1262                 SK_NO_KEY=true
1263         fi
1264 }
1265
1266 facet_svc() {
1267         local facet=$1
1268         local var=${facet}_svc
1269
1270         echo -n ${!var}
1271 }
1272
1273 facet_type() {
1274         local facet=$1
1275
1276         echo -n $facet | sed -e 's/^fs[0-9]\+//' -e 's/[0-9_]\+//' |
1277                 tr '[:lower:]' '[:upper:]'
1278 }
1279
1280 facet_number() {
1281         local facet=$1
1282
1283         if [ $facet == mgs ] || [ $facet == client ]; then
1284                 return 1
1285         fi
1286
1287         echo -n $facet | sed -e 's/^fs[0-9]\+//' | sed -e 's/^[a-z]\+//'
1288 }
1289
1290 facet_fstype() {
1291         local facet=$1
1292         local var
1293
1294         var=${facet}_FSTYPE
1295         if [ -n "${!var}" ]; then
1296                 echo -n ${!var}
1297                 return
1298         fi
1299
1300         var=$(facet_type $facet)FSTYPE
1301         if [ -n "${!var}" ]; then
1302                 echo -n ${!var}
1303                 return
1304         fi
1305
1306         if [ -n "$FSTYPE" ]; then
1307                 echo -n $FSTYPE
1308                 return
1309         fi
1310
1311         if [[ $facet == mgs ]] && combined_mgs_mds; then
1312                 facet_fstype mds1
1313                 return
1314         fi
1315
1316         return 1
1317 }
1318
1319 node_fstypes() {
1320         local node=$1
1321         local fstypes
1322         local fstype
1323         local facets=$(get_facets)
1324         local facet
1325
1326         for facet in ${facets//,/ }; do
1327                 if [ $node == $(facet_host $facet) ] ||
1328                    [ $node == "$(facet_failover_host $facet)" ]; then
1329                         fstype=$(facet_fstype $facet)
1330                         if [[ $fstypes != *$fstype* ]]; then
1331                                 fstypes+="${fstypes:+,}$fstype"
1332                         fi
1333                 fi
1334         done
1335         echo -n $fstypes
1336 }
1337
1338 facet_index() {
1339         local facet=$1
1340         local num=$(facet_number $facet)
1341         local index
1342
1343         if [[ $(facet_type $facet) = OST ]]; then
1344                 index=OSTINDEX${num}
1345                 if [[ -n "${!index}" ]]; then
1346                         echo -n ${!index}
1347                         return
1348                 fi
1349
1350                 index=${OST_INDICES[num - 1]}
1351         fi
1352
1353         [[ -n "$index" ]] || index=$((num - 1))
1354         echo -n $index
1355 }
1356
1357 devicelabel() {
1358         local facet=$1
1359         local dev=$2
1360         local label
1361         local fstype=$(facet_fstype $facet)
1362
1363         case $fstype in
1364         ldiskfs)
1365                 label=$(do_facet ${facet} "$E2LABEL ${dev} 2>/dev/null");;
1366         zfs)
1367                 label=$(do_facet ${facet} "$ZFS get -H -o value lustre:svname \
1368                                            ${dev} 2>/dev/null");;
1369         *)
1370                 error "unknown fstype!";;
1371         esac
1372
1373         echo -n $label
1374 }
1375
1376 #
1377 # Get the device of a facet.
1378 #
1379 facet_device() {
1380         local facet=$1
1381         local device
1382
1383         case $facet in
1384                 mgs) device=$(mgsdevname) ;;
1385                 mds*) device=$(mdsdevname $(facet_number $facet)) ;;
1386                 ost*) device=$(ostdevname $(facet_number $facet)) ;;
1387                 fs2mds) device=$(mdsdevname 1_2) ;;
1388                 fs2ost) device=$(ostdevname 1_2) ;;
1389                 fs3ost) device=$(ostdevname 2_2) ;;
1390                 *) ;;
1391         esac
1392
1393         echo -n $device
1394 }
1395
1396 #
1397 # Get the virtual device of a facet.
1398 #
1399 facet_vdevice() {
1400         local facet=$1
1401         local device
1402
1403         case $facet in
1404                 mgs) device=$(mgsvdevname) ;;
1405                 mds*) device=$(mdsvdevname $(facet_number $facet)) ;;
1406                 ost*) device=$(ostvdevname $(facet_number $facet)) ;;
1407                 fs2mds) device=$(mdsvdevname 1_2) ;;
1408                 fs2ost) device=$(ostvdevname 1_2) ;;
1409                 fs3ost) device=$(ostvdevname 2_2) ;;
1410                 *) ;;
1411         esac
1412
1413         echo -n $device
1414 }
1415
1416 running_in_vm() {
1417         local virt=$(virt-what 2> /dev/null)
1418
1419         [ $? -eq 0 ] && [ -n "$virt" ] && { echo $virt; return; }
1420
1421         virt=$(dmidecode -s system-product-name | awk '{print $1}')
1422
1423         case $virt in
1424                 VMware|KVM|VirtualBox|Parallels|Bochs)
1425                         echo $virt | tr '[A-Z]' '[a-z]' ;;
1426                 *) ;;
1427         esac
1428 }
1429
1430 #
1431 # Re-read the partition table on failover partner host.
1432 # After a ZFS storage pool is created on a shared device, the partition table
1433 # on the device may change. However, the operating system on the failover
1434 # host may not notice the change automatically. Without the up-to-date partition
1435 # block devices, 'zpool import ..' cannot find the labels, whose positions are
1436 # relative to partition rather than disk beginnings.
1437 #
1438 # This function performs partprobe on the failover host to make it re-read the
1439 # partition table.
1440 #
1441 refresh_partition_table() {
1442         local facet=$1
1443         local device=$2
1444         local host
1445
1446         host=$(facet_passive_host $facet)
1447         if [[ -n "$host" ]]; then
1448                 do_node $host "$PARTPROBE $device"
1449         fi
1450 }
1451
1452 #
1453 # Get ZFS storage pool name.
1454 #
1455 zpool_name() {
1456         local facet=$1
1457         local device
1458         local poolname
1459
1460         device=$(facet_device $facet)
1461         # poolname is string before "/"
1462         poolname="${device%%/*}"
1463
1464         echo -n $poolname
1465 }
1466
1467 #
1468 #
1469 # Get ZFS local fsname.
1470 #
1471 zfs_local_fsname() {
1472         local facet=$1
1473         local lfsname=$(basename $(facet_device $facet))
1474
1475         echo -n $lfsname
1476 }
1477
1478 #
1479 # Create ZFS storage pool.
1480 #
1481 create_zpool() {
1482         local facet=$1
1483         local poolname=$2
1484         local vdev=$3
1485         shift 3
1486         local opts=${@:-"-o cachefile=none"}
1487
1488         do_facet $facet "lsmod | grep zfs >&/dev/null || modprobe zfs;
1489                 $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1490                 $ZPOOL create -f $opts $poolname $vdev"
1491 }
1492
1493 #
1494 # Create ZFS file system.
1495 #
1496 create_zfs() {
1497         local facet=$1
1498         local dataset=$2
1499         shift 2
1500         local opts=${@:-"-o mountpoint=legacy"}
1501
1502         do_facet $facet "$ZFS list -H $dataset >/dev/null 2>&1 ||
1503                 $ZFS create $opts $dataset"
1504 }
1505
1506 #
1507 # Export ZFS storage pool.
1508 # Before exporting the pool, all datasets within the pool should be unmounted.
1509 #
1510 export_zpool() {
1511         local facet=$1
1512         shift
1513         local opts="$@"
1514         local poolname
1515
1516         poolname=$(zpool_name $facet)
1517
1518         if [[ -n "$poolname" ]]; then
1519                 do_facet $facet "! $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1520                         grep -q ^$poolname/ /proc/mounts ||
1521                         $ZPOOL export $opts $poolname"
1522         fi
1523 }
1524
1525 #
1526 # Destroy ZFS storage pool.
1527 # Destroy the given pool and free up any devices for other use. This command
1528 # tries to unmount any active datasets before destroying the pool.
1529 # -f    Force any active datasets contained within the pool to be unmounted.
1530 #
1531 destroy_zpool() {
1532         local facet=$1
1533         local poolname=${2:-$(zpool_name $facet)}
1534
1535         if [[ -n "$poolname" ]]; then
1536                 do_facet $facet "! $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1537                         $ZPOOL destroy -f $poolname"
1538         fi
1539 }
1540
1541 #
1542 # Import ZFS storage pool.
1543 # Force importing, even if the pool appears to be potentially active.
1544 #
1545 import_zpool() {
1546         local facet=$1
1547         shift
1548         local opts=${@:-"-o cachefile=none -o failmode=panic"}
1549         local poolname
1550
1551         poolname=$(zpool_name $facet)
1552
1553         if [[ -n "$poolname" ]]; then
1554                 opts+=" -d $(dirname $(facet_vdevice $facet))"
1555                 do_facet $facet "lsmod | grep zfs >&/dev/null || modprobe zfs;
1556                         $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1557                         $ZPOOL import -f $opts $poolname"
1558         fi
1559 }
1560
1561 #
1562 # Reimport ZFS storage pool with new name
1563 #
1564 reimport_zpool() {
1565         local facet=$1
1566         local newpool=$2
1567         local opts="-o cachefile=none"
1568         local poolname=$(zpool_name $facet)
1569
1570         opts+=" -d $(dirname $(facet_vdevice $facet))"
1571         do_facet $facet "$ZPOOL export $poolname;
1572                          $ZPOOL import $opts $poolname $newpool"
1573 }
1574
1575 #
1576 # Set the "cachefile=none" property on ZFS storage pool so that the pool
1577 # is not automatically imported on system startup.
1578 #
1579 # In a failover environment, this will provide resource level fencing which
1580 # will ensure that the same ZFS storage pool will not be imported concurrently
1581 # on different nodes.
1582 #
1583 disable_zpool_cache() {
1584         local facet=$1
1585         local poolname
1586
1587         poolname=$(zpool_name $facet)
1588
1589         if [[ -n "$poolname" ]]; then
1590                 do_facet $facet "$ZPOOL set cachefile=none $poolname"
1591         fi
1592 }
1593
1594 #
1595 # This and set_osd_param() shall be used to access OSD parameters
1596 # once existed under "obdfilter":
1597 #
1598 #   mntdev
1599 #   stats
1600 #   read_cache_enable
1601 #   writethrough_cache_enable
1602 #
1603 get_osd_param() {
1604         local nodes=$1
1605         local device=${2:-$FSNAME-OST*}
1606         local name=$3
1607
1608         do_nodes $nodes "$LCTL get_param -n osd-*.$device.$name"
1609 }
1610
1611 set_osd_param() {
1612         local nodes=$1
1613         local device=${2:-$FSNAME-OST*}
1614         local name=$3
1615         local value=$4
1616
1617         do_nodes $nodes "$LCTL set_param -n osd-*.$device.$name=$value"
1618 }
1619
1620 set_debug_size () {
1621     local dz=${1:-$DEBUG_SIZE}
1622
1623     if [ -f /sys/devices/system/cpu/possible ]; then
1624         local cpus=$(($(cut -d "-" -f 2 /sys/devices/system/cpu/possible)+1))
1625     else
1626         local cpus=$(getconf _NPROCESSORS_CONF 2>/dev/null)
1627     fi
1628
1629     # bug 19944, adjust size to be -gt num_possible_cpus()
1630     # promise 2MB for every cpu at least
1631     if [ -n "$cpus" ] && [ $((cpus * 2)) -gt $dz ]; then
1632         dz=$((cpus * 2))
1633     fi
1634     lctl set_param debug_mb=$dz
1635 }
1636
1637 set_default_debug () {
1638         local debug=${1:-"$PTLDEBUG"}
1639         local subsys=${2:-"$SUBSYSTEM"}
1640         local debug_size=${3:-$DEBUG_SIZE}
1641
1642         [ -n "$debug" ] && lctl set_param debug="$debug" >/dev/null
1643         [ -n "$subsys" ] && lctl set_param subsystem_debug="${subsys# }" >/dev/null
1644
1645         [ -n "$debug_size" ] && set_debug_size $debug_size > /dev/null
1646 }
1647
1648 set_default_debug_nodes () {
1649         local nodes="$1"
1650         local debug="${2:-"$PTLDEBUG"}"
1651         local subsys="${3:-"$SUBSYSTEM"}"
1652         local debug_size="${4:-$DEBUG_SIZE}"
1653
1654         if [[ ,$nodes, = *,$HOSTNAME,* ]]; then
1655                 nodes=$(exclude_items_from_list "$nodes" "$HOSTNAME")
1656                 set_default_debug
1657         fi
1658
1659         [[ -z "$nodes" ]] ||
1660                 do_rpc_nodes "$nodes" set_default_debug \
1661                         \\\"$debug\\\" \\\"$subsys\\\" $debug_size || true
1662 }
1663
1664 set_default_debug_facet () {
1665         local facet=$1
1666         local debug="${2:-"$PTLDEBUG"}"
1667         local subsys="${3:-"$SUBSYSTEM"}"
1668         local debug_size="${4:-$DEBUG_SIZE}"
1669         local node=$(facet_active_host $facet)
1670
1671         [ -n "$node" ] || error "No host defined for facet $facet"
1672
1673         set_default_debug_nodes $node "$debug" "$subsys" $debug_size
1674 }
1675
1676 set_params_nodes () {
1677         [[ $# -ge 2 ]] || return 0
1678
1679         local nodes=$1
1680         shift
1681         do_nodes $nodes $LCTL set_param $@
1682 }
1683
1684 set_params_clients () {
1685         local clients=${1:-$CLIENTS}
1686         local params=${2:-$CLIENT_LCTL_SETPARAM_PARAM}
1687
1688         [[ -n $params ]] || return 0
1689         set_params_nodes $clients $params
1690 }
1691
1692 set_hostid () {
1693     local hostid=${1:-$(hostid)}
1694
1695     if [ ! -s /etc/hostid ]; then
1696         printf $(echo -n $hostid |
1697             sed 's/\(..\)\(..\)\(..\)\(..\)/\\x\4\\x\3\\x\2\\x\1/') >/etc/hostid
1698     fi
1699 }
1700
1701 # Facet functions
1702 mount_facets () {
1703         local facets=${1:-$(get_facets)}
1704         local facet
1705         local -a mountpids
1706         local total=0
1707         local ret=0
1708
1709         for facet in ${facets//,/ }; do
1710                 mount_facet $facet &
1711                 mountpids[total]=$!
1712                 total=$((total+1))
1713         done
1714         for ((index=0; index<$total; index++)); do
1715                 wait ${mountpids[index]}
1716                 local RC=$?
1717                 [ $RC -eq 0 ] && continue
1718
1719                 if [ "$TESTSUITE.$TESTNAME" = "replay-dual.test_0a" ]; then
1720                         skip_noexit "Restart of $facet failed!." &&
1721                                 touch $LU482_FAILED
1722                 else
1723                         error "Restart of $facet failed!"
1724                 fi
1725                 ret=$RC
1726         done
1727         return $ret
1728 }
1729
1730 #
1731 # Add argument "arg" (e.g., "loop") to the comma-separated list
1732 # of arguments for option "opt" (e.g., "-o") on command
1733 # line "opts" (e.g., "-o flock").
1734 #
1735 csa_add() {
1736         local opts=$1
1737         local opt=$2
1738         local arg=$3
1739         local opt_pattern="\([[:space:]]\+\|^\)$opt"
1740
1741         if echo "$opts" | grep -q $opt_pattern; then
1742                 opts=$(echo "$opts" | sed -e \
1743                         "s/$opt_pattern[[:space:]]*[^[:space:]]\+/&,$arg/")
1744         else
1745                 opts+="${opts:+ }$opt $arg"
1746         fi
1747         echo -n "$opts"
1748 }
1749
1750 #
1751 # Associate loop device with a given regular file.
1752 # Return the loop device.
1753 #
1754 setup_loop_device() {
1755         local facet=$1
1756         local file=$2
1757
1758         do_facet $facet "loop_dev=\\\$($LOSETUP -j $file | cut -d : -f 1);
1759                          if [[ -z \\\$loop_dev ]]; then
1760                                 loop_dev=\\\$($LOSETUP -f);
1761                                 $LOSETUP \\\$loop_dev $file || loop_dev=;
1762                          fi;
1763                          echo -n \\\$loop_dev"
1764 }
1765
1766 #
1767 # Detach a loop device.
1768 #
1769 cleanup_loop_device() {
1770         local facet=$1
1771         local loop_dev=$2
1772
1773         do_facet $facet "! $LOSETUP $loop_dev >/dev/null 2>&1 ||
1774                          $LOSETUP -d $loop_dev"
1775 }
1776
1777 #
1778 # Check if a given device is a block device.
1779 #
1780 is_blkdev() {
1781         local facet=$1
1782         local dev=$2
1783         local size=${3:-""}
1784
1785         [[ -n "$dev" ]] || return 1
1786         do_facet $facet "test -b $dev" || return 1
1787         if [[ -n "$size" ]]; then
1788                 local in=$(do_facet $facet "dd if=$dev of=/dev/null bs=1k \
1789                                             count=1 skip=$size 2>&1" |
1790                                             awk '($3 == "in") { print $1 }')
1791                 [[ "$in" = "1+0" ]] || return 1
1792         fi
1793 }
1794
1795 #
1796 # Check if a given device is a device-mapper device.
1797 #
1798 is_dm_dev() {
1799         local facet=$1
1800         local dev=$2
1801
1802         [[ -n "$dev" ]] || return 1
1803         do_facet $facet "$DMSETUP status $dev >/dev/null 2>&1"
1804 }
1805
1806 #
1807 # Check if a given device is a device-mapper flakey device.
1808 #
1809 is_dm_flakey_dev() {
1810         local facet=$1
1811         local dev=$2
1812         local type
1813
1814         [[ -n "$dev" ]] || return 1
1815
1816         type=$(do_facet $facet "$DMSETUP status $dev 2>&1" |
1817                awk '{print $3}')
1818         [[ $type = flakey ]] && return 0 || return 1
1819 }
1820
1821 #
1822 # Check if device-mapper flakey device is supported by the kernel
1823 # of $facet node or not.
1824 #
1825 dm_flakey_supported() {
1826         local facet=$1
1827
1828         $FLAKEY || return 1
1829         do_facet $facet "modprobe dm-flakey;
1830                          $DMSETUP targets | grep -q flakey" &> /dev/null
1831 }
1832
1833 #
1834 # Get the device-mapper flakey device name of a given facet.
1835 #
1836 dm_facet_devname() {
1837         local facet=$1
1838         [[ $facet = mgs ]] && combined_mgs_mds && facet=mds1
1839
1840         echo -n ${facet}_flakey
1841 }
1842
1843 #
1844 # Get the device-mapper flakey device of a given facet.
1845 # A device created by dmsetup will appear as /dev/mapper/<device-name>.
1846 #
1847 dm_facet_devpath() {
1848         local facet=$1
1849
1850         echo -n $DM_DEV_PATH/$(dm_facet_devname $facet)
1851 }
1852
1853 #
1854 # Set a device-mapper device with a new table.
1855 #
1856 # The table has the following format:
1857 # <logical_start_sector> <num_sectors> <target_type> <target_args>
1858 #
1859 # flakey <target_args> includes:
1860 # <destination_device> <offset> <up_interval> <down_interval> \
1861 # [<num_features> [<feature_arguments>]]
1862 #
1863 # linear <target_args> includes:
1864 # <destination_device> <start_sector>
1865 #
1866 dm_set_dev_table() {
1867         local facet=$1
1868         local dm_dev=$2
1869         local target_type=$3
1870         local num_sectors
1871         local real_dev
1872         local tmp
1873         local table
1874
1875         read tmp num_sectors tmp real_dev tmp \
1876                 <<< $(do_facet $facet "$DMSETUP table $dm_dev")
1877
1878         case $target_type in
1879         flakey)
1880                 table="0 $num_sectors flakey $real_dev 0 0 1800 1 drop_writes"
1881                 ;;
1882         linear)
1883                 table="0 $num_sectors linear $real_dev 0"
1884                 ;;
1885         *) error "invalid target type $target_type" ;;
1886         esac
1887
1888         do_facet $facet "$DMSETUP suspend --nolockfs --noflush $dm_dev" ||
1889                 error "failed to suspend $dm_dev"
1890         do_facet $facet "$DMSETUP load $dm_dev --table \\\"$table\\\"" ||
1891                 error "failed to load $target_type table into $dm_dev"
1892         do_facet $facet "$DMSETUP resume $dm_dev" ||
1893                 error "failed to resume $dm_dev"
1894 }
1895
1896 #
1897 # Set a device-mapper flakey device as "read-only" by using the "drop_writes"
1898 # feature parameter.
1899 #
1900 # drop_writes:
1901 #       All write I/O is silently ignored.
1902 #       Read I/O is handled correctly.
1903 #
1904 dm_set_dev_readonly() {
1905         local facet=$1
1906         local dm_dev=${2:-$(dm_facet_devpath $facet)}
1907
1908         dm_set_dev_table $facet $dm_dev flakey
1909 }
1910
1911 #
1912 # Set a device-mapper device to traditional linear mapping mode.
1913 #
1914 dm_clear_dev_readonly() {
1915         local facet=$1
1916         local dm_dev=${2:-$(dm_facet_devpath $facet)}
1917
1918         dm_set_dev_table $facet $dm_dev linear
1919 }
1920
1921 #
1922 # Set the device of a given facet as "read-only".
1923 #
1924 set_dev_readonly() {
1925         local facet=$1
1926         local svc=${facet}_svc
1927
1928         if [[ $(facet_fstype $facet) = zfs ]] ||
1929            ! dm_flakey_supported $facet; then
1930                 do_facet $facet $LCTL --device ${!svc} readonly
1931         else
1932                 dm_set_dev_readonly $facet
1933         fi
1934 }
1935
1936 #
1937 # Get size in 512-byte sectors (BLKGETSIZE64 / 512) of a given device.
1938 #
1939 get_num_sectors() {
1940         local facet=$1
1941         local dev=$2
1942         local num_sectors
1943
1944         num_sectors=$(do_facet $facet "blockdev --getsz $dev 2>/dev/null")
1945         [[ ${PIPESTATUS[0]} = 0 && -n "$num_sectors" ]] || num_sectors=0
1946         echo -n $num_sectors
1947 }
1948
1949 #
1950 # Create a device-mapper device with a given block device or regular file (will
1951 # be associated with loop device).
1952 # Return the full path of the device-mapper device.
1953 #
1954 dm_create_dev() {
1955         local facet=$1
1956         local real_dev=$2                                  # destination device
1957         local dm_dev_name=${3:-$(dm_facet_devname $facet)} # device name
1958         local dm_dev=$DM_DEV_PATH/$dm_dev_name            # device-mapper device
1959
1960         # check if the device-mapper device to be created already exists
1961         if is_dm_dev $facet $dm_dev; then
1962                 # if the existing device was set to "read-only", then clear it
1963                 ! is_dm_flakey_dev $facet $dm_dev ||
1964                         dm_clear_dev_readonly $facet $dm_dev
1965
1966                 echo -n $dm_dev
1967                 return 0
1968         fi
1969
1970         # check if the destination device is a block device, and if not,
1971         # associate it with a loop device
1972         is_blkdev $facet $real_dev ||
1973                 real_dev=$(setup_loop_device $facet $real_dev)
1974         [[ -n "$real_dev" ]] || { echo -n $real_dev; return 2; }
1975
1976         # now create the device-mapper device
1977         local num_sectors=$(get_num_sectors $facet $real_dev)
1978         local table="0 $num_sectors linear $real_dev 0"
1979         local rc=0
1980
1981         do_facet $facet "$DMSETUP create $dm_dev_name --table \\\"$table\\\"" ||
1982                 { rc=${PIPESTATUS[0]}; dm_dev=; }
1983         do_facet $facet "$DMSETUP mknodes >/dev/null 2>&1"
1984
1985         echo -n $dm_dev
1986         return $rc
1987 }
1988
1989 #
1990 # Map the facet name to its device variable name.
1991 #
1992 facet_device_alias() {
1993         local facet=$1
1994         local dev_alias=$facet
1995
1996         case $facet in
1997                 fs2mds) dev_alias=mds1_2 ;;
1998                 fs2ost) dev_alias=ost1_2 ;;
1999                 fs3ost) dev_alias=ost2_2 ;;
2000                 *) ;;
2001         esac
2002
2003         echo -n $dev_alias
2004 }
2005
2006 #
2007 # Save the original value of the facet device and export the new value.
2008 #
2009 export_dm_dev() {
2010         local facet=$1
2011         local dm_dev=$2
2012
2013         local active_facet=$(facet_active $facet)
2014         local dev_alias=$(facet_device_alias $active_facet)
2015         local dev_name=${dev_alias}_dev
2016         local dev=${!dev_name}
2017
2018         if [[ $active_facet = $facet ]]; then
2019                 local failover_dev=${dev_alias}failover_dev
2020                 if [[ ${!failover_dev} = $dev ]]; then
2021                         eval export ${failover_dev}_saved=$dev
2022                         eval export ${failover_dev}=$dm_dev
2023                 fi
2024         else
2025                 dev_alias=$(facet_device_alias $facet)
2026                 local facet_dev=${dev_alias}_dev
2027                 if [[ ${!facet_dev} = $dev ]]; then
2028                         eval export ${facet_dev}_saved=$dev
2029                         eval export ${facet_dev}=$dm_dev
2030                 fi
2031         fi
2032
2033         eval export ${dev_name}_saved=$dev
2034         eval export ${dev_name}=$dm_dev
2035 }
2036
2037 #
2038 # Restore the saved value of the facet device.
2039 #
2040 unexport_dm_dev() {
2041         local facet=$1
2042
2043         [[ $facet = mgs ]] && combined_mgs_mds && facet=mds1
2044         local dev_alias=$(facet_device_alias $facet)
2045
2046         local saved_dev=${dev_alias}_dev_saved
2047         [[ -z ${!saved_dev} ]] ||
2048                 eval export ${dev_alias}_dev=${!saved_dev}
2049
2050         saved_dev=${dev_alias}failover_dev_saved
2051         [[ -z ${!saved_dev} ]] ||
2052                 eval export ${dev_alias}failover_dev=${!saved_dev}
2053 }
2054
2055 #
2056 # Remove a device-mapper device.
2057 # If the destination device is a loop device, then also detach it.
2058 #
2059 dm_cleanup_dev() {
2060         local facet=$1
2061         local dm_dev=${2:-$(dm_facet_devpath $facet)}
2062         local major
2063         local minor
2064
2065         is_dm_dev $facet $dm_dev || return 0
2066
2067         read major minor <<< $(do_facet $facet "$DMSETUP table $dm_dev" |
2068                 awk '{ print $4 }' | awk -F: '{ print $1" "$2 }')
2069
2070         do_facet $facet "$DMSETUP remove $dm_dev"
2071         do_facet $facet "$DMSETUP mknodes >/dev/null 2>&1"
2072
2073         unexport_dm_dev $facet
2074
2075         # detach a loop device
2076         [[ $major -ne 7 ]] || cleanup_loop_device $facet /dev/loop$minor
2077
2078         # unload dm-flakey module
2079         do_facet $facet "modprobe -r dm-flakey" || true
2080 }
2081
2082 mount_facet() {
2083         local facet=$1
2084         shift
2085         local active_facet=$(facet_active $facet)
2086         local dev_alias=$(facet_device_alias $active_facet)
2087         local dev=${dev_alias}_dev
2088         local opt=${facet}_opt
2089         local mntpt=$(facet_mntpt $facet)
2090         local opts="${!opt} $@"
2091         local fstype=$(facet_fstype $facet)
2092         local devicelabel
2093         local dm_dev=${!dev}
2094
2095         [[ $dev == "mgsfailover_dev" ]] && combined_mgs_mds &&
2096                 dev=mds1failover_dev
2097
2098         module_loaded lustre || load_modules
2099
2100         case $fstype in
2101         ldiskfs)
2102                 if dm_flakey_supported $facet; then
2103                         dm_dev=$(dm_create_dev $facet ${!dev})
2104                         [[ -n "$dm_dev" ]] || dm_dev=${!dev}
2105                 fi
2106
2107                 is_blkdev $facet $dm_dev || opts=$(csa_add "$opts" -o loop)
2108
2109                 devicelabel=$(do_facet ${facet} "$E2LABEL $dm_dev");;
2110         zfs)
2111                 # import ZFS storage pool
2112                 import_zpool $facet || return ${PIPESTATUS[0]}
2113
2114                 devicelabel=$(do_facet ${facet} "$ZFS get -H -o value \
2115                                                 lustre:svname $dm_dev");;
2116         *)
2117                 error "unknown fstype!";;
2118         esac
2119
2120         echo "Starting ${facet}: $opts $dm_dev $mntpt"
2121         # for testing LU-482 error handling in mount_facets() and test_0a()
2122         if [ -f $TMP/test-lu482-trigger ]; then
2123                 RC=2
2124         else
2125                 do_facet ${facet} \
2126                         "mkdir -p $mntpt; $MOUNT_CMD $opts $dm_dev $mntpt"
2127                 RC=${PIPESTATUS[0]}
2128         fi
2129
2130         if [ $RC -ne 0 ]; then
2131                 echo "Start of $dm_dev on ${facet} failed ${RC}"
2132                 return $RC
2133         fi
2134
2135         health=$(do_facet ${facet} "$LCTL get_param -n health_check")
2136         if [[ "$health" != "healthy" ]]; then
2137                 error "$facet is in a unhealthy state"
2138         fi
2139
2140         set_default_debug_facet $facet
2141
2142         if [[ $opts =~ .*nosvc.* ]]; then
2143                 echo "Start $dm_dev without service"
2144         else
2145
2146                 case $fstype in
2147                 ldiskfs)
2148                         wait_update_facet ${facet} "$E2LABEL $dm_dev \
2149                                 2>/dev/null | grep -E ':[a-zA-Z]{3}[0-9]{4}'" \
2150                                 "" || error "$dm_dev failed to initialize!";;
2151                 zfs)
2152                         wait_update_facet ${facet} "$ZFS get -H -o value \
2153                                 lustre:svname $dm_dev 2>/dev/null | \
2154                                 grep -E ':[a-zA-Z]{3}[0-9]{4}'" "" ||
2155                                 error "$dm_dev failed to initialize!";;
2156
2157                 *)
2158                         error "unknown fstype!";;
2159                 esac
2160         fi
2161
2162         # commit the device label change to disk
2163         if [[ $devicelabel =~ (:[a-zA-Z]{3}[0-9]{4}) ]]; then
2164                 echo "Commit the device label on ${!dev}"
2165                 do_facet $facet "sync; sleep 1; sync"
2166         fi
2167
2168
2169         label=$(devicelabel ${facet} $dm_dev)
2170         [ -z "$label" ] && echo no label for $dm_dev && exit 1
2171         eval export ${facet}_svc=${label}
2172         echo Started ${label}
2173
2174         export_dm_dev $facet $dm_dev
2175
2176         return $RC
2177 }
2178
2179 # start facet device options
2180 start() {
2181         local facet=$1
2182         shift
2183         local device=$1
2184         shift
2185         local dev_alias=$(facet_device_alias $facet)
2186
2187         eval export ${dev_alias}_dev=${device}
2188         eval export ${facet}_opt=\"$@\"
2189
2190         combined_mgs_mds && [[ ${dev_alias} == mds1 ]] &&
2191                 eval export mgs_dev=${device}
2192
2193         local varname=${dev_alias}failover_dev
2194         if [ -n "${!varname}" ] ; then
2195                 eval export ${dev_alias}failover_dev=${!varname}
2196         else
2197                 eval export ${dev_alias}failover_dev=$device
2198                 combined_mgs_mds && [[ ${dev_alias} == mds1 ]] &&
2199                         eval export mgsfailover_dev=${device}
2200
2201         fi
2202
2203         local mntpt=$(facet_mntpt $facet)
2204         do_facet ${facet} mkdir -p $mntpt
2205         eval export ${facet}_MOUNT=$mntpt
2206         mount_facet ${facet}
2207         RC=$?
2208
2209         return $RC
2210 }
2211
2212 stop() {
2213         local running
2214         local facet=$1
2215         shift
2216         local HOST=$(facet_active_host $facet)
2217         [[ -z $HOST ]] && echo stop: no host for $facet && return 0
2218
2219         local mntpt=$(facet_mntpt $facet)
2220         running=$(do_facet ${facet} "grep -c $mntpt' ' /proc/mounts || true")
2221         if [ ${running} -ne 0 ]; then
2222                 echo "Stopping $mntpt (opts:$@) on $HOST"
2223                 do_facet ${facet} $UMOUNT $@ $mntpt
2224         fi
2225
2226         # umount should block, but we should wait for unrelated obd's
2227         # like the MGS or MGC to also stop.
2228         wait_exit_ST ${facet} || return ${PIPESTATUS[0]}
2229
2230         if [[ $(facet_fstype $facet) == zfs ]]; then
2231                 # export ZFS storage pool
2232                 [ "$KEEP_ZPOOL" = "true" ] || export_zpool $facet
2233         elif dm_flakey_supported $facet; then
2234                 local host=${facet}_HOST
2235                 local failover_host=${facet}failover_HOST
2236                 if [[ -n ${!failover_host} && ${!failover_host} != ${!host} ]]||
2237                         $CLEANUP_DM_DEV || [[ $facet = fs* ]]; then
2238                         dm_cleanup_dev $facet
2239                 fi
2240         fi
2241 }
2242
2243 # get mdt quota type
2244 mdt_quota_type() {
2245         local varsvc=${SINGLEMDS}_svc
2246         do_facet $SINGLEMDS $LCTL get_param -n \
2247                 osd-$(facet_fstype $SINGLEMDS).${!varsvc}.quota_slave.enabled
2248 }
2249
2250 # get ost quota type
2251 ost_quota_type() {
2252         # All OSTs should have same quota type
2253         local varsvc=ost1_svc
2254         do_facet ost1 $LCTL get_param -n \
2255                 osd-$(facet_fstype ost1).${!varsvc}.quota_slave.enabled
2256 }
2257
2258 # restore old quota type settings
2259 restore_quota() {
2260         if [ "$old_MDT_QUOTA_TYPE" ]; then
2261                 if [[ $PERM_CMD == *"set_param -P"* ]]; then
2262                         do_facet mgs $PERM_CMD \
2263                                 osd-*.$FSNAME-MDT*.quota_slave.enabled = \
2264                                 $old_MDT_QUOTA_TYPE
2265                 else
2266                         do_facet mgs $PERM_CMD \
2267                                 $FSNAME.quota.mdt=$old_MDT_QUOTA_TYPE
2268                 fi
2269         fi
2270         if [ "$old_OST_QUOTA_TYPE" ]; then
2271                 if [[ $PERM_CMD == *"set_param -P"* ]]; then
2272                         do_facet mgs $PERM_CMD \
2273                                 osd-*.$FSNAME-OST*.quota_slave.enabled = \
2274                                 $old_OST_QUOTA_TYPE
2275                 else
2276                         do_facet mgs $LCTL conf_param \
2277                                 $FSNAME.quota.ost=$old_OST_QUOTA_TYPE
2278                 fi
2279         fi
2280 }
2281
2282 # Handle the case when there is a space in the lfs df
2283 # "filesystem summary" line the same as when there is no space.
2284 # This will allow fixing the "lfs df" summary line in the future.
2285 lfs_df() {
2286         $LFS df $* | sed -e 's/filesystem /filesystem_/'
2287         check_lfs_df_ret_val $?
2288 }
2289
2290 # Get free inodes on the MDT specified by mdt index, free indoes on
2291 # the whole filesystem will be returned when index == -1.
2292 mdt_free_inodes() {
2293         local index=$1
2294         local free_inodes
2295         local mdt_uuid
2296
2297         if [ $index -eq -1 ]; then
2298                 mdt_uuid="summary"
2299         else
2300                 mdt_uuid=$(mdtuuid_from_index $index)
2301         fi
2302
2303         free_inodes=$(lfs_df -i $MOUNT | grep $mdt_uuid | awk '{print $4}')
2304         echo $free_inodes
2305 }
2306
2307 #
2308 # Get the OST device status from 'lfs df' with a given OST index.
2309 #
2310 ost_dev_status() {
2311         local ost_idx=$1
2312         local mnt_pnt=${2:-$MOUNT}
2313         local opts=$3
2314         local ost_uuid
2315
2316         ost_uuid=$(ostuuid_from_index $ost_idx $mnt_pnt)
2317         lfs_df $opts $mnt_pnt | awk '/'$ost_uuid'/ { print $7 }'
2318 }
2319
2320 setup_quota(){
2321         local mntpt=$1
2322
2323         # save old quota type & set new quota type
2324         local mdt_qtype=$(mdt_quota_type)
2325         local ost_qtype=$(ost_quota_type)
2326
2327         echo "[HOST:$HOSTNAME] [old_mdt_qtype:$mdt_qtype]" \
2328                 "[old_ost_qtype:$ost_qtype] [new_qtype:$QUOTA_TYPE]"
2329
2330         export old_MDT_QUOTA_TYPE=$mdt_qtype
2331         export old_OST_QUOTA_TYPE=$ost_qtype
2332
2333         if [[ $PERM_CMD == *"set_param -P"* ]]; then
2334                 do_facet mgs $PERM_CMD \
2335                         osd-*.$FSNAME-MDT*.quota_slave.enabled=$QUOTA_TYPE
2336                 do_facet mgs $PERM_CMD \
2337                         osd-*.$FSNAME-OST*.quota_slave.enabled=$QUOTA_TYPE
2338         else
2339                 do_facet mgs $PERM_CMD $FSNAME.quota.mdt=$QUOTA_TYPE ||
2340                         error "set mdt quota type failed"
2341                 do_facet mgs $PERM_CMD $FSNAME.quota.ost=$QUOTA_TYPE ||
2342                         error "set ost quota type failed"
2343         fi
2344
2345         local quota_usrs=$QUOTA_USERS
2346
2347         # get_filesystem_size
2348         local disksz=$(lfs_df $mntpt | grep "summary" | awk '{print $2}')
2349         local blk_soft=$((disksz + 1024))
2350         local blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over
2351
2352         local inodes=$(lfs_df -i $mntpt | grep "summary" | awk '{print $2}')
2353         local i_soft=$inodes
2354         local i_hard=$((i_soft + i_soft / 20))
2355
2356         echo "Total disk size: $disksz  block-softlimit: $blk_soft" \
2357                 "block-hardlimit: $blk_hard inode-softlimit: $i_soft" \
2358                 "inode-hardlimit: $i_hard"
2359
2360         local cmd
2361         for usr in $quota_usrs; do
2362                 echo "Setting up quota on $HOSTNAME:$mntpt for $usr..."
2363                 for type in u g; do
2364                         cmd="$LFS setquota -$type $usr -b $blk_soft"
2365                         cmd="$cmd -B $blk_hard -i $i_soft -I $i_hard $mntpt"
2366                         echo "+ $cmd"
2367                         eval $cmd || error "$cmd FAILED!"
2368                 done
2369                 # display the quota status
2370                 echo "Quota settings for $usr : "
2371                 $LFS quota -v -u $usr $mntpt || true
2372         done
2373 }
2374
2375 zconf_mount() {
2376         local client=$1
2377         local mnt=$2
2378         local opts=${3:-$MOUNT_OPTS}
2379         opts=${opts:+-o $opts}
2380         local flags=${4:-$MOUNT_FLAGS}
2381
2382         local device=$MGSNID:/$FSNAME$FILESET
2383         if [ -z "$mnt" -o -z "$FSNAME" ]; then
2384                 echo "Bad mount command: opt=$flags $opts dev=$device " \
2385                      "mnt=$mnt"
2386                 exit 1
2387         fi
2388
2389         if $GSS_SK; then
2390                 # update mount option with skpath
2391                 opts=$(add_sk_mntflag $opts)
2392         fi
2393
2394         echo "Starting client: $client: $flags $opts $device $mnt"
2395         do_node $client mkdir -p $mnt
2396         if [ -n "$FILESET" -a -z "$SKIP_FILESET" ];then
2397                 do_node $client $MOUNT_CMD $flags $opts $MGSNID:/$FSNAME \
2398                         $mnt || return 1
2399                 #disable FILESET if not supported
2400                 do_nodes $client lctl get_param -n \
2401                         mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
2402                                 device=$MGSNID:/$FSNAME
2403                 do_node $client mkdir -p $mnt/$FILESET
2404                 do_node $client "! grep -q $mnt' ' /proc/mounts ||
2405                         umount $mnt"
2406         fi
2407         if $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then
2408                 # Mount using nodemap key
2409                 local mountkey=$SK_PATH/$FSNAME-nmclient.key
2410                 if $SK_UNIQUE_NM; then
2411                         mountkey=$SK_PATH/nodemap/c0.key
2412                 fi
2413                 local prunedopts=$(echo $opts |
2414                                 sed -e "s#skpath=[^,^ ]*#skpath=$mountkey#g")
2415                 do_node $client $MOUNT_CMD $flags $prunedopts $device $mnt ||
2416                                 return 1
2417         else
2418                 do_node $client $MOUNT_CMD $flags $opts $device $mnt ||
2419                                 return 1
2420         fi
2421
2422         set_default_debug_nodes $client
2423         set_params_clients $client
2424
2425         return 0
2426 }
2427
2428 zconf_umount() {
2429         local client=$1
2430         local mnt=$2
2431         local force
2432         local busy
2433         local need_kill
2434         local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
2435
2436         [ "$3" ] && force=-f
2437         [ $running -eq 0 ] && return 0
2438
2439         echo "Stopping client $client $mnt (opts:$force)"
2440         do_node $client lsof -t $mnt || need_kill=no
2441         if [ "x$force" != "x" ] && [ "x$need_kill" != "xno" ]; then
2442                 pids=$(do_node $client lsof -t $mnt | sort -u);
2443                 if [ -n "$pids" ]; then
2444                         do_node $client kill -9 $pids || true
2445                 fi
2446         fi
2447
2448         busy=$(do_node $client "umount $force $mnt 2>&1" | grep -c "busy") ||
2449                 true
2450         if [ $busy -ne 0 ] ; then
2451                 echo "$mnt is still busy, wait one second" && sleep 1
2452                 do_node $client umount $force $mnt
2453         fi
2454 }
2455
2456 # Mount the file system on the MDS
2457 mount_mds_client() {
2458         local host=$(facet_active_host $SINGLEMDS)
2459         echo $host
2460         zconf_mount $host $MOUNT2 $MOUNT_OPTS ||
2461                 error "unable to mount $MOUNT2 on $host"
2462 }
2463
2464 # Unmount the file system on the MDS
2465 umount_mds_client() {
2466         local host=$(facet_active_host $SINGLEMDS)
2467         zconf_umount $host $MOUNT2
2468         do_facet $SINGLEMDS "rmdir $MOUNT2"
2469 }
2470
2471 # nodes is comma list
2472 sanity_mount_check_nodes () {
2473     local nodes=$1
2474     shift
2475     local mnts="$@"
2476     local mnt
2477
2478     # FIXME: assume that all cluster nodes run the same os
2479     [ "$(uname)" = Linux ] || return 0
2480
2481     local rc=0
2482     for mnt in $mnts ; do
2483         do_nodes $nodes "running=\\\$(grep -c $mnt' ' /proc/mounts);
2484 mpts=\\\$(mount | grep -c $mnt' ');
2485 if [ \\\$running -ne \\\$mpts ]; then
2486     echo \\\$(hostname) env are INSANE!;
2487     exit 1;
2488 fi"
2489     [ $? -eq 0 ] || rc=1
2490     done
2491     return $rc
2492 }
2493
2494 sanity_mount_check_servers () {
2495     [ -n "$CLIENTONLY" ] &&
2496         { echo "CLIENTONLY mode, skip mount_check_servers"; return 0; } || true
2497     echo Checking servers environments
2498
2499     # FIXME: modify get_facets to display all facets wo params
2500     local facets="$(get_facets OST),$(get_facets MDS),mgs"
2501     local node
2502     local mntpt
2503     local facet
2504     for facet in ${facets//,/ }; do
2505         node=$(facet_host ${facet})
2506         mntpt=$(facet_mntpt $facet)
2507         sanity_mount_check_nodes $node $mntpt ||
2508             { error "server $node environments are insane!"; return 1; }
2509     done
2510 }
2511
2512 sanity_mount_check_clients () {
2513     local clients=${1:-$CLIENTS}
2514     local mntpt=${2:-$MOUNT}
2515     local mntpt2=${3:-$MOUNT2}
2516
2517     [ -z $clients ] && clients=$(hostname)
2518     echo Checking clients $clients environments
2519
2520     sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
2521        error "clients environments are insane!"
2522 }
2523
2524 sanity_mount_check () {
2525     sanity_mount_check_servers || return 1
2526     sanity_mount_check_clients || return 2
2527 }
2528
2529 # mount clients if not mouted
2530 zconf_mount_clients() {
2531         local clients=$1
2532         local mnt=$2
2533         local opts=${3:-$MOUNT_OPTS}
2534         opts=${opts:+-o $opts}
2535         local flags=${4:-$MOUNT_FLAGS}
2536         local device=$MGSNID:/$FSNAME$FILESET
2537         if [ -z "$mnt" -o -z "$FSNAME" ]; then
2538                 echo "Bad conf mount command: opt=$flags $opts dev=$device " \
2539                      "mnt=$mnt"
2540                 exit 1
2541         fi
2542
2543         echo "Starting client $clients: $flags $opts $device $mnt"
2544         do_nodes $clients mkdir -p $mnt
2545         if [ -n "$FILESET" -a -z "$SKIP_FILESET" ]; then
2546                 if $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then
2547                         # Mount with own nodemap key
2548                         local i=0
2549                         # Mount all server nodes first with per-NM keys
2550                         for nmclient in ${clients//,/ }; do
2551 #                               do_nodes $(comma_list $(all_server_nodes)) "lgss_sk -t server -l $SK_PATH/nodemap/c$i.key -n c$i"
2552                                 do_nodes $(comma_list $(all_server_nodes)) "lgss_sk -t server -l $SK_PATH/nodemap/c$i.key"
2553                                 i=$((i + 1))
2554                         done
2555                         # set perms for per-nodemap keys else permission denied
2556                         do_nodes $(comma_list $(all_nodes)) \
2557                                 "keyctl show | grep lustre | cut -c1-11 |
2558                                 sed -e 's/ //g;' |
2559                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
2560                         local mountkey=$SK_PATH/$FSNAME-nmclient.key
2561                         i=0
2562                         for nmclient in ${clients//,/ }; do
2563                                 if $SK_UNIQUE_NM; then
2564                                         mountkey=$SK_PATH/nodemap/c$i.key
2565                                 fi
2566                                 do_node $nmclient "! grep -q $mnt' ' \
2567                                         /proc/mounts || umount $mnt"
2568                                 local prunedopts=$(add_sk_mntflag $prunedopts);
2569                                 prunedopts=$(echo $prunedopts | sed -e \
2570                                         "s#skpath=[^ ^,]*#skpath=$mountkey#g")
2571                                 set -x
2572                                 do_nodes $(comma_list $(all_server_nodes)) \
2573                                         "keyctl show"
2574                                 set +x
2575                                 do_node $nmclient $MOUNT_CMD $flags \
2576                                         $prunedopts $MGSNID:/$FSNAME $mnt ||
2577                                         return 1
2578                                 i=$((i + 1))
2579                         done
2580                 else
2581                         do_nodes $clients "! grep -q $mnt' ' /proc/mounts ||
2582                                         umount $mnt"
2583                         do_nodes $clients $MOUNT_CMD $flags $opts \
2584                                         $MGSNID:/$FSNAME $mnt || return 1
2585                 fi
2586                 #disable FILESET if not supported
2587                 do_nodes $clients lctl get_param -n \
2588                         mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
2589                                 device=$MGSNID:/$FSNAME
2590                 do_nodes $clients mkdir -p $mnt/$FILESET
2591                 do_nodes $clients "! grep -q $mnt' ' /proc/mounts ||
2592                         umount $mnt"
2593         fi
2594
2595         if $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then
2596                 # Mount with nodemap key
2597                 local i=0
2598                 local mountkey=$SK_PATH/$FSNAME-nmclient.key
2599                 for nmclient in ${clients//,/ }; do
2600                         if $SK_UNIQUE_NM; then
2601                                 mountkey=$SK_PATH/nodemap/c$i.key
2602                         fi
2603                         local prunedopts=$(echo $opts | sed -e \
2604                                 "s#skpath=[^ ^,]*#skpath=$mountkey#g");
2605                         do_node $nmclient "! grep -q $mnt' ' /proc/mounts ||
2606                                 umount $mnt"
2607                         do_node $nmclient "
2608                 running=\\\$(mount | grep -c $mnt' ');
2609                 rc=0;
2610                 if [ \\\$running -eq 0 ] ; then
2611                         mkdir -p $mnt;
2612                         $MOUNT_CMD $flags $prunedopts $device $mnt;
2613                         rc=\\\$?;
2614                 else
2615                         lustre_mnt_count=\\\$(mount | grep $mnt' ' | \
2616                                 grep 'type lustre' | wc -l);
2617                         if [ \\\$running -ne \\\$lustre_mnt_count ] ; then
2618                                 echo zconf_mount_clients FAILED: \
2619                                         mount count \\\$running, not matching \
2620                                         with mount count of 'type lustre' \
2621                                         \\\$lustre_mnt_count;
2622                                 rc=1;
2623                         fi;
2624                 fi;
2625         exit \\\$rc" || return ${PIPESTATUS[0]}
2626
2627                         i=$((i + 1))
2628                 done
2629         else
2630
2631                 local tmpopts=$opts
2632                 if $SHARED_KEY; then
2633                         tmpopts=$(add_sk_mntflag $opts)
2634                 fi
2635                 do_nodes $clients "
2636 running=\\\$(mount | grep -c $mnt' ');
2637 rc=0;
2638 if [ \\\$running -eq 0 ] ; then
2639         mkdir -p $mnt;
2640         $MOUNT_CMD $flags $tmpopts $device $mnt;
2641         rc=\\\$?;
2642 fi;
2643 exit \\\$rc" || return ${PIPESTATUS[0]}
2644         fi
2645
2646         echo "Started clients $clients: "
2647         do_nodes $clients "mount | grep $mnt' '"
2648
2649         set_default_debug_nodes $clients
2650         set_params_clients $clients
2651
2652         return 0
2653 }
2654
2655 zconf_umount_clients() {
2656     local clients=$1
2657     local mnt=$2
2658     local force
2659
2660     [ "$3" ] && force=-f
2661
2662     echo "Stopping clients: $clients $mnt (opts:$force)"
2663     do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
2664 if [ \\\$running -ne 0 ] ; then
2665 echo Stopping client \\\$(hostname) $mnt opts:$force;
2666 lsof $mnt || need_kill=no;
2667 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
2668     pids=\\\$(lsof -t $mnt | sort -u);
2669     if [ -n \\\"\\\$pids\\\" ]; then
2670              kill -9 \\\$pids;
2671     fi
2672 fi;
2673 while umount $force $mnt 2>&1 | grep -q "busy"; do
2674     echo "$mnt is still busy, wait one second" && sleep 1;
2675 done;
2676 fi"
2677 }
2678
2679 shutdown_node () {
2680     local node=$1
2681     echo + $POWER_DOWN $node
2682     $POWER_DOWN $node
2683 }
2684
2685 shutdown_node_hard () {
2686     local host=$1
2687     local attempts=$SHUTDOWN_ATTEMPTS
2688
2689     for i in $(seq $attempts) ; do
2690         shutdown_node $host
2691         sleep 1
2692         wait_for_function --quiet "! ping -w 3 -c 1 $host" 5 1 && return 0
2693         echo "waiting for $host to fail attempts=$attempts"
2694         [ $i -lt $attempts ] || \
2695             { echo "$host still pingable after power down! attempts=$attempts" && return 1; }
2696     done
2697 }
2698
2699 shutdown_client() {
2700     local client=$1
2701     local mnt=${2:-$MOUNT}
2702     local attempts=3
2703
2704     if [ "$FAILURE_MODE" = HARD ]; then
2705         shutdown_node_hard $client
2706     else
2707        zconf_umount_clients $client $mnt -f
2708     fi
2709 }
2710
2711 facets_on_host () {
2712     local host=$1
2713     local facets="$(get_facets OST),$(get_facets MDS)"
2714     local affected
2715
2716     combined_mgs_mds || facets="$facets,mgs"
2717
2718     for facet in ${facets//,/ }; do
2719         if [ $(facet_active_host $facet) == $host ]; then
2720            affected="$affected $facet"
2721         fi
2722     done
2723
2724     echo $(comma_list $affected)
2725 }
2726
2727 facet_up() {
2728         local facet=$1
2729         local host=${2:-$(facet_host $facet)}
2730
2731         local label=$(convert_facet2label $facet)
2732         do_node $host $LCTL dl | awk '{ print $4 }' | grep -q "^$label\$"
2733 }
2734
2735 facets_up_on_host () {
2736     local host=$1
2737     local facets=$(facets_on_host $host)
2738     local affected_up
2739
2740     for facet in ${facets//,/ }; do
2741         if $(facet_up $facet $host); then
2742             affected_up="$affected_up $facet"
2743         fi
2744     done
2745
2746     echo $(comma_list $affected_up)
2747 }
2748
2749 shutdown_facet() {
2750         local facet=$1
2751         local affected_facet
2752         local affected_facets
2753
2754         if [[ "$FAILURE_MODE" = HARD ]]; then
2755                 if [[ $(facet_fstype $facet) = ldiskfs ]] &&
2756                         dm_flakey_supported $facet; then
2757                         affected_facets=$(affected_facets $facet)
2758                         for affected_facet in ${affected_facets//,/ }; do
2759                                 unexport_dm_dev $affected_facet
2760                         done
2761                 fi
2762
2763                 shutdown_node_hard $(facet_active_host $facet)
2764         else
2765                 stop $facet
2766         fi
2767 }
2768
2769 reboot_node() {
2770     local node=$1
2771     echo + $POWER_UP $node
2772     $POWER_UP $node
2773 }
2774
2775 remount_facet() {
2776     local facet=$1
2777
2778     stop $facet
2779     mount_facet $facet
2780 }
2781
2782 reboot_facet() {
2783         local facet=$1
2784         local node=$(facet_active_host $facet)
2785         local sleep_time=${2:-10}
2786
2787         if [ "$FAILURE_MODE" = HARD ]; then
2788                 boot_node $node
2789         else
2790                 sleep $sleep_time
2791         fi
2792 }
2793
2794 boot_node() {
2795         local node=$1
2796
2797         if [ "$FAILURE_MODE" = HARD ]; then
2798                 reboot_node $node
2799                 wait_for_host $node
2800                 if $LOAD_MODULES_REMOTE; then
2801                         echo "loading modules on $node: $facet"
2802                         do_rpc_nodes $node load_modules_local
2803                 fi
2804         fi
2805 }
2806
2807 facets_hosts () {
2808     local facets=$1
2809     local hosts
2810
2811     for facet in ${facets//,/ }; do
2812         hosts=$(expand_list $hosts $(facet_host $facet) )
2813     done
2814
2815     echo $hosts
2816 }
2817
2818 _check_progs_installed () {
2819     local progs=$@
2820     local rc=0
2821
2822     for prog in $progs; do
2823         if ! [ "$(which $prog)"  -o  "${!prog}" ]; then
2824            echo $prog missing on $(hostname)
2825            rc=1
2826         fi
2827     done
2828     return $rc
2829 }
2830
2831 check_progs_installed () {
2832         local nodes=$1
2833         shift
2834
2835         do_rpc_nodes "$nodes" _check_progs_installed $@
2836 }
2837
2838 # recovery-scale functions
2839 node_var_name() {
2840     echo __$(echo $1 | tr '-' '_' | tr '.' '_')
2841 }
2842
2843 start_client_load() {
2844         local client=$1
2845         local load=$2
2846         local var=$(node_var_name $client)_load
2847         eval export ${var}=$load
2848
2849         do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
2850                         BREAK_ON_ERROR=$BREAK_ON_ERROR \
2851                         END_RUN_FILE=$END_RUN_FILE \
2852                         LOAD_PID_FILE=$LOAD_PID_FILE \
2853                         TESTLOG_PREFIX=$TESTLOG_PREFIX \
2854                         TESTNAME=$TESTNAME \
2855                         DBENCH_LIB=$DBENCH_LIB \
2856                         DBENCH_SRC=$DBENCH_SRC \
2857                         CLIENT_COUNT=$((CLIENTCOUNT - 1)) \
2858                         LFS=$LFS \
2859                         LCTL=$LCTL \
2860                         FSNAME=$FSNAME \
2861                         MPIRUN=$MPIRUN \
2862                         MPIRUN_OPTIONS=\\\"$MPIRUN_OPTIONS\\\" \
2863                         MACHINEFILE_OPTION=\\\"$MACHINEFILE_OPTION\\\" \
2864                         num_clients=$(get_node_count ${CLIENTS//,/ }) \
2865                         ior_THREADS=$ior_THREADS ior_iteration=$ior_iteration \
2866                         ior_blockSize=$ior_blockSize \
2867                         ior_blockUnit=$ior_blockUnit \
2868                         ior_xferSize=$ior_xferSize ior_type=$ior_type \
2869                         ior_DURATION=$ior_DURATION \
2870                         ior_stripe_params=\\\"$ior_stripe_params\\\" \
2871                         ior_custom_params=\\\"$ior_custom_param\\\" \
2872                         mpi_ior_custom_threads=$mpi_ior_custom_threads \
2873                         run_${load}.sh" &
2874         local ppid=$!
2875         log "Started client load: ${load} on $client"
2876
2877         # get the children process IDs
2878         local pids=$(ps --ppid $ppid -o pid= | xargs)
2879         CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $ppid $pids"
2880         return 0
2881 }
2882
2883 start_client_loads () {
2884         local -a clients=(${1//,/ })
2885         local numloads=${#CLIENT_LOADS[@]}
2886
2887         for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
2888                 local load=$((nodenum % numloads))
2889                 start_client_load ${clients[nodenum]} ${CLIENT_LOADS[load]}
2890         done
2891         # bug 22169: wait the background threads to start
2892         sleep 2
2893 }
2894
2895 # only for remote client
2896 check_client_load () {
2897         local client=$1
2898         local var=$(node_var_name $client)_load
2899         local testload=run_${!var}.sh
2900
2901         ps auxww | grep -v grep | grep $client | grep -q $testload || return 1
2902
2903         # bug 18914: try to connect several times not only when
2904         # check ps, but  while check_node_health also
2905
2906         local tries=3
2907         local RC=254
2908         while [ $RC = 254 -a $tries -gt 0 ]; do
2909                 let tries=$tries-1
2910                 # assume success
2911                 RC=0
2912                 if ! check_node_health $client; then
2913                         RC=${PIPESTATUS[0]}
2914                         if [ $RC -eq 254 ]; then
2915                                 # FIXME: not sure how long we shuold sleep here
2916                                 sleep 10
2917                                 continue
2918                         fi
2919                         echo "check node health failed: RC=$RC "
2920                         return $RC
2921                 fi
2922         done
2923         # We can continue try to connect if RC=254
2924         # Just print the warning about this
2925         if [ $RC = 254 ]; then
2926                 echo "got a return status of $RC from do_node while checking " \
2927                 "node health on $client"
2928         fi
2929
2930         # see if the load is still on the client
2931         tries=3
2932         RC=254
2933         while [ $RC = 254 -a $tries -gt 0 ]; do
2934                 let tries=$tries-1
2935                 # assume success
2936                 RC=0
2937                 if ! do_node $client \
2938                         "ps auxwww | grep -v grep | grep -q $testload"; then
2939                         RC=${PIPESTATUS[0]}
2940                         sleep 30
2941                 fi
2942         done
2943         if [ $RC = 254 ]; then
2944                 echo "got a return status of $RC from do_node while checking " \
2945                 "(node health and 'ps') the client load on $client"
2946                 # see if we can diagnose a bit why this is
2947         fi
2948
2949         return $RC
2950 }
2951 check_client_loads () {
2952    local clients=${1//,/ }
2953    local client=
2954    local rc=0
2955
2956    for client in $clients; do
2957       check_client_load $client
2958       rc=${PIPESTATUS[0]}
2959       if [ "$rc" != 0 ]; then
2960         log "Client load failed on node $client, rc=$rc"
2961         return $rc
2962       fi
2963    done
2964 }
2965
2966 restart_client_loads () {
2967     local clients=${1//,/ }
2968     local expectedfail=${2:-""}
2969     local client=
2970     local rc=0
2971
2972     for client in $clients; do
2973         check_client_load $client
2974         rc=${PIPESTATUS[0]}
2975         if [ "$rc" != 0 -a "$expectedfail" ]; then
2976             local var=$(node_var_name $client)_load
2977             start_client_load $client ${!var}
2978             echo "Restarted client load ${!var}: on $client. Checking ..."
2979             check_client_load $client
2980             rc=${PIPESTATUS[0]}
2981             if [ "$rc" != 0 ]; then
2982                 log "Client load failed to restart on node $client, rc=$rc"
2983                 # failure one client load means test fail
2984                 # we do not need to check other
2985                 return $rc
2986             fi
2987         else
2988             return $rc
2989         fi
2990     done
2991 }
2992
2993 # Start vmstat and save its process ID in a file.
2994 start_vmstat() {
2995     local nodes=$1
2996     local pid_file=$2
2997
2998     [ -z "$nodes" -o -z "$pid_file" ] && return 0
2999
3000     do_nodes $nodes \
3001         "vmstat 1 > $TESTLOG_PREFIX.$TESTNAME.vmstat.\\\$(hostname -s).log \
3002         2>/dev/null </dev/null & echo \\\$! > $pid_file"
3003 }
3004
3005 # Display the nodes on which client loads failed.
3006 print_end_run_file() {
3007     local file=$1
3008     local node
3009
3010     [ -s $file ] || return 0
3011
3012     echo "Found the END_RUN_FILE file: $file"
3013     cat $file
3014
3015     # A client load will stop if it finds the END_RUN_FILE file.
3016     # That does not mean the client load actually failed though.
3017     # The first node in END_RUN_FILE is the one we are interested in.
3018     read node < $file
3019
3020     if [ -n "$node" ]; then
3021         local var=$(node_var_name $node)_load
3022
3023         local prefix=$TESTLOG_PREFIX
3024         [ -n "$TESTNAME" ] && prefix=$prefix.$TESTNAME
3025         local stdout_log=$prefix.run_${!var}_stdout.$node.log
3026         local debug_log=$(echo $stdout_log | sed 's/\(.*\)stdout/\1debug/')
3027
3028         echo "Client load ${!var} failed on node $node:"
3029         echo "$stdout_log"
3030         echo "$debug_log"
3031     fi
3032 }
3033
3034 # Stop the process which had its PID saved in a file.
3035 stop_process() {
3036     local nodes=$1
3037     local pid_file=$2
3038
3039     [ -z "$nodes" -o -z "$pid_file" ] && return 0
3040
3041     do_nodes $nodes "test -f $pid_file &&
3042         { kill -s TERM \\\$(cat $pid_file); rm -f $pid_file; }" || true
3043 }
3044
3045 # Stop all client loads.
3046 stop_client_loads() {
3047     local nodes=${1:-$CLIENTS}
3048     local pid_file=$2
3049
3050     # stop the client loads
3051     stop_process $nodes $pid_file
3052
3053     # clean up the processes that started them
3054     [ -n "$CLIENT_LOAD_PIDS" ] && kill -9 $CLIENT_LOAD_PIDS 2>/dev/null || true
3055 }
3056 # End recovery-scale functions
3057
3058 ##
3059 # wait for a command to return the expected result
3060 #
3061 # This will run @check on @node repeatedly until the output matches @expect
3062 # based on the supplied condition, or until @max_wait seconds have elapsed,
3063 # whichever comes first.  @cond may be one of the normal bash operators,
3064 # "-gt", "-ge", "-eq", "-le", "-lt", "==", "!=", or "=~", and must be quoted
3065 # in the caller to avoid unintentional evaluation by the shell in the caller.
3066 #
3067 # If @max_wait is not specified, the condition will be checked for up to 90s.
3068 #
3069 # If --verbose is passed as the first argument, the result is printed on each
3070 # value change, otherwise it is only printed after every 10s interval.
3071 #
3072 # If --quiet is passed as the first/second argument, the do_node() command
3073 # will not print the remote command before executing it each time.
3074 #
3075 # Using wait_update_cond() or related helper function is preferable to adding
3076 # a "long enough" wait for some state to change in the background, since
3077 # "long enough" may be too short due to tunables, system config, or running in
3078 # a VM, and must by necessity wait too long for most cases or risk failure.
3079 #
3080 # usage: wait_update_cond [--verbose] [--quiet] node check cond expect [max_wait]
3081 wait_update_cond() {
3082         local verbose
3083         local quiet
3084
3085         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
3086         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
3087
3088         local node=$1
3089         local check="$2"
3090         local cond="$3"
3091         local expect="$4"
3092         local max_wait=${5:-90}
3093         local result
3094         local prev_result
3095         local waited=0
3096         local begin=$SECONDS
3097         local sleep=1
3098         local print=10
3099
3100         while (( $waited <= $max_wait )); do
3101                 result=$(do_node $quiet $node "$check")
3102
3103                 eval [[ "'$result'" $cond "'$expect'" ]]
3104                 if [[ $? == 0 ]]; then
3105                         [[ -z "$result" || $waited -le $sleep ]] ||
3106                                 echo "Updated after ${waited}s: want '$expect' got '$result'"
3107                         return 0
3108                 fi
3109                 if [[ -n "$verbose" && "$result" != "$prev_result" ]]; then
3110                         [[ -n "$prev_result" ]] &&
3111                                 echo "Changed after ${waited}s: from '$prev_result' to '$result'"
3112                         prev_result="$result"
3113                 fi
3114                 (( $waited % $print == 0 )) &&
3115                         echo "Waiting $((max_wait - waited))s for '$expect'"
3116                 sleep $sleep
3117                 waited=$((SECONDS - begin))
3118         done
3119         echo "Update not seen after ${max_wait}s: want '$expect' got '$result'"
3120         return 3
3121 }
3122
3123 # usage: wait_update [--verbose] [--quiet] node check expect [max_wait]
3124 wait_update() {
3125         local verbose
3126         local quiet
3127
3128         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
3129         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
3130
3131         local node="$1"
3132         local check="$2"
3133         local expect="$3"
3134         local max_wait=$4
3135
3136         wait_update_cond $verbose $quiet $node "$check" "==" "$expect" $max_wait
3137 }
3138
3139 # usage: wait_update_facet_cond [--verbose] facet check cond expect [max_wait]
3140 wait_update_facet_cond() {
3141         local verbose
3142         local quiet
3143
3144         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
3145         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
3146
3147         local node=$(facet_active_host $1)
3148         local check="$2"
3149         local cond="$3"
3150         local expect="$4"
3151         local max_wait=$5
3152
3153         wait_update_cond $verbose $quiet $node "$check" "$cond" "$expect" $max_wait
3154 }
3155
3156 # usage: wait_update_facet [--verbose] facet check expect [max_wait]
3157 wait_update_facet() {
3158         local verbose
3159         local quiet
3160
3161         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
3162         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
3163
3164         local node=$(facet_active_host $1)
3165         local check="$2"
3166         local expect="$3"
3167         local max_wait=$4
3168
3169         wait_update_cond $verbose $quiet $node "$check" "==" "$expect" $max_wait
3170 }
3171
3172 sync_all_data() {
3173         do_nodes $(comma_list $(mdts_nodes)) \
3174             "lctl set_param -n os[cd]*.*MDT*.force_sync=1"
3175         do_nodes $(comma_list $(osts_nodes)) \
3176             "lctl set_param -n osd*.*OS*.force_sync=1" 2>&1 |
3177                 grep -v 'Found no match'
3178 }
3179
3180 wait_zfs_commit() {
3181         local zfs_wait=${2:-5}
3182
3183         # the occupied disk space will be released
3184         # only after TXGs are committed
3185         if [[ $(facet_fstype $1) == zfs ]]; then
3186                 echo "sleep $zfs_wait for ZFS $(facet_fstype $1)"
3187                 sleep $zfs_wait
3188         fi
3189 }
3190
3191 fill_ost() {
3192         local filename=$1
3193         local ost_idx=$2
3194         local lwm=$3  #low watermark
3195         local size_mb #how many MB should we write to pass watermark
3196         local ost_name=$(ostname_from_index $ost_idx)
3197
3198         free_kb=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
3199         size_mb=0
3200         if (( $free_kb / 1024 > lwm )); then
3201                 size_mb=$((free_kb / 1024 - lwm))
3202         fi
3203         #If 10% of free space cross low watermark use it
3204         if (( $free_kb / 10240 > size_mb )); then
3205                 size_mb=$((free_kb / 10240))
3206         else
3207                 #At least we need to store 1.1 of difference between
3208                 #free space and low watermark
3209                 size_mb=$((size_mb + size_mb / 10))
3210         fi
3211         if (( lwm <= $free_kb / 1024 )) ||
3212            [ ! -f $DIR/${filename}.fill_ost$ost_idx ]; then
3213                 $LFS setstripe -i $ost_idx -c1 $DIR/${filename}.fill_ost$ost_idx
3214                 dd if=/dev/zero of=$DIR/${filename}.fill_ost$ost_idx bs=1M \
3215                         count=$size_mb oflag=append conv=notrunc
3216         fi
3217
3218         sleep_maxage
3219
3220         free_kb=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
3221         echo "OST still has $((free_kb / 1024)) MB free"
3222 }
3223
3224 # This checks only the primary MDS
3225 ost_watermarks_get() {
3226         local ost_idx=$1
3227         local ost_name=$(ostname_from_index $ost_idx)
3228         local mdtosc_proc=$(get_mdtosc_proc_path $SINGLEMDS $ost_name)
3229
3230         local hwm=$(do_facet $SINGLEMDS $LCTL get_param -n \
3231                         osp.$mdtosc_proc.reserved_mb_high)
3232         local lwm=$(do_facet $SINGLEMDS $LCTL get_param -n \
3233                         osp.$mdtosc_proc.reserved_mb_low)
3234
3235         echo "$lwm $hwm"
3236 }
3237
3238 # Note that we set watermarks on all MDSes (necessary for striped dirs)
3239 ost_watermarks_set() {
3240         local ost_idx=$1
3241         local lwm=$2
3242         local hwm=$3
3243         local ost_name=$(ostname_from_index $ost_idx)
3244         local facets=$(get_facets MDS)
3245
3246         do_nodes $(comma_list $(mdts_nodes)) $LCTL set_param -n \
3247                 osp.*$ost_name*.reserved_mb_low=$lwm \
3248                 osp.*$ost_name*.reserved_mb_high=$hwm > /dev/null
3249
3250         # sleep to ensure we see the change
3251         sleep_maxage
3252 }
3253
3254 ost_watermarks_set_low_space() {
3255         local ost_idx=$1
3256         local wms=$(ost_watermarks_get $ost_idx)
3257         local ost_name=$(ostname_from_index $ost_idx)
3258
3259         local old_lwm=$(echo $wms | awk '{ print $1 }')
3260         local old_hwm=$(echo $wms | awk '{ print $2 }')
3261
3262         local blocks=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
3263         # minimal extension size is 64M
3264         local new_lwm=50
3265         if (( $blocks / 1024 > 50 )); then
3266                 new_lwm=$((blocks / 1024 - 50))
3267         fi
3268         local new_hwm=$((new_lwm + 5))
3269
3270         ost_watermarks_set $ost_idx $new_lwm $new_hwm
3271         echo "watermarks: $old_lwm $old_hwm $new_lwm $new_hwm"
3272 }
3273
3274 # Set watermarks to ~current available space & then write data to fill it