Whamcloud - gitweb
LU-6635 lfsck: block replacing the OST-object for test
[fs/lustre-release.git] / lustre / tests / test-framework.sh
1 #!/bin/bash
2
3 trap 'print_summary && touch $TF_FAIL && \
4     echo "test-framework exiting on error"' ERR
5 set -e
6 #set -x
7
8 export LANG=en_US
9 export REFORMAT=${REFORMAT:-""}
10 export WRITECONF=${WRITECONF:-""}
11 export VERBOSE=${VERBOSE:-false}
12 export GSS=false
13 export GSS_KRB5=false
14 export GSS_PIPEFS=false
15 export IDENTITY_UPCALL=default
16 export QUOTA_AUTO=1
17 # specify environment variable containing batch job name for server statistics
18 export JOBID_VAR=${JOBID_VAR:-"procname_uid"}  # or "existing" or "disable"
19
20 # LOAD_LLOOP: LU-409: only load llite_lloop module if kernel < 2.6.32 or
21 #             LOAD_LLOOP is true. LOAD_LLOOP is false by default.
22 export LOAD_LLOOP=${LOAD_LLOOP:-false}
23
24 #export PDSH="pdsh -S -Rssh -w"
25 export MOUNT_CMD=${MOUNT_CMD:-"mount -t lustre"}
26 export UMOUNT=${UMOUNT:-"umount -d"}
27 # sles12 umount has a issue with -d option
28 [ -e /etc/SuSE-release ] && grep -w VERSION /etc/SuSE-release | grep -wq 12 && {
29         export UMOUNT="umount"
30 }
31
32 # function used by scripts run on remote nodes
33 LUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}
34 . $LUSTRE/tests/functions.sh
35 . $LUSTRE/tests/yaml.sh
36
37 export LD_LIBRARY_PATH=${LUSTRE}/utils:${LD_LIBRARY_PATH}
38
39 LUSTRE_TESTS_CFG_DIR=${LUSTRE_TESTS_CFG_DIR:-${LUSTRE}/tests/cfg}
40
41 EXCEPT_LIST_FILE=${EXCEPT_LIST_FILE:-${LUSTRE_TESTS_CFG_DIR}/tests-to-skip.sh}
42
43 if [ -f "$EXCEPT_LIST_FILE" ]; then
44     echo "Reading test skip list from $EXCEPT_LIST_FILE"
45     cat $EXCEPT_LIST_FILE
46     . $EXCEPT_LIST_FILE
47 fi
48
49 # check config files for options in decreasing order of preference
50 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/lustre.conf ] &&
51     MODPROBECONF=/etc/modprobe.d/lustre.conf
52 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/Lustre ] &&
53     MODPROBECONF=/etc/modprobe.d/Lustre
54 [ -z "$MODPROBECONF" -a -f /etc/modprobe.conf ] &&
55     MODPROBECONF=/etc/modprobe.conf
56
57 sanitize_parameters() {
58         for i in DIR DIR1 DIR2 MOUNT MOUNT1 MOUNT2
59         do
60                 local path=${!i}
61                 if [ -d "$path" ]; then
62                         eval export $i=$(echo $path | sed -r 's/\/+$//g')
63                 fi
64         done
65 }
66 assert_DIR () {
67         local failed=""
68         [[ $DIR/ = $MOUNT/* ]] ||
69                 { failed=1 && echo "DIR=$DIR not in $MOUNT. Aborting."; }
70         [[ $DIR1/ = $MOUNT1/* ]] ||
71                 { failed=1 && echo "DIR1=$DIR1 not in $MOUNT1. Aborting."; }
72         [[ $DIR2/ = $MOUNT2/* ]] ||
73                 { failed=1 && echo "DIR2=$DIR2 not in $MOUNT2. Aborting"; }
74
75         [ -n "$failed" ] && exit 99 || true
76 }
77
78 usage() {
79     echo "usage: $0 [-r] [-f cfgfile]"
80     echo "       -r: reformat"
81
82     exit
83 }
84
85 print_summary () {
86     trap 0
87         [ -z "$DEFAULT_SUITES"] && return 0
88     [ -n "$ONLY" ] && echo "WARNING: ONLY is set to $(echo $ONLY)"
89     local details
90     local form="%-13s %-17s %-9s %s %s\n"
91     printf "$form" "status" "script" "Total(sec)" "E(xcluded) S(low)"
92     echo "------------------------------------------------------------------------------------"
93     for O in $DEFAULT_SUITES; do
94         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
95         [ "${!O}" = "no" ] && continue || true
96         local o=$(echo $O  | tr "[:upper:]_" "[:lower:]-")
97         local log=${TMP}/${o}.log
98         if is_sanity_benchmark $o; then
99             log=${TMP}/sanity-benchmark.log
100         fi
101         local slow=
102         local skipped=
103         local total=
104         local status=Unfinished
105         if [ -f $log ]; then
106                 skipped=$(grep excluded $log | awk '{ printf " %s", $3 }' |
107                         sed 's/test_//g')
108                 slow=$(egrep "^PASS|^FAIL" $log | tr -d "("| sed s/s\)$//g |
109                         sort -nr -k 3  | head -n5 |  awk '{ print $2":"$3"s" }')
110                 total=$(grep duration $log | awk '{ print $2 }')
111                 if [ "${!O}" = "done" ]; then
112                         status=Done
113                 fi
114                 if $DDETAILS; then
115                         local durations=$(egrep "^PASS|^FAIL" $log |
116                                 tr -d "("| sed s/s\)$//g |
117                                 awk '{ print $2":"$3"|" }')
118                         details=$(printf "%s\n%s %s %s\n" "$details" \
119                                 "DDETAILS" "$O" "$(echo $durations)")
120                 fi
121         fi
122         printf "$form" $status "$O" "${total}" "E=$skipped"
123         printf "$form" "-" "-" "-" "S=$(echo $slow)"
124     done
125
126     for O in $DEFAULT_SUITES; do
127         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
128         if [ "${!O}" = "no" ]; then
129             printf "$form" "Skipped" "$O" ""
130         fi
131     done
132
133     # print the detailed tests durations if DDETAILS=true
134     if $DDETAILS; then
135         echo "$details"
136     fi
137 }
138
139 init_test_env() {
140         export LUSTRE=$(absolute_path $LUSTRE)
141         export TESTSUITE=$(basename $0 .sh)
142         export TEST_FAILED=false
143         export FAIL_ON_SKIP_ENV=${FAIL_ON_SKIP_ENV:-false}
144         export RPC_MODE=${RPC_MODE:-false}
145         export DO_CLEANUP=${DO_CLEANUP:-true}
146
147     export MKE2FS=$MKE2FS
148     if [ -z "$MKE2FS" ]; then
149         if which mkfs.ldiskfs >/dev/null 2>&1; then
150             export MKE2FS=mkfs.ldiskfs
151         else
152             export MKE2FS=mke2fs
153         fi
154     fi
155
156     export DEBUGFS=$DEBUGFS
157     if [ -z "$DEBUGFS" ]; then
158         if which debugfs.ldiskfs >/dev/null 2>&1; then
159             export DEBUGFS=debugfs.ldiskfs
160         else
161             export DEBUGFS=debugfs
162         fi
163     fi
164
165     export TUNE2FS=$TUNE2FS
166     if [ -z "$TUNE2FS" ]; then
167         if which tunefs.ldiskfs >/dev/null 2>&1; then
168             export TUNE2FS=tunefs.ldiskfs
169         else
170             export TUNE2FS=tune2fs
171         fi
172     fi
173
174     export E2LABEL=$E2LABEL
175     if [ -z "$E2LABEL" ]; then
176         if which label.ldiskfs >/dev/null 2>&1; then
177             export E2LABEL=label.ldiskfs
178         else
179             export E2LABEL=e2label
180         fi
181     fi
182
183     export DUMPE2FS=$DUMPE2FS
184     if [ -z "$DUMPE2FS" ]; then
185         if which dumpfs.ldiskfs >/dev/null 2>&1; then
186             export DUMPE2FS=dumpfs.ldiskfs
187         else
188             export DUMPE2FS=dumpe2fs
189         fi
190     fi
191
192     export E2FSCK=$E2FSCK
193     if [ -z "$E2FSCK" ]; then
194         if which fsck.ldiskfs >/dev/null 2>&1; then
195             export E2FSCK=fsck.ldiskfs
196         else
197             export E2FSCK=e2fsck
198         fi
199     fi
200
201         export RESIZE2FS=$RESIZE2FS
202         if [ -z "$RESIZE2FS" ]; then
203                 if which resizefs.ldiskfs >/dev/null 2>&1; then
204                         export RESIZE2FS=resizefs.ldiskfs
205                 else
206                         export RESIZE2FS=resize2fs
207                 fi
208         fi
209
210         export LFSCK_ALWAYS=${LFSCK_ALWAYS:-"no"} # check fs after test suite
211         export FSCK_MAX_ERR=4   # File system errors left uncorrected
212
213         export ZFS=${ZFS:-zfs}
214         export ZPOOL=${ZPOOL:-zpool}
215         export ZDB=${ZDB:-zdb}
216         export PARTPROBE=${PARTPROBE:-partprobe}
217
218     #[ -d /r ] && export ROOT=${ROOT:-/r}
219     export TMP=${TMP:-$ROOT/tmp}
220     export TESTSUITELOG=${TMP}/${TESTSUITE}.log
221     export LOGDIR=${LOGDIR:-${TMP}/test_logs/$(date +%s)}
222     export TESTLOG_PREFIX=$LOGDIR/$TESTSUITE
223
224     export HOSTNAME=${HOSTNAME:-$(hostname -s)}
225     if ! echo $PATH | grep -q $LUSTRE/utils; then
226         export PATH=$LUSTRE/utils:$PATH
227     fi
228     if ! echo $PATH | grep -q $LUSTRE/utils/gss; then
229         export PATH=$LUSTRE/utils/gss:$PATH
230     fi
231     if ! echo $PATH | grep -q $LUSTRE/tests; then
232         export PATH=$LUSTRE/tests:$PATH
233     fi
234     if ! echo $PATH | grep -q $LUSTRE/../lustre-iokit/sgpdd-survey; then
235         export PATH=$LUSTRE/../lustre-iokit/sgpdd-survey:$PATH
236     fi
237     export LST=${LST:-"$LUSTRE/../lnet/utils/lst"}
238     [ ! -f "$LST" ] && export LST=$(which lst)
239     export SGPDDSURVEY=${SGPDDSURVEY:-"$LUSTRE/../lustre-iokit/sgpdd-survey/sgpdd-survey")}
240     [ ! -f "$SGPDDSURVEY" ] && export SGPDDSURVEY=$(which sgpdd-survey)
241         export MCREATE=${MCREATE:-mcreate}
242     # Ubuntu, at least, has a truncate command in /usr/bin
243     # so fully path our truncate command.
244     export TRUNCATE=${TRUNCATE:-$LUSTRE/tests/truncate}
245         export FSX=${FSX:-$LUSTRE/tests/fsx}
246     export MDSRATE=${MDSRATE:-"$LUSTRE/tests/mpi/mdsrate"}
247     [ ! -f "$MDSRATE" ] && export MDSRATE=$(which mdsrate 2> /dev/null)
248     if ! echo $PATH | grep -q $LUSTRE/tests/racer; then
249         export PATH=$LUSTRE/tests/racer:$PATH:
250     fi
251     if ! echo $PATH | grep -q $LUSTRE/tests/mpi; then
252         export PATH=$LUSTRE/tests/mpi:$PATH
253     fi
254     export RSYNC_RSH=${RSYNC_RSH:-rsh}
255
256     export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
257     [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
258     export LFS=${LFS:-"$LUSTRE/utils/lfs"}
259     [ ! -f "$LFS" ] && export LFS=$(which lfs)
260     SETSTRIPE=${SETSTRIPE:-"$LFS setstripe"}
261     GETSTRIPE=${GETSTRIPE:-"$LFS getstripe"}
262
263     export L_GETIDENTITY=${L_GETIDENTITY:-"$LUSTRE/utils/l_getidentity"}
264     if [ ! -f "$L_GETIDENTITY" ]; then
265         if `which l_getidentity > /dev/null 2>&1`; then
266             export L_GETIDENTITY=$(which l_getidentity)
267         else
268             export L_GETIDENTITY=NONE
269         fi
270     fi
271     export LL_DECODE_FILTER_FID=${LL_DECODE_FILTER_FID:-"$LUSTRE/utils/ll_decode_filter_fid"}
272     [ ! -f "$LL_DECODE_FILTER_FID" ] && export LL_DECODE_FILTER_FID="ll_decode_filter_fid"
273     export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
274     [ ! -f "$MKFS" ] && export MKFS="mkfs.lustre"
275     export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
276     [ ! -f "$TUNEFS" ] && export TUNEFS="tunefs.lustre"
277     export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
278     export LUSTRE_RMMOD=${LUSTRE_RMMOD:-$LUSTRE/scripts/lustre_rmmod}
279     [ ! -f "$LUSTRE_RMMOD" ] &&
280         export LUSTRE_RMMOD=$(which lustre_rmmod 2> /dev/null)
281     export LFS_MIGRATE=${LFS_MIGRATE:-$LUSTRE/scripts/lfs_migrate}
282     [ ! -f "$LFS_MIGRATE" ] &&
283         export LFS_MIGRATE=$(which lfs_migrate 2> /dev/null)
284     export LR_READER=${LR_READER:-"$LUSTRE/utils/lr_reader"}
285     [ ! -f "$LR_READER" ] && export LR_READER=$(which lr_reader 2> /dev/null)
286     [ -z "$LR_READER" ] && export LR_READER="/usr/sbin/lr_reader"
287     export NAME=${NAME:-local}
288     export LGSSD=${LGSSD:-"$LUSTRE/utils/gss/lgssd"}
289     [ "$GSS_PIPEFS" = "true" ] && [ ! -f "$LGSSD" ] && \
290         export LGSSD=$(which lgssd)
291     export LSVCGSSD=${LSVCGSSD:-"$LUSTRE/utils/gss/lsvcgssd"}
292     [ ! -f "$LSVCGSSD" ] && export LSVCGSSD=$(which lsvcgssd 2> /dev/null)
293     export KRB5DIR=${KRB5DIR:-"/usr/kerberos"}
294     export DIR2
295     export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
296     export AT_MAX_PATH
297     export LDEV=${LDEV:-"$LUSTRE/scripts/ldev"}
298     [ ! -f "$LDEV" ] && export LDEV=$(which ldev 2> /dev/null)
299
300     if [ "$ACCEPTOR_PORT" ]; then
301         export PORT_OPT="--port $ACCEPTOR_PORT"
302     fi
303
304     case "x$SEC" in
305         xkrb5*)
306             echo "Using GSS/krb5 ptlrpc security flavor"
307             which lgss_keyring > /dev/null 2>&1 || \
308                 error_exit "built with gss disabled! SEC=$SEC"
309             GSS=true
310             GSS_KRB5=true
311             ;;
312     esac
313
314     case "x$IDUP" in
315         xtrue)
316             IDENTITY_UPCALL=true
317             ;;
318         xfalse)
319             IDENTITY_UPCALL=false
320             ;;
321     esac
322
323     export LOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}
324
325     # Paths on remote nodes, if different
326     export RLUSTRE=${RLUSTRE:-$LUSTRE}
327     export RPWD=${RPWD:-$PWD}
328     export I_MOUNTED=${I_MOUNTED:-"no"}
329         if [ ! -f /lib/modules/$(uname -r)/kernel/fs/lustre/mdt.ko -a \
330              ! -f /lib/modules/$(uname -r)/updates/kernel/fs/lustre/mdt.ko -a \
331              ! -f /lib/modules/$(uname -r)/extra/kernel/fs/lustre/mdt.ko -a \
332              ! -f $LUSTRE/mdt/mdt.ko ]; then
333             export CLIENTMODSONLY=yes
334         fi
335
336         export SHUTDOWN_ATTEMPTS=${SHUTDOWN_ATTEMPTS:-3}
337         export OSD_TRACK_DECLARES_LBUG=${OSD_TRACK_DECLARES_LBUG:-"yes"}
338
339         # command line
340
341         while getopts "rvwf:" opt $*; do
342                 case $opt in
343                         f) CONFIG=$OPTARG;;
344                         r) REFORMAT=yes;;
345                         v) VERBOSE=true;;
346                         w) WRITECONF=writeconf;;
347                         \?) usage;;
348                 esac
349         done
350
351         shift $((OPTIND - 1))
352         ONLY=${ONLY:-$*}
353
354         # print the durations of each test if "true"
355         DDETAILS=${DDETAILS:-false}
356         [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
357         if ! $RPC_MODE; then
358                 rm -f $TMP/*active
359         fi
360
361         export TF_FAIL=${TF_FAIL:-$TMP/tf.fail}
362 }
363
364 check_cpt_number() {
365         local facet=$1
366         local ncpts
367
368         ncpts=$(do_facet $facet "lctl get_param -n " \
369                 "cpu_partition_table 2>/dev/null| wc -l" || echo 1)
370
371         if [ $ncpts -eq 0 ]; then
372                 echo "1"
373         else
374                 echo $ncpts
375         fi
376 }
377
378 # Return a numeric version code based on a version string.  The version
379 # code is useful for comparison two version strings to see which is newer.
380 version_code() {
381         # split arguments like "1.8.6-wc3" into "1", "8", "6", "wc3"
382         eval set -- $(tr "[:punct:]" " " <<< $*)
383
384         echo -n "$((($1 << 16) | ($2 << 8) | $3))"
385 }
386
387 export LINUX_VERSION=$(uname -r | sed -e "s/\([0-9]*\.[0-9]*\.[0-9]*\).*/\1/")
388 export LINUX_VERSION_CODE=$(version_code ${LINUX_VERSION//\./ })
389
390 # Report the Lustre build version string (e.g. 1.8.7.3 or 2.4.1).
391 #
392 # usage: lustre_build_version
393 #
394 # All Lustre versions support "lctl get_param" to report the version of the
395 # code running in the kernel (what our tests are interested in), but it
396 # doesn't work without modules loaded.  If that fails, use "lctl version"
397 # instead, which is easy to parse and works without the kernel modules,
398 # but was only added in 2.6.50.  If that also fails, fall back to calling
399 # "lctl lustre_build_version" which prints either (or both) the userspace
400 # and kernel build versions, but is deprecated and should eventually be
401 # removed.
402 #
403 # output: prints version string to stdout in dotted-decimal format
404 lustre_build_version() {
405         local facet=${1:-client}
406
407         # lustre: 2.8.52
408         local VER=$(do_facet $facet $LCTL get_param -n version 2> /dev/null |
409                     awk '/lustre: / { print $2 }')
410         # lctl 2.6.50
411         [ -z "$VER" ] && VER=$(do_facet $facet $LCTL --version 2>/dev/null |
412                                awk '{ print $2 }')
413         # Lustre version: 2.5.3-gfcfd782-CHANGED-2.6.32.26-175.fc12.x86_64
414         # lctl   version: 2.5.3-gfcfd782-CHANGED-2.6.32.26-175.fc12.x86_64
415         [ -z "$VER" ] && VER=$(do_facet $facet $LCTL lustre_build_version |
416                                awk '/version:/ { print $3; exit; }')
417         sed -e 's/^v//' -e 's/-.*//' -e 's/_/./g' <<<$VER
418 }
419
420 # Report the Lustre numeric build version code for the supplied facet.
421 lustre_version_code() {
422         version_code $(lustre_build_version $1)
423 }
424
425 module_loaded () {
426         /sbin/lsmod | grep -q "^\<$1\>"
427 }
428
429 # Load a module on the system where this is running.
430 #
431 # usage: load_module module_name [module arguments for insmod/modprobe]
432 #
433 # If module arguments are not given but MODOPTS_<MODULE> is set, then its value
434 # will be used as the arguments.  Otherwise arguments will be obtained from
435 # /etc/modprobe.conf, from /etc/modprobe.d/Lustre, or else none will be used.
436 #
437 load_module() {
438     local optvar
439     EXT=".ko"
440     module=$1
441     shift
442     BASE=$(basename $module $EXT)
443
444     module_loaded ${BASE} && return
445
446     # If no module arguments were passed, get them from $MODOPTS_<MODULE>,
447     # else from modprobe.conf
448     if [ $# -eq 0 ]; then
449         # $MODOPTS_<MODULE>; we could use associative arrays, but that's not in
450         # Bash until 4.x, so we resort to eval.
451         optvar="MODOPTS_$(basename $module | tr a-z A-Z)"
452         eval set -- \$$optvar
453         if [ $# -eq 0 -a -n "$MODPROBECONF" ]; then
454                 # Nothing in $MODOPTS_<MODULE>; try modprobe.conf
455                 local opt
456                 opt=$(awk -v var="^options $BASE" '$0 ~ var \
457                         {gsub("'"options $BASE"'",""); print}' $MODPROBECONF)
458                 set -- $(echo -n $opt)
459
460                 # Ensure we have accept=all for lnet
461                 if [ $(basename $module) = lnet ]; then
462                         # OK, this is a bit wordy...
463                         local arg accept_all_present=false
464
465                         for arg in "$@"; do
466                                 [ "$arg" = accept=all ] && \
467                                         accept_all_present=true
468                         done
469                         $accept_all_present || set -- "$@" accept=all
470                 fi
471                 export $optvar="$*"
472         fi
473     fi
474
475     [ $# -gt 0 ] && echo "${module} options: '$*'"
476
477         # Note that insmod will ignore anything in modprobe.conf, which is why
478         # we're passing options on the command-line.
479         if [[ "$BASE" == "lnet_selftest" ]] &&
480                 [[ -f ${LUSTRE}/../lnet/selftest/${module}${EXT} ]]; then
481                 insmod ${LUSTRE}/../lnet/selftest/${module}${EXT}
482         elif [[ -f ${LUSTRE}/${module}${EXT} ]]; then
483                 [[ "$BASE" != "ptlrpc_gss" ]] || modprobe sunrpc
484                 insmod ${LUSTRE}/${module}${EXT} "$@"
485         else
486                 # must be testing a "make install" or "rpm" installation
487                 # note failed to load ptlrpc_gss is considered not fatal
488                 if [[ "$BASE" == "ptlrpc_gss" ]]; then
489                         modprobe $BASE "$@" 2>/dev/null ||
490                                 echo "gss/krb5 is not supported"
491                 else
492                         modprobe $BASE "$@"
493                 fi
494         fi
495 }
496
497 llite_lloop_enabled() {
498     local n1=$(uname -r | cut -d. -f1)
499     local n2=$(uname -r | cut -d. -f2)
500     local n3=$(uname -r | cut -d- -f1 | cut -d. -f3)
501
502     # load the llite_lloop module for < 2.6.32 kernels
503     if [[ $n1 -lt 2 ]] || [[ $n1 -eq 2 && $n2 -lt 6 ]] || \
504        [[ $n1 -eq 2 && $n2 -eq 6 && $n3 -lt 32 ]] || \
505         $LOAD_LLOOP; then
506         return 0
507     fi
508     return 1
509 }
510
511 load_modules_local() {
512         if [ -n "$MODPROBE" ]; then
513                 # use modprobe
514                 echo "Using modprobe to load modules"
515                 return 0
516         fi
517
518         echo Loading modules from $LUSTRE
519
520         local ncpus
521
522         if [ -f /sys/devices/system/cpu/online ]; then
523                 ncpus=$(($(cut -d "-" -f 2 /sys/devices/system/cpu/online) + 1))
524                 echo "detected $ncpus online CPUs by sysfs"
525         else
526                 ncpus=$(getconf _NPROCESSORS_CONF 2>/dev/null)
527                 local rc=$?
528                 if [ $rc -eq 0 ]; then
529                         echo "detected $ncpus online CPUs by getconf"
530                 else
531                         echo "Can't detect number of CPUs"
532                         ncpus=1
533                 fi
534         fi
535
536         # if there is only one CPU core, libcfs can only create one partition
537         # if there is more than 4 CPU cores, libcfs should create multiple CPU
538         # partitions. So we just force libcfs to create 2 partitions for
539         # system with 2 or 4 cores
540         if [ $ncpus -le 4 ] && [ $ncpus -gt 1 ]; then
541                 # force to enable multiple CPU partitions
542                 echo "Force libcfs to create 2 CPU partitions"
543                 MODOPTS_LIBCFS="cpu_npartitions=2 $MODOPTS_LIBCFS"
544         else
545                 echo "libcfs will create CPU partition based on online CPUs"
546         fi
547
548         load_module ../libcfs/libcfs/libcfs
549
550     [ "$PTLDEBUG" ] && lctl set_param debug="$PTLDEBUG"
551     [ "$SUBSYSTEM" ] && lctl set_param subsystem_debug="${SUBSYSTEM# }"
552     load_module ../lnet/lnet/lnet
553         case $NETTYPE in
554         o2ib)
555                 LNETLND="o2iblnd/ko2iblnd"
556                 ;;
557         *)
558                 ;;
559         esac
560     LNETLND=${LNETLND:-"socklnd/ksocklnd"}
561     load_module ../lnet/klnds/$LNETLND
562     load_module obdclass/obdclass
563     load_module ptlrpc/ptlrpc
564     load_module ptlrpc/gss/ptlrpc_gss
565     load_module fld/fld
566     load_module fid/fid
567     load_module lmv/lmv
568     load_module mdc/mdc
569     load_module osc/osc
570     load_module lov/lov
571     load_module mgc/mgc
572     load_module obdecho/obdecho
573         if ! client_only; then
574                 SYMLIST=/proc/kallsyms
575                 grep -q crc16 $SYMLIST ||
576                         { modprobe crc16 2>/dev/null || true; }
577                 grep -q -w jbd2 $SYMLIST ||
578                         { modprobe jbd2 2>/dev/null || true; }
579                 load_module lfsck/lfsck
580                 [ "$LQUOTA" != "no" ] &&
581                         load_module quota/lquota $LQUOTAOPTS
582                 if [[ $(node_fstypes $HOSTNAME) == *zfs* ]]; then
583                         modprobe zfs
584                         load_module osd-zfs/osd_zfs
585                 fi
586                 if [[ $(node_fstypes $HOSTNAME) == *ldiskfs* ]]; then
587                         grep -q exportfs_decode_fh $SYMLIST ||
588                                 { modprobe exportfs 2> /dev/null || true; }
589                         grep -q -w mbcache $SYMLIST ||
590                                 { modprobe mbcache 2>/dev/null || true; }
591                         load_module ../ldiskfs/ldiskfs
592                         load_module osd-ldiskfs/osd_ldiskfs
593                 fi
594                 load_module mgs/mgs
595                 load_module mdd/mdd
596                 load_module mdt/mdt
597                 load_module ost/ost
598                 load_module lod/lod
599                 load_module osp/osp
600                 load_module ofd/ofd
601                 load_module osp/osp
602         fi
603
604         load_module llite/lustre
605         llite_lloop_enabled && load_module llite/llite_lloop
606         [ -d /r ] && OGDB=${OGDB:-"/r/tmp"}
607         OGDB=${OGDB:-$TMP}
608         rm -f $OGDB/ogdb-$HOSTNAME
609         $LCTL modules > $OGDB/ogdb-$HOSTNAME
610
611         # 'mount' doesn't look in $PATH, just sbin
612         local mount_lustre=$LUSTRE/utils/mount.lustre
613         if [ -f $mount_lustre ]; then
614                 local sbin_mount=$(readlink -f /sbin)/mount.lustre
615                 if grep -qw "$sbin_mount" /proc/mounts; then
616                         cmp -s $mount_lustre $sbin_mount || umount $sbin_mount
617                 fi
618                 if ! grep -qw "$sbin_mount" /proc/mounts; then
619                         [ ! -f "$sbin_mount" ] && touch "$sbin_mount"
620                         if [ ! -s "$sbin_mount" -a -w "$sbin_mount" ]; then
621                                 cat <<- EOF > "$sbin_mount"
622                                 #!/bin/sh
623                                 #STUB MARK
624                                 echo "This $sbin_mount just a mountpoint." 1>&2
625                                 echo "It is never supposed to be run." 1>&2
626                                 logger -p emerg -- "using stub $sbin_mount $@"
627                                 exit 1
628                                 EOF
629                                 chmod a+x $sbin_mount
630                         fi
631                         mount --bind $mount_lustre $sbin_mount ||
632                                 error "can't bind $mount_lustre to $sbin_mount"
633                 fi
634         fi
635 }
636
637 load_modules () {
638         load_modules_local
639         # bug 19124
640         # load modules on remote nodes optionally
641         # lustre-tests have to be installed on these nodes
642         if $LOAD_MODULES_REMOTE; then
643                 local list=$(comma_list $(remote_nodes_list))
644                 if [ -n "$list" ]; then
645                         echo "loading modules on: '$list'"
646                         do_rpc_nodes "$list" load_modules_local
647                 fi
648         fi
649 }
650
651 check_mem_leak () {
652     LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
653     LEAK_PORTALS=$(dmesg | tail -n 20 | grep "Portals memory leaked" || true)
654     if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
655         echo "$LEAK_LUSTRE" 1>&2
656         echo "$LEAK_PORTALS" 1>&2
657         mv $TMP/debug $TMP/debug-leak.`date +%s` || true
658         echo "Memory leaks detected"
659         [ -n "$IGNORE_LEAK" ] && { echo "ignoring leaks" && return 0; } || true
660         return 1
661     fi
662 }
663
664 unload_modules() {
665         wait_exit_ST client # bug 12845
666
667         $LUSTRE_RMMOD ldiskfs || return 2
668
669         if $LOAD_MODULES_REMOTE; then
670                 local list=$(comma_list $(remote_nodes_list))
671                 if [ -n "$list" ]; then
672                         echo "unloading modules on: '$list'"
673                         do_rpc_nodes "$list" $LUSTRE_RMMOD ldiskfs
674                         do_rpc_nodes "$list" check_mem_leak
675                 fi
676         fi
677
678         local sbin_mount=$(readlink -f /sbin)/mount.lustre
679         if grep -qe "$sbin_mount " /proc/mounts; then
680                 umount $sbin_mount || true
681                 [ -s $sbin_mount ] && ! grep -q "STUB MARK" $sbin_mount ||
682                         rm -f $sbin_mount
683         fi
684
685         check_mem_leak || return 254
686
687         echo "modules unloaded."
688         return 0
689 }
690
691 fs_log_size() {
692         local facet=${1:-$SINGLEMDS}
693         local fstype=$(facet_fstype $facet)
694         local size=0
695         case $fstype in
696                 ldiskfs) size=50;; # largest seen is 44, leave some headroom
697                 zfs)     size=400;; # largest seen is 384
698         esac
699
700         echo -n $size
701 }
702
703 fs_inode_ksize() {
704         local facet=${1:-$SINGLEMDS}
705         local fstype=$(facet_fstype $facet)
706         local size=0
707         case $fstype in
708                 ldiskfs) size=4;;  # ~4KB per inode
709                 zfs)     size=11;; # 10 to 11KB per inode
710         esac
711
712         echo -n $size
713 }
714
715 check_gss_daemon_nodes() {
716     local list=$1
717     dname=$2
718
719     do_nodesv $list "num=\\\$(ps -o cmd -C $dname | grep $dname | wc -l);
720 if [ \\\"\\\$num\\\" -ne 1 ]; then
721     echo \\\$num instance of $dname;
722     exit 1;
723 fi; "
724 }
725
726 check_gss_daemon_facet() {
727     facet=$1
728     dname=$2
729
730     num=`do_facet $facet ps -o cmd -C $dname | grep $dname | wc -l`
731     if [ $num -ne 1 ]; then
732         echo "$num instance of $dname on $facet"
733         return 1
734     fi
735     return 0
736 }
737
738 send_sigint() {
739     local list=$1
740     shift
741     echo Stopping $@ on $list
742     do_nodes $list "killall -2 $@ 2>/dev/null || true"
743 }
744
745 # start gss daemons on all nodes, or
746 # "daemon" on "list" if set
747 start_gss_daemons() {
748     local list=$1
749     local daemon=$2
750
751     if [ "$list" ] && [ "$daemon" ] ; then
752         echo "Starting gss daemon on nodes: $list"
753         do_nodes $list "$daemon" || return 8
754         return 0
755     fi
756
757     local list=$(comma_list $(mdts_nodes))
758     echo "Starting gss daemon on mds: $list"
759     do_nodes $list "$LSVCGSSD -v" || return 1
760     if $GSS_PIPEFS; then
761         do_nodes $list "$LGSSD -v" || return 2
762     fi
763
764     list=$(comma_list $(osts_nodes))
765     echo "Starting gss daemon on ost: $list"
766     do_nodes $list "$LSVCGSSD -v" || return 3
767     # starting on clients
768
769     local clients=${CLIENTS:-`hostname`}
770     if $GSS_PIPEFS; then
771         echo "Starting $LGSSD on clients $clients "
772         do_nodes $clients  "$LGSSD -v" || return 4
773     fi
774
775     # wait daemons entering "stable" status
776     sleep 5
777
778     #
779     # check daemons are running
780     #
781     list=$(comma_list $(mdts_nodes) $(osts_nodes))
782     check_gss_daemon_nodes $list lsvcgssd || return 5
783     if $GSS_PIPEFS; then
784         list=$(comma_list $(mdts_nodes))
785         check_gss_daemon_nodes $list lgssd || return 6
786     fi
787     if $GSS_PIPEFS; then
788         check_gss_daemon_nodes $clients lgssd || return 7
789     fi
790 }
791
792 stop_gss_daemons() {
793     local list=$(comma_list $(mdts_nodes))
794
795     send_sigint $list lsvcgssd lgssd
796
797     list=$(comma_list $(osts_nodes))
798     send_sigint $list lsvcgssd
799
800     list=${CLIENTS:-`hostname`}
801     send_sigint $list lgssd
802 }
803
804 init_gss() {
805     if $GSS; then
806         if ! module_loaded ptlrpc_gss; then
807             load_module ptlrpc/gss/ptlrpc_gss
808             module_loaded ptlrpc_gss ||
809                 error_exit "init_gss : GSS=$GSS, but gss/krb5 is not supported!"
810         fi
811         if $GSS_KRB5; then
812                 start_gss_daemons || error_exit "start gss daemon failed! rc=$?"
813         fi
814
815         if [ -n "$LGSS_KEYRING_DEBUG" ]; then
816                 lctl set_param -n \
817                     sptlrpc.gss.lgss_keyring.debug_level=$LGSS_KEYRING_DEBUG
818         fi
819     fi
820 }
821
822 cleanup_gss() {
823     if $GSS; then
824         stop_gss_daemons
825         # maybe cleanup credential cache?
826     fi
827 }
828
829 facet_svc() {
830         local facet=$1
831         local var=${facet}_svc
832
833         echo -n ${!var}
834 }
835
836 facet_type() {
837         local facet=$1
838
839         echo -n $facet | sed -e 's/^fs[0-9]\+//' -e 's/[0-9_]\+//' |
840                 tr '[:lower:]' '[:upper:]'
841 }
842
843 facet_number() {
844         local facet=$1
845
846         if [ $facet == mgs ] || [ $facet == client ]; then
847                 return 1
848         fi
849
850         echo -n $facet | sed -e 's/^fs[0-9]\+//' | sed -e 's/^[a-z]\+//'
851 }
852
853 facet_fstype() {
854         local facet=$1
855         local var
856
857         var=${facet}_FSTYPE
858         if [ -n "${!var}" ]; then
859                 echo -n ${!var}
860                 return
861         fi
862
863         var=$(facet_type $facet)FSTYPE
864         if [ -n "${!var}" ]; then
865                 echo -n ${!var}
866                 return
867         fi
868
869         if [ -n "$FSTYPE" ]; then
870                 echo -n $FSTYPE
871                 return
872         fi
873
874         if [[ $facet == mgs ]] && combined_mgs_mds; then
875                 facet_fstype mds1
876                 return
877         fi
878
879         return 1
880 }
881
882 node_fstypes() {
883         local node=$1
884         local fstypes
885         local fstype
886         local facets=$(get_facets)
887         local facet
888
889         for facet in ${facets//,/ }; do
890                 if [ $node == $(facet_host $facet) ] ||
891                    [ $node == "$(facet_failover_host $facet)" ]; then
892                         fstype=$(facet_fstype $facet)
893                         if [[ $fstypes != *$fstype* ]]; then
894                                 fstypes+="${fstypes:+,}$fstype"
895                         fi
896                 fi
897         done
898         echo -n $fstypes
899 }
900
901 facet_index() {
902         local facet=$1
903         local num=$(facet_number $facet)
904         local index
905
906         if [[ $(facet_type $facet) = OST ]]; then
907                 index=OSTINDEX${num}
908                 if [[ -n "${!index}" ]]; then
909                         echo -n ${!index}
910                         return
911                 fi
912
913                 index=${OST_INDICES[num - 1]}
914         fi
915
916         [[ -n "$index" ]] || index=$((num - 1))
917         echo -n $index
918 }
919
920 devicelabel() {
921         local facet=$1
922         local dev=$2
923         local label
924         local fstype=$(facet_fstype $facet)
925
926         case $fstype in
927         ldiskfs)
928                 label=$(do_facet ${facet} "$E2LABEL ${dev} 2>/dev/null");;
929         zfs)
930                 label=$(do_facet ${facet} "$ZFS get -H -o value lustre:svname \
931                                            ${dev} 2>/dev/null");;
932         *)
933                 error "unknown fstype!";;
934         esac
935
936         echo -n $label
937 }
938
939 mdsdevlabel() {
940         local num=$1
941         local device=$(mdsdevname $num)
942         local label=$(devicelabel mds$num ${device} | grep -v "CMD: ")
943         echo -n $label
944 }
945
946 ostdevlabel() {
947         local num=$1
948         local device=$(ostdevname $num)
949         local label=$(devicelabel ost$num ${device} | grep -v "CMD: ")
950         echo -n $label
951 }
952
953 #
954 # Get the device of a facet.
955 #
956 facet_device() {
957         local facet=$1
958         local device
959
960         case $facet in
961                 mgs) device=$(mgsdevname) ;;
962                 mds*) device=$(mdsdevname $(facet_number $facet)) ;;
963                 ost*) device=$(ostdevname $(facet_number $facet)) ;;
964                 fs2mds) device=$(mdsdevname 1_2) ;;
965                 fs2ost) device=$(ostdevname 1_2) ;;
966                 fs3ost) device=$(ostdevname 2_2) ;;
967                 *) ;;
968         esac
969
970         echo -n $device
971 }
972
973 #
974 # Get the virtual device of a facet.
975 #
976 facet_vdevice() {
977         local facet=$1
978         local device
979
980         case $facet in
981                 mgs) device=$(mgsvdevname) ;;
982                 mds*) device=$(mdsvdevname $(facet_number $facet)) ;;
983                 ost*) device=$(ostvdevname $(facet_number $facet)) ;;
984                 fs2mds) device=$(mdsvdevname 1_2) ;;
985                 fs2ost) device=$(ostvdevname 1_2) ;;
986                 fs3ost) device=$(ostvdevname 2_2) ;;
987                 *) ;;
988         esac
989
990         echo -n $device
991 }
992
993 running_in_vm() {
994         local virt=$(virt-what 2> /dev/null)
995
996         [ $? -eq 0 ] && [ -n "$virt" ] && { echo $virt; return; }
997
998         virt=$(dmidecode -s system-product-name | awk '{print $1}')
999
1000         case $virt in
1001                 VMware|KVM|VirtualBox|Parallels) echo ${virt,,} ;;
1002                 *) ;;
1003         esac
1004 }
1005
1006 #
1007 # Re-read the partition table on failover partner host.
1008 # After a ZFS storage pool is created on a shared device, the partition table
1009 # on the device may change. However, the operating system on the failover
1010 # host may not notice the change automatically. Without the up-to-date partition
1011 # block devices, 'zpool import ..' cannot find the labels, whose positions are
1012 # relative to partition rather than disk beginnings.
1013 #
1014 # This function performs partprobe on the failover host to make it re-read the
1015 # partition table.
1016 #
1017 refresh_partition_table() {
1018         local facet=$1
1019         local device=$2
1020         local host
1021
1022         host=$(facet_passive_host $facet)
1023         if [[ -n "$host" ]]; then
1024                 do_node $host "$PARTPROBE $device"
1025         fi
1026 }
1027
1028 #
1029 # Get ZFS storage pool name.
1030 #
1031 zpool_name() {
1032         local facet=$1
1033         local device
1034         local poolname
1035
1036         device=$(facet_device $facet)
1037         # poolname is string before "/"
1038         poolname="${device%%/*}"
1039
1040         echo -n $poolname
1041 }
1042
1043 #
1044 # Create ZFS storage pool.
1045 #
1046 create_zpool() {
1047         local facet=$1
1048         local poolname=$2
1049         local vdev=$3
1050         shift 3
1051         local opts=${@:-"-o cachefile=none"}
1052
1053         do_facet $facet "$ZPOOL list -H $poolname >/dev/null 2>&1 ||
1054                 $ZPOOL create -f $opts $poolname $vdev"
1055 }
1056
1057 #
1058 # Create ZFS file system.
1059 #
1060 create_zfs() {
1061         local facet=$1
1062         local dataset=$2
1063         shift 2
1064         local opts=${@:-"-o mountpoint=legacy"}
1065
1066         do_facet $facet "$ZFS list -H $dataset >/dev/null 2>&1 ||
1067                 $ZFS create $opts $dataset"
1068 }
1069
1070 #
1071 # Export ZFS storage pool.
1072 # Before exporting the pool, all datasets within the pool should be unmounted.
1073 #
1074 export_zpool() {
1075         local facet=$1
1076         shift
1077         local opts="$@"
1078         local poolname
1079
1080         poolname=$(zpool_name $facet)
1081
1082         if [[ -n "$poolname" ]]; then
1083                 do_facet $facet "! $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1084                         grep -q ^$poolname/ /proc/mounts ||
1085                         $ZPOOL export $opts $poolname"
1086         fi
1087 }
1088
1089 #
1090 # Destroy ZFS storage pool.
1091 # Destroy the given pool and free up any devices for other use. This command
1092 # tries to unmount any active datasets before destroying the pool.
1093 # -f    Force any active datasets contained within the pool to be unmounted.
1094 #
1095 destroy_zpool() {
1096         local facet=$1
1097         local poolname=${2:-$(zpool_name $facet)}
1098
1099         if [[ -n "$poolname" ]]; then
1100                 do_facet $facet "! $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1101                         $ZPOOL destroy -f $poolname"
1102         fi
1103 }
1104
1105 #
1106 # Import ZFS storage pool.
1107 # Force importing, even if the pool appears to be potentially active.
1108 #
1109 import_zpool() {
1110         local facet=$1
1111         shift
1112         local opts=${@:-"-o cachefile=none"}
1113         local poolname
1114
1115         poolname=$(zpool_name $facet)
1116
1117         if [[ -n "$poolname" ]]; then
1118                 opts+=" -d $(dirname $(facet_vdevice $facet))"
1119                 do_facet $facet "$ZPOOL list -H $poolname >/dev/null 2>&1 ||
1120                         $ZPOOL import -f $opts $poolname"
1121         fi
1122 }
1123
1124 #
1125 # Set the "cachefile=none" property on ZFS storage pool so that the pool
1126 # is not automatically imported on system startup.
1127 #
1128 # In a failover environment, this will provide resource level fencing which
1129 # will ensure that the same ZFS storage pool will not be imported concurrently
1130 # on different nodes.
1131 #
1132 disable_zpool_cache() {
1133         local facet=$1
1134         local poolname
1135
1136         poolname=$(zpool_name $facet)
1137
1138         if [[ -n "$poolname" ]]; then
1139                 do_facet $facet "$ZPOOL set cachefile=none $poolname"
1140         fi
1141 }
1142
1143 #
1144 # This and set_osd_param() shall be used to access OSD parameters
1145 # once existed under "obdfilter":
1146 #
1147 #   mntdev
1148 #   stats
1149 #   read_cache_enable
1150 #   writethrough_cache_enable
1151 #
1152 get_osd_param() {
1153         local nodes=$1
1154         local device=${2:-$FSNAME-OST*}
1155         local name=$3
1156
1157         do_nodes $nodes "$LCTL get_param -n obdfilter.$device.$name \
1158                 osd-*.$device.$name 2>&1" | grep -v 'error:'
1159 }
1160
1161 set_osd_param() {
1162         local nodes=$1
1163         local device=${2:-$FSNAME-OST*}
1164         local name=$3
1165         local value=$4
1166
1167         do_nodes $nodes "$LCTL set_param -n obdfilter.$device.$name=$value \
1168                 osd-*.$device.$name=$value 2>&1" | grep -v 'error:'
1169 }
1170
1171 set_debug_size () {
1172     local dz=${1:-$DEBUG_SIZE}
1173
1174     if [ -f /sys/devices/system/cpu/possible ]; then
1175         local cpus=$(($(cut -d "-" -f 2 /sys/devices/system/cpu/possible)+1))
1176     else
1177         local cpus=$(getconf _NPROCESSORS_CONF 2>/dev/null)
1178     fi
1179
1180     # bug 19944, adjust size to be -gt num_possible_cpus()
1181     # promise 2MB for every cpu at least
1182     if [ -n "$cpus" ] && [ $((cpus * 2)) -gt $dz ]; then
1183         dz=$((cpus * 2))
1184     fi
1185     lctl set_param debug_mb=$dz
1186 }
1187
1188 set_default_debug () {
1189     local debug=${1:-"$PTLDEBUG"}
1190     local subsys=${2:-"$SUBSYSTEM"}
1191     local debug_size=${3:-$DEBUG_SIZE}
1192
1193     [ -n "$debug" ] && lctl set_param debug="$debug" >/dev/null
1194     [ -n "$subsys" ] && lctl set_param subsystem_debug="${subsys# }" >/dev/null
1195
1196     [ -n "$debug_size" ] && set_debug_size $debug_size > /dev/null
1197 }
1198
1199 set_default_debug_nodes () {
1200         local nodes="$1"
1201
1202         if [[ ,$nodes, = *,$HOSTNAME,* ]]; then
1203                 nodes=$(exclude_items_from_list "$nodes" "$HOSTNAME")
1204                 set_default_debug
1205         fi
1206
1207         do_rpc_nodes "$nodes" set_default_debug \
1208                 \\\"$PTLDEBUG\\\" \\\"$SUBSYSTEM\\\" $DEBUG_SIZE || true
1209 }
1210
1211 set_default_debug_facet () {
1212     local facet=$1
1213     local node=$(facet_active_host $facet)
1214     [ -z "$node" ] && echo "No host defined for facet $facet" && exit 1
1215
1216     set_default_debug_nodes $node
1217 }
1218
1219 set_hostid () {
1220     local hostid=${1:-$(hostid)}
1221
1222     if [ ! -s /etc/hostid ]; then
1223         printf $(echo -n $hostid |
1224             sed 's/\(..\)\(..\)\(..\)\(..\)/\\x\4\\x\3\\x\2\\x\1/') >/etc/hostid
1225     fi
1226 }
1227
1228 # Facet functions
1229 mount_facets () {
1230         local facets=${1:-$(get_facets)}
1231         local facet
1232
1233         for facet in ${facets//,/ }; do
1234                 mount_facet $facet
1235                 local RC=$?
1236                 [ $RC -eq 0 ] && continue
1237
1238                 if [ "$TESTSUITE.$TESTNAME" = "replay-dual.test_0a" ]; then
1239                         skip "Restart of $facet failed!." && touch $LU482_FAILED
1240                 else
1241                         error "Restart of $facet failed!"
1242                 fi
1243                 return $RC
1244         done
1245 }
1246
1247 #
1248 # Add argument "arg" (e.g., "loop") to the comma-separated list
1249 # of arguments for option "opt" (e.g., "-o") on command
1250 # line "opts" (e.g., "-o flock").
1251 #
1252 csa_add() {
1253         local opts=$1
1254         local opt=$2
1255         local arg=$3
1256         local opt_pattern="\([[:space:]]\+\|^\)$opt"
1257
1258         if echo "$opts" | grep -q $opt_pattern; then
1259                 opts=$(echo "$opts" | sed -e \
1260                         "s/$opt_pattern[[:space:]]*[^[:space:]]\+/&,$arg/")
1261         else
1262                 opts+="${opts:+ }$opt $arg"
1263         fi
1264         echo -n "$opts"
1265 }
1266
1267 mount_facet() {
1268         local facet=$1
1269         shift
1270         local dev=$(facet_active $facet)_dev
1271         local opt=${facet}_opt
1272         local mntpt=$(facet_mntpt $facet)
1273         local opts="${!opt} $@"
1274         local fstype=$(facet_fstype $facet)
1275         local devicelabel
1276
1277         module_loaded lustre || load_modules
1278
1279         if [ $(facet_fstype $facet) == ldiskfs ] &&
1280            ! do_facet $facet test -b ${!dev}; then
1281                 opts=$(csa_add "$opts" -o loop)
1282         fi
1283
1284         if [[ $(facet_fstype $facet) == zfs ]]; then
1285                 # import ZFS storage pool
1286                 import_zpool $facet || return ${PIPESTATUS[0]}
1287         fi
1288
1289         case $fstype in
1290         ldiskfs)
1291                 devicelabel=$(do_facet ${facet} "$E2LABEL ${!dev}");;
1292         zfs)
1293                 devicelabel=$(do_facet ${facet} "$ZFS get -H -o value \
1294                                                 lustre:svname ${!dev}");;
1295         *)
1296                 error "unknown fstype!";;
1297         esac
1298
1299         echo "Starting ${facet}: $opts ${!dev} $mntpt"
1300         # for testing LU-482 error handling in mount_facets() and test_0a()
1301         if [ -f $TMP/test-lu482-trigger ]; then
1302                 RC=2
1303         else
1304                 do_facet ${facet} "mkdir -p $mntpt; $MOUNT_CMD $opts \
1305                                    ${!dev} $mntpt"
1306                 RC=${PIPESTATUS[0]}
1307         fi
1308
1309         if [ $RC -ne 0 ]; then
1310                 echo "Start of ${!dev} on ${facet} failed ${RC}"
1311                 return $RC
1312         fi
1313
1314         health=$(do_facet ${facet} "$LCTL get_param -n health_check")
1315         if [[ "$health" != "healthy" ]]; then
1316                 error "$facet is in a unhealthy state"
1317         fi
1318
1319         set_default_debug_facet $facet
1320
1321         if [[ $facet == mds* ]]; then
1322                 do_facet $facet \
1323                 lctl set_param -n mdt.${FSNAME}*.enable_remote_dir=1 2>/dev/null
1324         fi
1325
1326         if [[ $opts =~ .*nosvc.* ]]; then
1327                 echo "Start ${!dev} without service"
1328         else
1329
1330                 case $fstype in
1331                 ldiskfs)
1332                         wait_update_facet ${facet} "$E2LABEL ${!dev} \
1333                                 2>/dev/null | grep -E ':[a-zA-Z]{3}[0-9]{4}'" \
1334                                 "" || error "${!dev} failed to initialize!";;
1335                 zfs)
1336                         wait_update_facet ${facet} "$ZFS get -H -o value \
1337                                 lustre:svname ${!dev} 2>/dev/null | \
1338                                 grep -E ':[a-zA-Z]{3}[0-9]{4}'" "" ||
1339                                 error "${!dev} failed to initialize!";;
1340
1341                 *)
1342                         error "unknown fstype!";;
1343                 esac
1344         fi
1345
1346         # commit the device label change to disk
1347         if [[ $devicelabel =~ (:[a-zA-Z]{3}[0-9]{4}) ]]; then
1348                 echo "Commit the device label on ${!dev}"
1349                 do_facet $facet "sync; sync; sync"
1350                 sleep 5
1351         fi
1352
1353
1354         label=$(devicelabel ${facet} ${!dev})
1355         [ -z "$label" ] && echo no label for ${!dev} && exit 1
1356         eval export ${facet}_svc=${label}
1357         echo Started ${label}
1358
1359         return $RC
1360 }
1361
1362 # start facet device options
1363 start() {
1364         local facet=$1
1365         shift
1366         local device=$1
1367         shift
1368         eval export ${facet}_dev=${device}
1369         eval export ${facet}_opt=\"$@\"
1370
1371         local varname=${facet}failover_dev
1372         if [ -n "${!varname}" ] ; then
1373                 eval export ${facet}failover_dev=${!varname}
1374         else
1375                 eval export ${facet}failover_dev=$device
1376         fi
1377
1378         local mntpt=$(facet_mntpt $facet)
1379         do_facet ${facet} mkdir -p $mntpt
1380         eval export ${facet}_MOUNT=$mntpt
1381         mount_facet ${facet}
1382         RC=$?
1383
1384         if [[ $facet == mds* ]]; then
1385                 do_facet $facet \
1386                         lctl set_param -n mdt.${FSNAME}*.enable_remote_dir=1 \
1387                                 2>/dev/null
1388         fi
1389
1390         return $RC
1391 }
1392
1393 stop() {
1394     local running
1395     local facet=$1
1396     shift
1397     local HOST=`facet_active_host $facet`
1398     [ -z $HOST ] && echo stop: no host for $facet && return 0
1399
1400     local mntpt=$(facet_mntpt $facet)
1401     running=$(do_facet ${facet} "grep -c $mntpt' ' /proc/mounts") || true
1402     if [ ${running} -ne 0 ]; then
1403         echo "Stopping $mntpt (opts:$@) on $HOST"
1404         do_facet ${facet} $UMOUNT $@ $mntpt
1405     fi
1406
1407         # umount should block, but we should wait for unrelated obd's
1408         # like the MGS or MGC to also stop.
1409         wait_exit_ST ${facet} || return ${PIPESTATUS[0]}
1410
1411         if [[ $(facet_fstype $facet) == zfs ]]; then
1412                 # export ZFS storage pool
1413                 export_zpool $facet
1414         fi
1415 }
1416
1417 # save quota version (both administrative and operational quotas)
1418 # add an additional parameter if mountpoint is ever different from $MOUNT
1419 #
1420 # XXX This function is kept for interoperability with old server (< 2.3.50),
1421 #     it should be removed whenever we drop the interoperability for such
1422 #     server.
1423 quota_save_version() {
1424     local fsname=${2:-$FSNAME}
1425     local spec=$1
1426     local ver=$(tr -c -d "123" <<< $spec)
1427     local type=$(tr -c -d "ug" <<< $spec)
1428
1429     [ -n "$ver" -a "$ver" != "3" ] && error "wrong quota version specifier"
1430
1431     [ -n "$type" ] && { $LFS quotacheck -$type $MOUNT || error "quotacheck has failed"; }
1432
1433     do_facet mgs "lctl conf_param ${fsname}-MDT*.mdd.quota_type=$spec"
1434     local varsvc
1435     local osts=$(get_facets OST)
1436     for ost in ${osts//,/ }; do
1437         varsvc=${ost}_svc
1438         do_facet mgs "lctl conf_param ${!varsvc}.ost.quota_type=$spec"
1439     done
1440 }
1441
1442 # client could mount several lustre
1443 #
1444 # XXX This function is kept for interoperability with old server (< 2.3.50),
1445 #     it should be removed whenever we drop the interoperability for such
1446 #     server.
1447 quota_type() {
1448         local fsname=${1:-$FSNAME}
1449         local rc=0
1450         do_facet $SINGLEMDS lctl get_param mdd.${fsname}-MDT*.quota_type ||
1451                 rc=$?
1452         do_nodes $(comma_list $(osts_nodes)) \
1453                 lctl get_param obdfilter.${fsname}-OST*.quota_type || rc=$?
1454         return $rc
1455 }
1456
1457 # get mdt quota type
1458 mdt_quota_type() {
1459         local varsvc=${SINGLEMDS}_svc
1460         do_facet $SINGLEMDS $LCTL get_param -n \
1461                 osd-$(facet_fstype $SINGLEMDS).${!varsvc}.quota_slave.enabled
1462 }
1463
1464 # get ost quota type
1465 ost_quota_type() {
1466         # All OSTs should have same quota type
1467         local varsvc=ost1_svc
1468         do_facet ost1 $LCTL get_param -n \
1469                 osd-$(facet_fstype ost1).${!varsvc}.quota_slave.enabled
1470 }
1471
1472 # restore old quota type settings
1473 restore_quota() {
1474         if [ "$old_MDT_QUOTA_TYPE" ]; then
1475                 do_facet mgs $LCTL conf_param \
1476                         $FSNAME.quota.mdt=$old_MDT_QUOTA_TYPE
1477         fi
1478         if [ "$old_OST_QUOTA_TYPE" ]; then
1479                 do_facet mgs $LCTL conf_param \
1480                         $FSNAME.quota.ost=$old_OST_QUOTA_TYPE
1481         fi
1482 }
1483
1484 # Handle the case when there is a space in the lfs df
1485 # "filesystem summary" line the same as when there is no space.
1486 # This will allow fixing the "lfs df" summary line in the future.
1487 lfs_df() {
1488         $LFS df $* | sed -e 's/filesystem /filesystem_/'
1489 }
1490
1491 # Get free inodes on the MDT specified by mdt index, free indoes on
1492 # the whole filesystem will be returned when index == -1.
1493 mdt_free_inodes() {
1494         local index=$1
1495         local free_inodes
1496         local mdt_uuid
1497
1498         if [ $index -eq -1 ]; then
1499                 mdt_uuid="summary"
1500         else
1501                 mdt_uuid=$(mdtuuid_from_index $index)
1502         fi
1503
1504         free_inodes=$(lfs_df -i $MOUNT | grep $mdt_uuid | awk '{print $4}')
1505         echo $free_inodes
1506 }
1507
1508 setup_quota(){
1509         local mntpt=$1
1510
1511         # save old quota type & set new quota type
1512         local mdt_qtype=$(mdt_quota_type)
1513         local ost_qtype=$(ost_quota_type)
1514
1515         echo "[HOST:$HOSTNAME] [old_mdt_qtype:$mdt_qtype]" \
1516                 "[old_ost_qtype:$ost_qtype] [new_qtype:$QUOTA_TYPE]"
1517
1518         export old_MDT_QUOTA_TYPE=$mdt_qtype
1519         export old_OST_QUOTA_TYPE=$ost_qtype
1520
1521         do_facet mgs $LCTL conf_param $FSNAME.quota.mdt=$QUOTA_TYPE ||
1522                 error "set mdt quota type failed"
1523         do_facet mgs $LCTL conf_param $FSNAME.quota.ost=$QUOTA_TYPE ||
1524                 error "set ost quota type failed"
1525
1526         local quota_usrs=$QUOTA_USERS
1527
1528         # get_filesystem_size
1529         local disksz=$(lfs_df $mntpt | grep "summary" | awk '{print $2}')
1530         local blk_soft=$((disksz + 1024))
1531         local blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over
1532
1533         local inodes=$(lfs_df -i $mntpt | grep "summary" | awk '{print $2}')
1534         local i_soft=$inodes
1535         local i_hard=$((i_soft + i_soft / 20))
1536
1537         echo "Total disk size: $disksz  block-softlimit: $blk_soft" \
1538                 "block-hardlimit: $blk_hard inode-softlimit: $i_soft" \
1539                 "inode-hardlimit: $i_hard"
1540
1541         local cmd
1542         for usr in $quota_usrs; do
1543                 echo "Setting up quota on $HOSTNAME:$mntpt for $usr..."
1544                 for type in u g; do
1545                         cmd="$LFS setquota -$type $usr -b $blk_soft"
1546                         cmd="$cmd -B $blk_hard -i $i_soft -I $i_hard $mntpt"
1547                         echo "+ $cmd"
1548                         eval $cmd || error "$cmd FAILED!"
1549                 done
1550                 # display the quota status
1551                 echo "Quota settings for $usr : "
1552                 $LFS quota -v -u $usr $mntpt || true
1553         done
1554 }
1555
1556 zconf_mount() {
1557         local client=$1
1558         local mnt=$2
1559         local opts=${3:-$MOUNT_OPTS}
1560         opts=${opts:+-o $opts}
1561         local flags=${4:-$MOUNT_FLAGS}
1562
1563         local device=$MGSNID:/$FSNAME$FILESET
1564         if [ -z "$mnt" -o -z "$FSNAME" ]; then
1565                 echo "Bad mount command: opt=$flags $opts dev=$device " \
1566                      "mnt=$mnt"
1567                 exit 1
1568         fi
1569
1570         echo "Starting client: $client: $flags $opts $device $mnt"
1571         do_node $client mkdir -p $mnt
1572         if [ -n "$FILESET" -a -z "$SKIP_FILESET" ];then
1573                 do_node $client $MOUNT_CMD $flags $opts $MGSNID:/$FSNAME \
1574                         $mnt || return 1
1575                 #disable FILESET if not supported
1576                 do_nodes $client lctl get_param -n \
1577                         mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
1578                                 device=$MGSNID:/$FSNAME
1579                 do_node $client mkdir -p $mnt/$FILESET
1580                 do_node $client "! grep -q $mnt' ' /proc/mounts ||
1581                         umount $mnt"
1582         fi
1583         do_node $client $MOUNT_CMD $flags $opts $device $mnt || return 1
1584
1585         set_default_debug_nodes $client
1586
1587         return 0
1588 }
1589
1590 zconf_umount() {
1591     local client=$1
1592     local mnt=$2
1593     local force
1594     local busy
1595     local need_kill
1596
1597     [ "$3" ] && force=-f
1598     local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
1599     if [ $running -ne 0 ]; then
1600         echo "Stopping client $client $mnt (opts:$force)"
1601         do_node $client lsof -t $mnt || need_kill=no
1602         if [ "x$force" != "x" -a "x$need_kill" != "xno" ]; then
1603             pids=$(do_node $client lsof -t $mnt | sort -u);
1604             if [ -n $pids ]; then
1605                 do_node $client kill -9 $pids || true
1606             fi
1607         fi
1608
1609         busy=$(do_node $client "umount $force $mnt 2>&1" | grep -c "busy") || true
1610         if [ $busy -ne 0 ] ; then
1611             echo "$mnt is still busy, wait one second" && sleep 1
1612             do_node $client umount $force $mnt
1613         fi
1614     fi
1615 }
1616
1617 # nodes is comma list
1618 sanity_mount_check_nodes () {
1619     local nodes=$1
1620     shift
1621     local mnts="$@"
1622     local mnt
1623
1624     # FIXME: assume that all cluster nodes run the same os
1625     [ "$(uname)" = Linux ] || return 0
1626
1627     local rc=0
1628     for mnt in $mnts ; do
1629         do_nodes $nodes "running=\\\$(grep -c $mnt' ' /proc/mounts);
1630 mpts=\\\$(mount | grep -c $mnt' ');
1631 if [ \\\$running -ne \\\$mpts ]; then
1632     echo \\\$(hostname) env are INSANE!;
1633     exit 1;
1634 fi"
1635     [ $? -eq 0 ] || rc=1
1636     done
1637     return $rc
1638 }
1639
1640 sanity_mount_check_servers () {
1641     [ -n "$CLIENTONLY" ] &&
1642         { echo "CLIENTONLY mode, skip mount_check_servers"; return 0; } || true
1643     echo Checking servers environments
1644
1645     # FIXME: modify get_facets to display all facets wo params
1646     local facets="$(get_facets OST),$(get_facets MDS),mgs"
1647     local node
1648     local mntpt
1649     local facet
1650     for facet in ${facets//,/ }; do
1651         node=$(facet_host ${facet})
1652         mntpt=$(facet_mntpt $facet)
1653         sanity_mount_check_nodes $node $mntpt ||
1654             { error "server $node environments are insane!"; return 1; }
1655     done
1656 }
1657
1658 sanity_mount_check_clients () {
1659     local clients=${1:-$CLIENTS}
1660     local mntpt=${2:-$MOUNT}
1661     local mntpt2=${3:-$MOUNT2}
1662
1663     [ -z $clients ] && clients=$(hostname)
1664     echo Checking clients $clients environments
1665
1666     sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
1667        error "clients environments are insane!"
1668 }
1669
1670 sanity_mount_check () {
1671     sanity_mount_check_servers || return 1
1672     sanity_mount_check_clients || return 2
1673 }
1674
1675 # mount clients if not mouted
1676 zconf_mount_clients() {
1677         local clients=$1
1678         local mnt=$2
1679         local opts=${3:-$MOUNT_OPTS}
1680         opts=${opts:+-o $opts}
1681         local flags=${4:-$MOUNT_FLAGS}
1682
1683         local device=$MGSNID:/$FSNAME$FILESET
1684         if [ -z "$mnt" -o -z "$FSNAME" ]; then
1685                 echo "Bad conf mount command: opt=$flags $opts dev=$device " \
1686                      "mnt=$mnt"
1687                 exit 1
1688         fi
1689
1690         echo "Starting client $clients: $flags $opts $device $mnt"
1691         if [ -n "$FILESET" -a ! -n "$SKIP_FILESET" ]; then
1692                 do_nodes $clients "! grep -q $mnt' ' /proc/mounts ||
1693                         umount $mnt"
1694                 do_nodes $clients $MOUNT_CMD $flags $opts $MGSNID:/$FSNAME \
1695                         $mnt || return 1
1696                 #disable FILESET if not supported
1697                 do_nodes $clients lctl get_param -n \
1698                         mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
1699                                 device=$MGSNID:/$FSNAME
1700                 do_nodes $clients mkdir -p $mnt/$FILESET
1701                 do_nodes $clients "! grep -q $mnt' ' /proc/mounts ||
1702                         umount $mnt"
1703         fi
1704
1705         do_nodes $clients "
1706 running=\\\$(mount | grep -c $mnt' ');
1707 rc=0;
1708 if [ \\\$running -eq 0 ] ; then
1709     mkdir -p $mnt;
1710     $MOUNT_CMD $flags $opts $device $mnt;
1711     rc=\\\$?;
1712 fi;
1713 exit \\\$rc" || return ${PIPESTATUS[0]}
1714
1715         echo "Started clients $clients: "
1716         do_nodes $clients "mount | grep $mnt' '"
1717
1718         set_default_debug_nodes $clients
1719
1720         return 0
1721 }
1722
1723 zconf_umount_clients() {
1724     local clients=$1
1725     local mnt=$2
1726     local force
1727
1728     [ "$3" ] && force=-f
1729
1730     echo "Stopping clients: $clients $mnt (opts:$force)"
1731     do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
1732 if [ \\\$running -ne 0 ] ; then
1733 echo Stopping client \\\$(hostname) $mnt opts:$force;
1734 lsof $mnt || need_kill=no;
1735 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
1736     pids=\\\$(lsof -t $mnt | sort -u);
1737     if [ -n \\\"\\\$pids\\\" ]; then
1738              kill -9 \\\$pids;
1739     fi
1740 fi;
1741 while umount $force $mnt 2>&1 | grep -q "busy"; do
1742     echo "$mnt is still busy, wait one second" && sleep 1;
1743 done;
1744 fi"
1745 }
1746
1747 shutdown_node () {
1748     local node=$1
1749     echo + $POWER_DOWN $node
1750     $POWER_DOWN $node
1751 }
1752
1753 shutdown_node_hard () {
1754     local host=$1
1755     local attempts=$SHUTDOWN_ATTEMPTS
1756
1757     for i in $(seq $attempts) ; do
1758         shutdown_node $host
1759         sleep 1
1760         wait_for_function --quiet "! ping -w 3 -c 1 $host" 5 1 && return 0
1761         echo "waiting for $host to fail attempts=$attempts"
1762         [ $i -lt $attempts ] || \
1763             { echo "$host still pingable after power down! attempts=$attempts" && return 1; }
1764     done
1765 }
1766
1767 shutdown_client() {
1768     local client=$1
1769     local mnt=${2:-$MOUNT}
1770     local attempts=3
1771
1772     if [ "$FAILURE_MODE" = HARD ]; then
1773         shutdown_node_hard $client
1774     else
1775        zconf_umount_clients $client $mnt -f
1776     fi
1777 }
1778
1779 facets_on_host () {
1780     local host=$1
1781     local facets="$(get_facets OST),$(get_facets MDS)"
1782     local affected
1783
1784     combined_mgs_mds || facets="$facets,mgs"
1785
1786     for facet in ${facets//,/ }; do
1787         if [ $(facet_active_host $facet) == $host ]; then
1788            affected="$affected $facet"
1789         fi
1790     done
1791
1792     echo $(comma_list $affected)
1793 }
1794
1795 facet_up() {
1796         local facet=$1
1797         local host=${2:-$(facet_host $facet)}
1798
1799         local label=$(convert_facet2label $facet)
1800         do_node $host $LCTL dl | awk '{ print $4 }' | grep -q "^$label\$"
1801 }
1802
1803 facets_up_on_host () {
1804     local host=$1
1805     local facets=$(facets_on_host $host)
1806     local affected_up
1807
1808     for facet in ${facets//,/ }; do
1809         if $(facet_up $facet $host); then
1810             affected_up="$affected_up $facet"
1811         fi
1812     done
1813
1814     echo $(comma_list $affected_up)
1815 }
1816
1817 shutdown_facet() {
1818     local facet=$1
1819
1820     if [ "$FAILURE_MODE" = HARD ]; then
1821         shutdown_node_hard $(facet_active_host $facet)
1822     else
1823         stop $facet
1824     fi
1825 }
1826
1827 reboot_node() {
1828     local node=$1
1829     echo + $POWER_UP $node
1830     $POWER_UP $node
1831 }
1832
1833 remount_facet() {
1834     local facet=$1
1835
1836     stop $facet
1837     mount_facet $facet
1838 }
1839
1840 reboot_facet() {
1841         local facet=$1
1842         if [ "$FAILURE_MODE" = HARD ]; then
1843                 reboot_node $(facet_active_host $facet)
1844         else
1845                 sleep 10
1846         fi
1847 }
1848
1849 boot_node() {
1850     local node=$1
1851     if [ "$FAILURE_MODE" = HARD ]; then
1852        reboot_node $node
1853        wait_for_host $node
1854     fi
1855 }
1856
1857 facets_hosts () {
1858     local facets=$1
1859     local hosts
1860
1861     for facet in ${facets//,/ }; do
1862         hosts=$(expand_list $hosts $(facet_host $facet) )
1863     done
1864
1865     echo $hosts
1866 }
1867
1868 _check_progs_installed () {
1869     local progs=$@
1870     local rc=0
1871
1872     for prog in $progs; do
1873         if ! [ "$(which $prog)"  -o  "${!prog}" ]; then
1874            echo $prog missing on $(hostname)
1875            rc=1
1876         fi
1877     done
1878     return $rc
1879 }
1880
1881 check_progs_installed () {
1882         local nodes=$1
1883         shift
1884
1885         do_rpc_nodes "$nodes" _check_progs_installed $@
1886 }
1887
1888 # recovery-scale functions
1889 node_var_name() {
1890     echo __$(echo $1 | tr '-' '_' | tr '.' '_')
1891 }
1892
1893 start_client_load() {
1894     local client=$1
1895     local load=$2
1896     local var=$(node_var_name $client)_load
1897     eval export ${var}=$load
1898
1899     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
1900 BREAK_ON_ERROR=$BREAK_ON_ERROR \
1901 END_RUN_FILE=$END_RUN_FILE \
1902 LOAD_PID_FILE=$LOAD_PID_FILE \
1903 TESTLOG_PREFIX=$TESTLOG_PREFIX \
1904 TESTNAME=$TESTNAME \
1905 DBENCH_LIB=$DBENCH_LIB \
1906 DBENCH_SRC=$DBENCH_SRC \
1907 CLIENT_COUNT=$((CLIENTCOUNT - 1)) \
1908 LFS=$LFS \
1909 run_${load}.sh" &
1910     local ppid=$!
1911     log "Started client load: ${load} on $client"
1912
1913     # get the children process IDs
1914     local pids=$(ps --ppid $ppid -o pid= | xargs)
1915     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $ppid $pids"
1916     return 0
1917 }
1918
1919 start_client_loads () {
1920     local -a clients=(${1//,/ })
1921     local numloads=${#CLIENT_LOADS[@]}
1922     local testnum
1923
1924     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
1925         testnum=$((nodenum % numloads))
1926         start_client_load ${clients[nodenum]} ${CLIENT_LOADS[testnum]}
1927     done
1928     # bug 22169: wait the background threads to start
1929     sleep 2
1930 }
1931
1932 # only for remote client
1933 check_client_load () {
1934         local client=$1
1935         local var=$(node_var_name $client)_load
1936         local testload=run_${!var}.sh
1937
1938         ps -C $testload | grep $client || return 1
1939
1940         # bug 18914: try to connect several times not only when
1941         # check ps, but  while check_node_health also
1942
1943         local tries=3
1944         local RC=254
1945         while [ $RC = 254 -a $tries -gt 0 ]; do
1946                 let tries=$tries-1
1947                 # assume success
1948                 RC=0
1949                 if ! check_node_health $client; then
1950                         RC=${PIPESTATUS[0]}
1951                         if [ $RC -eq 254 ]; then
1952                                 # FIXME: not sure how long we shuold sleep here
1953                                 sleep 10
1954                                 continue
1955                         fi
1956                         echo "check node health failed: RC=$RC "
1957                         return $RC
1958                 fi
1959         done
1960         # We can continue try to connect if RC=254
1961         # Just print the warning about this
1962         if [ $RC = 254 ]; then
1963                 echo "got a return status of $RC from do_node while checking " \
1964                 "node health on $client"
1965         fi
1966
1967         # see if the load is still on the client
1968         tries=3
1969         RC=254
1970         while [ $RC = 254 -a $tries -gt 0 ]; do
1971                 let tries=$tries-1
1972                 # assume success
1973                 RC=0
1974                 if ! do_node $client \
1975                         "ps auxwww | grep -v grep | grep -q $testload"; then
1976                         RC=${PIPESTATUS[0]}
1977                         sleep 30
1978                 fi
1979         done
1980         if [ $RC = 254 ]; then
1981                 echo "got a return status of $RC from do_node while checking " \
1982                 "(node health and 'ps') the client load on $client"
1983                 # see if we can diagnose a bit why this is
1984         fi
1985
1986         return $RC
1987 }
1988 check_client_loads () {
1989    local clients=${1//,/ }
1990    local client=
1991    local rc=0
1992
1993    for client in $clients; do
1994       check_client_load $client
1995       rc=${PIPESTATUS[0]}
1996       if [ "$rc" != 0 ]; then
1997         log "Client load failed on node $client, rc=$rc"
1998         return $rc
1999       fi
2000    done
2001 }
2002
2003 restart_client_loads () {
2004     local clients=${1//,/ }
2005     local expectedfail=${2:-""}
2006     local client=
2007     local rc=0
2008
2009     for client in $clients; do
2010         check_client_load $client
2011         rc=${PIPESTATUS[0]}
2012         if [ "$rc" != 0 -a "$expectedfail" ]; then
2013             local var=$(node_var_name $client)_load
2014             start_client_load $client ${!var}
2015             echo "Restarted client load ${!var}: on $client. Checking ..."
2016             check_client_load $client
2017             rc=${PIPESTATUS[0]}
2018             if [ "$rc" != 0 ]; then
2019                 log "Client load failed to restart on node $client, rc=$rc"
2020                 # failure one client load means test fail
2021                 # we do not need to check other
2022                 return $rc
2023             fi
2024         else
2025             return $rc
2026         fi
2027     done
2028 }
2029
2030 # Start vmstat and save its process ID in a file.
2031 start_vmstat() {
2032     local nodes=$1
2033     local pid_file=$2
2034
2035     [ -z "$nodes" -o -z "$pid_file" ] && return 0
2036
2037     do_nodes $nodes \
2038         "vmstat 1 > $TESTLOG_PREFIX.$TESTNAME.vmstat.\\\$(hostname -s).log \
2039         2>/dev/null </dev/null & echo \\\$! > $pid_file"
2040 }
2041
2042 # Display the nodes on which client loads failed.
2043 print_end_run_file() {
2044     local file=$1
2045     local node
2046
2047     [ -s $file ] || return 0
2048
2049     echo "Found the END_RUN_FILE file: $file"
2050     cat $file
2051
2052     # A client load will stop if it finds the END_RUN_FILE file.
2053     # That does not mean the client load actually failed though.
2054     # The first node in END_RUN_FILE is the one we are interested in.
2055     read node < $file
2056
2057     if [ -n "$node" ]; then
2058         local var=$(node_var_name $node)_load
2059
2060         local prefix=$TESTLOG_PREFIX
2061         [ -n "$TESTNAME" ] && prefix=$prefix.$TESTNAME
2062         local stdout_log=$prefix.run_${!var}_stdout.$node.log
2063         local debug_log=$(echo $stdout_log | sed 's/\(.*\)stdout/\1debug/')
2064
2065         echo "Client load ${!var} failed on node $node:"
2066         echo "$stdout_log"
2067         echo "$debug_log"
2068     fi
2069 }
2070
2071 # Stop the process which had its PID saved in a file.
2072 stop_process() {
2073     local nodes=$1
2074     local pid_file=$2
2075
2076     [ -z "$nodes" -o -z "$pid_file" ] && return 0
2077
2078     do_nodes $nodes "test -f $pid_file &&
2079         { kill -s TERM \\\$(cat $pid_file); rm -f $pid_file; }" || true
2080 }
2081
2082 # Stop all client loads.
2083 stop_client_loads() {
2084     local nodes=${1:-$CLIENTS}
2085     local pid_file=$2
2086
2087     # stop the client loads
2088     stop_process $nodes $pid_file
2089
2090     # clean up the processes that started them
2091     [ -n "$CLIENT_LOAD_PIDS" ] && kill -9 $CLIENT_LOAD_PIDS 2>/dev/null || true
2092 }
2093 # End recovery-scale functions
2094
2095 # verify that lustre actually cleaned up properly
2096 cleanup_check() {
2097         VAR=$(lctl get_param -n catastrophe 2>&1)
2098         if [ $? = 0 ] ; then
2099                 if [ $VAR != 0 ]; then
2100                         error "LBUG/LASSERT detected"
2101                 fi
2102         fi
2103         BUSY=$(dmesg | grep -i destruct || true)
2104         if [ -n "$BUSY" ]; then
2105                 echo "$BUSY" 1>&2
2106                 [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.$(date +%s)
2107                 exit 205
2108         fi
2109
2110         check_mem_leak || exit 204
2111
2112         [[ $($LCTL dl 2>/dev/null | wc -l) -gt 0 ]] && $LCTL dl &&
2113                 echo "$TESTSUITE: lustre didn't clean up..." 1>&2 &&
2114                 return 202 || true
2115
2116         if module_loaded lnet || module_loaded libcfs; then
2117                 echo "$TESTSUITE: modules still loaded..." 1>&2
2118                 /sbin/lsmod 1>&2
2119                 return 203
2120         fi
2121         return 0
2122 }
2123
2124 wait_update () {
2125         local verbose=false
2126         if [[ "$1" == "--verbose" ]]; then
2127                 shift
2128                 verbose=true
2129         fi
2130
2131         local node=$1
2132         local TEST=$2
2133         local FINAL=$3
2134         local MAX=${4:-90}
2135         local RESULT
2136         local PREV_RESULT
2137         local WAIT=0
2138         local sleep=1
2139         local print=10
2140
2141         PREV_RESULT=$(do_node $node "$TEST")
2142         while [ true ]; do
2143                 RESULT=$(do_node $node "$TEST")
2144                 if [[ "$RESULT" == "$FINAL" ]]; then
2145                         [[ -z "$RESULT" || $WAIT -le $sleep ]] ||
2146                                 echo "Updated after ${WAIT}s: wanted '$FINAL'"\
2147                                      "got '$RESULT'"
2148                         return 0
2149                 fi
2150                 if [[ $verbose && "$RESULT" != "$PREV_RESULT" ]]; then
2151                         echo "Changed after ${WAIT}s: from '$PREV_RESULT'"\
2152                              "to '$RESULT'"
2153                         PREV_RESULT=$RESULT
2154                 fi
2155                 [[ $WAIT -ge $MAX ]] && break
2156                 [[ $((WAIT % print)) -eq 0 ]] &&
2157                         echo "Waiting $((MAX - WAIT)) secs for update"
2158                 WAIT=$((WAIT + sleep))
2159                 sleep $sleep
2160         done
2161         echo "Update not seen after ${MAX}s: wanted '$FINAL' got '$RESULT'"
2162         return 3
2163 }
2164
2165 wait_update_facet() {
2166         local verbose=
2167         [ "$1" = "--verbose" ] && verbose="$1" && shift
2168
2169         local facet=$1
2170         shift
2171         wait_update $verbose $(facet_active_host $facet) "$@"
2172 }
2173
2174 sync_all_data() {
2175         do_nodes $(comma_list $(mdts_nodes)) \
2176             "lctl set_param -n osd*.*MDT*.force_sync=1"
2177         do_nodes $(comma_list $(osts_nodes)) \
2178             "lctl set_param -n osd*.*OS*.force_sync=1" 2>&1 |
2179                 grep -v 'Found no match'
2180 }
2181
2182 wait_delete_completed_mds() {
2183         local MAX_WAIT=${1:-20}
2184         # for ZFS, waiting more time for DMUs to be committed
2185         local ZFS_WAIT=${2:-5}
2186         local mds2sync=""
2187         local stime=$(date +%s)
2188         local etime
2189         local node
2190         local changes
2191
2192         # find MDS with pending deletions
2193         for node in $(mdts_nodes); do
2194                 changes=$(do_node $node "$LCTL get_param -n osc.*MDT*.sync_*" \
2195                         2>/dev/null | calc_sum)
2196                 if [[ $changes -eq 0 ]]; then
2197                         continue
2198                 fi
2199                 mds2sync="$mds2sync $node"
2200         done
2201         if [ -z "$mds2sync" ]; then
2202                 return
2203         fi
2204         mds2sync=$(comma_list $mds2sync)
2205
2206         # sync MDS transactions
2207         do_nodes $mds2sync "$LCTL set_param -n osd*.*MD*.force_sync 1"
2208
2209         # wait till all changes are sent and commmitted by OSTs
2210         # for ldiskfs space is released upon execution, but DMU
2211         # do this upon commit
2212
2213         local WAIT=0
2214         while [[ $WAIT -ne $MAX_WAIT ]]; do
2215                 changes=$(do_nodes $mds2sync \
2216                         "$LCTL get_param -n osc.*MDT*.sync_*" | calc_sum)
2217                 #echo "$node: $changes changes on all"
2218                 if [[ $changes -eq 0 ]]; then
2219                         etime=$(date +%s)
2220                         #echo "delete took $((etime - stime)) seconds"
2221
2222                         # the occupied disk space will be released
2223                         # only after DMUs are committed
2224                         if [[ $(facet_fstype $SINGLEMDS) == zfs ]]; then
2225                                 echo "sleep $ZFS_WAIT for ZFS OSD"
2226                                 sleep $ZFS_WAIT
2227                         fi
2228
2229                         return
2230                 fi
2231                 sleep 1
2232                 WAIT=$(( WAIT + 1))
2233         done
2234
2235         etime=$(date +%s)
2236         echo "Delete is not completed in $((etime - stime)) seconds"
2237         do_nodes $mds2sync "$LCTL get_param osc.*MDT*.sync_*"
2238 }
2239
2240 wait_for_host() {
2241     local hostlist=$1
2242
2243     # we can use "for" here because we are waiting the slowest
2244     for host in ${hostlist//,/ }; do
2245         check_network "$host" 900
2246     done
2247     while ! do_nodes $hostlist hostname  > /dev/null; do sleep 5; done
2248 }
2249
2250 wait_for_facet() {
2251     local facetlist=$1
2252     local hostlist
2253
2254     for facet in ${facetlist//,/ }; do
2255         hostlist=$(expand_list $hostlist $(facet_active_host $facet))
2256     done
2257     wait_for_host $hostlist
2258 }
2259
2260 _wait_recovery_complete () {
2261     local param=$1
2262
2263     # Use default policy if $2 is not passed by caller.
2264     local MAX=${2:-$(max_recovery_time)}
2265
2266     local WAIT=0
2267     local STATUS=
2268
2269     while [ $WAIT -lt $MAX ]; do
2270         STATUS=$(lctl get_param -n $param | grep status)
2271         echo $param $STATUS
2272         [[ $STATUS = "status: COMPLETE" || $STATUS = "status: INACTIVE" ]] && return 0
2273         sleep 5
2274         WAIT=$((WAIT + 5))
2275         echo "Waiting $((MAX - WAIT)) secs for $param recovery done. $STATUS"
2276     done
2277     echo "$param recovery not done in $MAX sec. $STATUS"
2278     return 1
2279 }
2280
2281 wait_recovery_complete () {
2282     local facet=$1
2283
2284     # with an assumption that at_max is the same on all nodes
2285     local MAX=${2:-$(max_recovery_time)}
2286
2287     local facets=$facet
2288     if [ "$FAILURE_MODE" = HARD ]; then
2289         facets=$(facets_on_host $(facet_active_host $facet))
2290     fi
2291     echo affected facets: $facets
2292
2293         # we can use "for" here because we are waiting the slowest
2294         for facet in ${facets//,/ }; do
2295                 local var_svc=${facet}_svc
2296                 local param="*.${!var_svc}.recovery_status"
2297
2298                 local host=$(facet_active_host $facet)
2299                 do_rpc_nodes "$host" _wait_recovery_complete $param $MAX
2300         done
2301 }
2302
2303 wait_mds_ost_sync () {
2304         # just because recovery is done doesn't mean we've finished
2305         # orphan cleanup. Wait for llogs to get synchronized.
2306         echo "Waiting for orphan cleanup..."
2307         # MAX value includes time needed for MDS-OST reconnection
2308         local MAX=$(( TIMEOUT * 2 ))
2309         local WAIT_TIMEOUT=${1:-$MAX}
2310         local WAIT=0
2311         local new_wait=true
2312         local list=$(comma_list $(mdts_nodes))
2313         local cmd="$LCTL get_param -n osp.*osc*.old_sync_processed"
2314         if ! do_facet $SINGLEMDS \
2315                 "$LCTL list_param osp.*osc*.old_sync_processed 2> /dev/null"
2316         then
2317                 # old way, use mds_sync
2318                 new_wait=false
2319                 list=$(comma_list $(osts_nodes))
2320                 cmd="$LCTL get_param -n obdfilter.*.mds_sync"
2321         fi
2322
2323         echo "wait $WAIT_TIMEOUT secs maximumly for $list mds-ost sync done."
2324         while [ $WAIT -lt $WAIT_TIMEOUT ]; do
2325                 local -a sync=($(do_nodes $list "$cmd"))
2326                 local con=1
2327                 local i
2328                 for ((i=0; i<${#sync[@]}; i++)); do
2329                         if $new_wait; then
2330                                 [ ${sync[$i]} -eq 1 ] && continue
2331                         else
2332                                 [ ${sync[$i]} -eq 0 ] && continue
2333                         fi
2334                         # there is a not finished MDS-OST synchronization
2335                         con=0
2336                         break;
2337                 done
2338                 sleep 2 # increase waiting time and cover statfs cache
2339                 [ ${con} -eq 1 ] && return 0
2340                 echo "Waiting $WAIT secs for $list $i mds-ost sync done."
2341                 WAIT=$((WAIT + 2))
2342         done
2343
2344         # show which nodes are not finished.
2345         do_nodes $list "$cmd"
2346         echo "$facet recovery node $i not done in $WAIT_TIMEOUT sec. $STATUS"
2347         return 1
2348 }
2349
2350 wait_destroy_complete () {
2351         echo "Waiting for local destroys to complete"
2352         # MAX value shouldn't be big as this mean server responsiveness
2353         # never increase this just to make test pass but investigate
2354         # why it takes so long time
2355         local MAX=5
2356         local WAIT=0
2357         while [ $WAIT -lt $MAX ]; do
2358                 local -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))
2359                 local con=1
2360                 local i
2361
2362                 for ((i=0; i<${#RPCs[@]}; i++)); do
2363                         [ ${RPCs[$i]} -eq 0 ] && continue
2364                         # there are still some destroy RPCs in flight
2365                         con=0
2366                         break;
2367                 done
2368                 sleep 1
2369                 [ ${con} -eq 1 ] && return 0 # done waiting
2370                 echo "Waiting ${WAIT}s for local destroys to complete"
2371                 WAIT=$((WAIT + 1))
2372         done
2373         echo "Local destroys weren't done in $MAX sec."
2374         return 1
2375 }
2376
2377 wait_delete_completed() {
2378         wait_delete_completed_mds $1 || return $?
2379         wait_destroy_complete
2380 }
2381
2382 wait_exit_ST () {
2383     local facet=$1
2384
2385     local WAIT=0
2386     local INTERVAL=1
2387     local running
2388     # conf-sanity 31 takes a long time cleanup
2389     while [ $WAIT -lt 300 ]; do
2390         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
2391         [ -z "${running}" ] && return 0
2392         echo "waited $WAIT for${running}"
2393         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
2394         sleep $INTERVAL
2395         WAIT=$((WAIT + INTERVAL))
2396     done
2397     echo "service didn't stop after $WAIT seconds.  Still running:"
2398     echo ${running}
2399     return 1
2400 }
2401
2402 wait_remote_prog () {
2403    local prog=$1
2404    local WAIT=0
2405    local INTERVAL=5
2406    local rc=0
2407
2408    [ "$PDSH" = "no_dsh" ] && return 0
2409
2410    while [ $WAIT -lt $2 ]; do
2411         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
2412         [ -z "${running}" ] && return 0 || true
2413         echo "waited $WAIT for: "
2414         echo "$running"
2415         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
2416         sleep $INTERVAL
2417         WAIT=$((WAIT + INTERVAL))
2418     done
2419     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
2420     [ -z "$pids" ] && return 0
2421     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
2422     # FIXME: not portable
2423     for pid in $pids; do
2424         cat /proc/${pid}/status || true
2425         cat /proc/${pid}/wchan || true
2426         echo "Killing $pid"
2427         kill -9 $pid || true
2428         sleep 1
2429         ps -P $pid && rc=1
2430     done
2431
2432     return $rc
2433 }
2434
2435 lfs_df_check() {
2436         local clients=${1:-$CLIENTS}
2437
2438         if [ -z "$clients" ]; then
2439                 $LFS df $MOUNT
2440         else
2441                 $PDSH $clients "$LFS df $MOUNT" > /dev/null
2442         fi
2443 }
2444
2445
2446 clients_up() {
2447         # not every config has many clients
2448         sleep 1
2449         lfs_df_check
2450 }
2451
2452 client_up() {
2453         # usually checked on particular client or locally
2454         sleep 1
2455         lfs_df_check $1
2456 }
2457
2458 client_evicted() {
2459     ! client_up $1
2460 }
2461
2462 client_reconnect_try() {
2463         local f=$MOUNT/recon
2464
2465         uname -n >> $f
2466         if [ -z "$CLIENTS" ]; then
2467                 $LFS df $MOUNT; uname -n >> $f
2468         else
2469                 do_nodes $CLIENTS "$LFS df $MOUNT; uname -n >> $f" > /dev/null
2470         fi
2471         echo "Connected clients: $(cat $f)"
2472         ls -l $f > /dev/null
2473         rm $f
2474 }
2475
2476 client_reconnect() {
2477         # one client_reconnect_try call does not always do the job...
2478         while true ; do
2479                 client_reconnect_try && break
2480                 sleep 1
2481         done
2482 }
2483
2484 affected_facets () {
2485     local facet=$1
2486
2487     local host=$(facet_active_host $facet)
2488     local affected=$facet
2489
2490     if [ "$FAILURE_MODE" = HARD ]; then
2491         affected=$(facets_up_on_host $host)
2492     fi
2493     echo $affected
2494 }
2495
2496 facet_failover() {
2497         local E2FSCK_ON_MDT0=false
2498         if [ "$1" == "--fsck" ]; then
2499                 shift
2500                 [ $(facet_fstype $SINGLEMDS) == ldiskfs ] &&
2501                         E2FSCK_ON_MDT0=true
2502         fi
2503
2504         local facets=$1
2505         local sleep_time=$2
2506         local -a affecteds
2507         local facet
2508         local total=0
2509         local index=0
2510         local skip
2511
2512         #Because it will only get up facets, we need get affected
2513         #facets before shutdown
2514         #For HARD Failure mode, it needs make sure facets on the same
2515         #HOST will only be shutdown and reboot once
2516         for facet in ${facets//,/ }; do
2517                 local affected_facet
2518                 skip=0
2519                 #check whether facet has been included in other affected facets
2520                 for ((index=0; index<$total; index++)); do
2521                         [[ *,$facet,* == ,${affecteds[index]}, ]] && skip=1
2522                 done
2523
2524                 if [ $skip -eq 0 ]; then
2525                         affecteds[$total]=$(affected_facets $facet)
2526                         total=$((total+1))
2527                 fi
2528         done
2529
2530         for ((index=0; index<$total; index++)); do
2531                 facet=$(echo ${affecteds[index]} | tr -s " " | cut -d"," -f 1)
2532                 local host=$(facet_active_host $facet)
2533                 echo "Failing ${affecteds[index]} on $host"
2534                 shutdown_facet $facet
2535         done
2536
2537         $E2FSCK_ON_MDT0 && (run_e2fsck $(facet_active_host $SINGLEMDS) \
2538                 $(mdsdevname 1) "-n" || error "Running e2fsck")
2539
2540         for ((index=0; index<$total; index++)); do
2541                 facet=$(echo ${affecteds[index]} | tr -s " " | cut -d"," -f 1)
2542                 echo reboot facets: ${affecteds[index]}
2543
2544                 reboot_facet $facet
2545
2546                 change_active ${affecteds[index]}
2547
2548                 wait_for_facet ${affecteds[index]}
2549                 # start mgs first if it is affected
2550                 if ! combined_mgs_mds &&
2551                         list_member ${affecteds[index]} mgs; then
2552                         mount_facet mgs || error "Restart of mgs failed"
2553                 fi
2554                 # FIXME; has to be changed to mount all facets concurrently
2555                 affected=$(exclude_items_from_list ${affecteds[index]} mgs)
2556                 echo mount facets: ${affecteds[index]}
2557                 mount_facets ${affecteds[index]}
2558         done
2559 }
2560
2561 obd_name() {
2562     local facet=$1
2563 }
2564
2565 replay_barrier() {
2566         local facet=$1
2567         do_facet $facet "sync; sync; sync"
2568         $LFS df $MOUNT
2569
2570         # make sure there will be no seq change
2571         local clients=${CLIENTS:-$HOSTNAME}
2572         local f=fsa-\\\$\(hostname\)
2573         do_nodes $clients "mcreate $MOUNT/$f; rm $MOUNT/$f"
2574         do_nodes $clients "if [ -d $MOUNT2 ]; then mcreate $MOUNT2/$f; rm $MOUNT2/$f; fi"
2575
2576         local svc=${facet}_svc
2577         do_facet $facet $LCTL --device ${!svc} notransno
2578         #
2579         # If a ZFS OSD is made read-only here, its pool is "freezed". This
2580         # in-memory state has to be cleared by either rebooting the host or
2581         # exporting and reimporting the pool.
2582         #
2583         # Although the uberblocks are not updated when a pool is freezed,
2584         # transactions are still written to the disks. Modified blocks may be
2585         # cached in memory when tests try reading them back. The
2586         # export-and-reimport process also evicts any cached pool data from
2587         # memory to provide the correct "data loss" semantics.
2588         #
2589         # In the test framework, the exporting and importing operations are
2590         # handled by stop() and mount_facet() separately, which are used
2591         # inside fail() and fail_abort().
2592         #
2593         do_facet $facet $LCTL --device ${!svc} readonly
2594         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
2595         $LCTL mark "local REPLAY BARRIER on ${!svc}"
2596 }
2597
2598 replay_barrier_nodf() {
2599         local facet=$1    echo running=${running}
2600         do_facet $facet "sync; sync; sync"
2601         local svc=${facet}_svc
2602         echo Replay barrier on ${!svc}
2603         do_facet $facet $LCTL --device ${!svc} notransno
2604         do_facet $facet $LCTL --device ${!svc} readonly
2605         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
2606         $LCTL mark "local REPLAY BARRIER on ${!svc}"
2607 }
2608
2609 replay_barrier_nosync() {
2610         local facet=$1    echo running=${running}
2611         local svc=${facet}_svc
2612         echo Replay barrier on ${!svc}
2613         do_facet $facet $LCTL --device ${!svc} notransno
2614         do_facet $facet $LCTL --device ${!svc} readonly
2615         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
2616         $LCTL mark "local REPLAY BARRIER on ${!svc}"
2617 }
2618
2619 #
2620 # Get Lustre client uuid for a given Lustre mount point.
2621 #
2622 get_client_uuid() {
2623         local mntpnt=${1:-$MOUNT}
2624
2625         local name=$($LFS getname $mntpnt | cut -d' ' -f1)
2626         local uuid=$($LCTL get_param -n llite.$name.uuid)
2627
2628         echo -n $uuid
2629 }
2630
2631 mds_evict_client() {
2632         local mntpnt=${1:-$MOUNT}
2633         local uuid=$(get_client_uuid $mntpnt)
2634
2635         do_facet $SINGLEMDS \
2636                 "$LCTL set_param -n mdt.${mds1_svc}.evict_client $uuid"
2637 }
2638
2639 ost_evict_client() {
2640         local mntpnt=${1:-$MOUNT}
2641         local uuid=$(get_client_uuid $mntpnt)
2642
2643         do_facet ost1 \
2644                 "$LCTL set_param -n obdfilter.${ost1_svc}.evict_client $uuid"
2645 }
2646
2647 fail() {
2648         local facets=$1
2649         local clients=${CLIENTS:-$HOSTNAME}
2650
2651         facet_failover $* || error "failover: $?"
2652         wait_clients_import_state "$clients" "$facets" FULL
2653         clients_up || error "post-failover stat: $?"
2654 }
2655
2656 fail_nodf() {
2657         local facet=$1
2658         facet_failover $facet
2659 }
2660
2661 fail_abort() {
2662         local facet=$1
2663         stop $facet
2664         change_active $facet
2665         wait_for_facet $facet
2666         mount_facet $facet -o abort_recovery
2667         clients_up || echo "first stat failed: $?"
2668         clients_up || error "post-failover stat: $?"
2669 }
2670
2671 do_lmc() {
2672     echo There is no lmc.  This is mountconf, baby.
2673     exit 1
2674 }
2675
2676 host_nids_address() {
2677     local nodes=$1
2678     local kind=$2
2679
2680     if [ -n "$kind" ]; then
2681         nids=$(do_nodes $nodes "$LCTL list_nids | grep $kind | cut -f 1 -d '@'")
2682     else
2683         nids=$(do_nodes $nodes "$LCTL list_nids all | cut -f 1 -d '@'")
2684     fi
2685     echo $nids
2686 }
2687
2688 h2name_or_ip() {
2689         if [ "$1" = "'*'" ]; then echo \'*\'; else
2690                 echo $1"@$2"
2691         fi
2692 }
2693
2694 h2ptl() {
2695         if [ "$1" = "'*'" ]; then echo \'*\'; else
2696                 ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | \
2697                                                         awk '{print $1}'`
2698                 if [ -z "$ID" ]; then
2699                         echo "Could not get a ptl id for $1..."
2700                         exit 1
2701                 fi
2702                 echo $ID"@ptl"
2703         fi
2704 }
2705 declare -fx h2ptl
2706
2707 h2tcp() {
2708         h2name_or_ip "$1" "tcp"
2709 }
2710 declare -fx h2tcp
2711
2712 h2elan() {
2713         if [ "$1" = "'*'" ]; then echo \'*\'; else
2714                 if type __h2elan >/dev/null 2>&1; then
2715                         ID=$(__h2elan $1)
2716                 else
2717                         ID=`echo $1 | sed 's/[^0-9]*//g'`
2718                 fi
2719                 echo $ID"@elan"
2720         fi
2721 }
2722 declare -fx h2elan
2723
2724 h2o2ib() {
2725         h2name_or_ip "$1" "o2ib"
2726 }
2727 declare -fx h2o2ib
2728
2729 # This enables variables in cfg/"setup".sh files to support the pdsh HOSTLIST
2730 # expressions format. As a bonus we can then just pass in those variables
2731 # to pdsh. What this function does is take a HOSTLIST type string and
2732 # expand it into a space deliminated list for us.
2733 hostlist_expand() {
2734     local hostlist=$1
2735     local offset=$2
2736     local myList
2737     local item
2738     local list
2739
2740     [ -z "$hostlist" ] && return
2741
2742     # Translate the case of [..],..,[..] to [..] .. [..]
2743     list="${hostlist/],/] }"
2744     front=${list%%[*}
2745     [[ "$front" == *,* ]] && {
2746         new="${list%,*} "
2747         old="${list%,*},"
2748         list=${list/${old}/${new}}
2749     }
2750
2751     for item in $list; do
2752         # Test if we have any []'s at all
2753         if [ "$item" != "${item/\[/}" ]; then {
2754             # Expand the [*] into list
2755             name=${item%%[*}
2756             back=${item#*]}
2757
2758             if [ "$name" != "$item" ]; then
2759                 group=${item#$name[*}
2760                 group=${group%%]*}
2761
2762                 for range in ${group//,/ }; do
2763                     begin=${range%-*}
2764                     end=${range#*-}
2765
2766                     # Number of leading zeros
2767                     padlen=${#begin}
2768                     padlen2=${#end}
2769                     end=$(echo $end | sed 's/0*//')
2770                     [[ -z "$end" ]] && end=0
2771                     [[ $padlen2 -gt $padlen ]] && {
2772                         [[ $padlen2 -eq ${#end} ]] && padlen2=0
2773                         padlen=$padlen2
2774                     }
2775                     begin=$(echo $begin | sed 's/0*//')
2776                     [ -z $begin ] && begin=0
2777
2778                     for num in $(seq -f "%0${padlen}g" $begin $end); do
2779                         value="${name#*,}${num}${back}"
2780                         [ "$value" != "${value/\[/}" ] && {
2781                             value=$(hostlist_expand "$value")
2782                         }
2783                         myList="$myList $value"
2784                     done
2785                 done
2786             fi
2787         } else {
2788             myList="$myList $item"
2789         } fi
2790     done
2791     myList=${myList//,/ }
2792     myList=${myList:1} # Remove first character which is a space
2793
2794     # Filter any duplicates without sorting
2795     list="$myList "
2796     myList="${list%% *}"
2797
2798     while [[ "$list" != ${myList##* } ]]; do
2799         list=${list//${list%% *} /}
2800         myList="$myList ${list%% *}"
2801     done
2802     myList="${myList%* }";
2803
2804     # We can select an object at an offset in the list
2805     [ $# -eq 2 ] && {
2806         cnt=0
2807         for item in $myList; do
2808             let cnt=cnt+1
2809             [ $cnt -eq $offset ] && {
2810                 myList=$item
2811             }
2812         done
2813         [ $(get_node_count $myList) -ne 1 ] && myList=""
2814     }
2815     echo $myList
2816 }
2817
2818 facet_host() {
2819         local facet=$1
2820         local varname
2821
2822         [ "$facet" == client ] && echo -n $HOSTNAME && return
2823         varname=${facet}_HOST
2824         if [ -z "${!varname}" ]; then
2825                 if [ "${facet:0:3}" == "ost" ]; then
2826                         local fh=${facet%failover}_HOST
2827                         eval export ${facet}_HOST=${!fh}
2828                         if [ -z "${!varname}" ]; then
2829                                 eval export ${facet}_HOST=${ost_HOST}
2830                         fi
2831                 elif [ "${facet:0:3}" == "mdt" -o \
2832                         "${facet:0:3}" == "mds" -o \
2833                         "${facet:0:3}" == "mgs" ]; then
2834                         eval export ${facet}_HOST=${mds_HOST}
2835                 fi
2836         fi
2837         echo -n ${!varname}
2838 }
2839
2840 facet_failover_host() {
2841         local facet=$1
2842         local varname
2843
2844         var=${facet}failover_HOST
2845         if [ -n "${!var}" ]; then
2846                 echo ${!var}
2847                 return
2848         fi
2849
2850         if [ "${facet:0:3}" == "mdt" -o "${facet:0:3}" == "mds" -o \
2851              "${facet:0:3}" == "mgs" ]; then
2852
2853                 eval export ${facet}failover_host=${mds_HOST}
2854                 echo ${mds_HOST}
2855                 return
2856         fi
2857
2858         if [[ $facet == ost* ]]; then
2859                 eval export ${facet}failover_host=${ost_HOST}
2860                 echo ${ost_HOST}
2861                 return
2862         fi
2863 }
2864
2865 facet_active() {
2866     local facet=$1
2867     local activevar=${facet}active
2868
2869     if [ -f $TMP/${facet}active ] ; then
2870         source $TMP/${facet}active
2871     fi
2872
2873     active=${!activevar}
2874     if [ -z "$active" ] ; then
2875         echo -n ${facet}
2876     else
2877         echo -n ${active}
2878     fi
2879 }
2880
2881 facet_active_host() {
2882         facet_host $(facet_active $1)
2883 }
2884
2885 # Get the passive failover partner host of facet.
2886 facet_passive_host() {
2887         local facet=$1
2888         [[ $facet = client ]] && return
2889
2890         local host=${facet}_HOST
2891         local failover_host=${facet}failover_HOST
2892         local active_host=$(facet_active_host $facet)
2893
2894         [[ -z ${!failover_host} || ${!failover_host} = ${!host} ]] && return
2895
2896         if [[ $active_host = ${!host} ]]; then
2897                 echo -n ${!failover_host}
2898         else
2899                 echo -n ${!host}
2900         fi
2901 }
2902
2903 change_active() {
2904     local facetlist=$1
2905     local facet
2906
2907     facetlist=$(exclude_items_from_list $facetlist mgs)
2908
2909     for facet in ${facetlist//,/ }; do
2910     local failover=${facet}failover
2911     local host=`facet_host $failover`
2912     [ -z "$host" ] && return
2913
2914     local curactive=`facet_active $facet`
2915     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
2916         eval export ${facet}active=$facet
2917     else
2918         eval export ${facet}active=$failover
2919     fi
2920     # save the active host for this facet
2921     local activevar=${facet}active
2922     echo "$activevar=${!activevar}" > $TMP/$activevar
2923     [[ $facet = mds1 ]] && combined_mgs_mds && \
2924         echo "mgsactive=${!activevar}" > $TMP/mgsactive
2925     local TO=`facet_active_host $facet`
2926     echo "Failover $facet to $TO"
2927     done
2928 }
2929
2930 do_node() {
2931     local verbose=false
2932     # do not stripe off hostname if verbose, bug 19215
2933     if [ x$1 = x--verbose ]; then
2934         shift
2935         verbose=true
2936     fi
2937
2938     local HOST=$1
2939     shift
2940     local myPDSH=$PDSH
2941     if [ "$HOST" = "$HOSTNAME" ]; then
2942         myPDSH="no_dsh"
2943     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
2944         echo "cannot run remote command on $HOST with $myPDSH"
2945         return 128
2946     fi
2947     if $VERBOSE; then
2948         echo "CMD: $HOST $@" >&2
2949         $myPDSH $HOST "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
2950     fi
2951
2952     if [ "$myPDSH" = "rsh" ]; then
2953 # we need this because rsh does not return exit code of an executed command
2954         local command_status="$TMP/cs"
2955         rsh $HOST ":> $command_status"
2956         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
2957                     cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
2958                     echo command failed >$command_status"
2959         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
2960         return 0
2961     fi
2962
2963     if $verbose ; then
2964         # print HOSTNAME for myPDSH="no_dsh"
2965         if [[ $myPDSH = no_dsh ]]; then
2966             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
2967         else
2968             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
2969         fi
2970     else
2971         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
2972     fi
2973     return ${PIPESTATUS[0]}
2974 }
2975
2976 do_nodev() {
2977     do_node --verbose "$@"
2978 }
2979
2980 single_local_node () {
2981    [ "$1" = "$HOSTNAME" ]
2982 }
2983
2984 # Outputs environment variable assignments that should be passed to remote nodes
2985 get_env_vars() {
2986         local var
2987         local value
2988         local facets=$(get_facets)
2989         local facet
2990
2991         for var in ${!MODOPTS_*}; do
2992                 value=${!var//\"/\\\"}
2993                 echo -n " ${var}=\"$value\""
2994         done
2995
2996         for facet in ${facets//,/ }; do
2997                 var=${facet}_FSTYPE
2998                 if [ -n "${!var}" ]; then
2999                         echo -n " $var=${!var}"
3000                 fi
3001         done
3002
3003         for var in MGSFSTYPE MDSFSTYPE OSTFSTYPE; do
3004                 if [ -n "${!var}" ]; then
3005                         echo -n " $var=${!var}"
3006                 fi
3007         done
3008
3009         for var in VERBOSE; do
3010                 if [ -n "${!var}" ]; then
3011                         echo -n " $var=${!var}"
3012                 fi
3013         done
3014
3015         if [ -n "$FSTYPE" ]; then
3016                 echo -n " FSTYPE=$FSTYPE"
3017         fi
3018
3019         for var in LNETLND NETTYPE; do
3020                 if [ -n "${!var}" ]; then
3021                         echo -n " $var=${!var}"
3022                 fi
3023         done
3024 }
3025
3026 do_nodes() {
3027     local verbose=false
3028     # do not stripe off hostname if verbose, bug 19215
3029     if [ x$1 = x--verbose ]; then
3030         shift
3031         verbose=true
3032     fi
3033
3034     local rnodes=$1
3035     shift
3036
3037     if single_local_node $rnodes; then
3038         if $verbose; then
3039            do_nodev $rnodes "$@"
3040         else
3041            do_node $rnodes "$@"
3042         fi
3043         return $?
3044     fi
3045
3046     # This is part from do_node
3047     local myPDSH=$PDSH
3048
3049     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
3050         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
3051
3052     export FANOUT=$(get_node_count "${rnodes//,/ }")
3053     if $VERBOSE; then
3054         echo "CMD: $rnodes $@" >&2
3055         $myPDSH $rnodes "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
3056     fi
3057
3058     # do not replace anything from pdsh output if -N is used
3059     # -N     Disable hostname: prefix on lines of output.
3060     if $verbose || [[ $myPDSH = *-N* ]]; then
3061         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")"
3062     else
3063         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")" | sed -re "s/^[^:]*: //g"
3064     fi
3065     return ${PIPESTATUS[0]}
3066 }
3067
3068 ##
3069 # Execute commands on a single service's host
3070 #
3071 # The \a facet (service) may be on a local or remote node, which is
3072 # determined at the time the command is run.
3073 #
3074 # usage: do_facet $facet command [arg ...]
3075 do_facet() {
3076         local facet=$1
3077         shift
3078         local HOST=$(facet_active_host $facet)
3079         [ -z $HOST ] && echo "No host defined for facet ${facet}" && exit 1
3080         do_node $HOST "$@"
3081 }
3082
3083 # Function: do_facet_random_file $FACET $FILE $SIZE
3084 # Creates FILE with random content on the given FACET of given SIZE
3085
3086 do_facet_random_file() {
3087         local facet="$1"
3088         local fpath="$2"
3089         local fsize="$3"
3090         local cmd="dd if=/dev/urandom of='$fpath' bs=$fsize count=1"
3091         do_facet $facet "$cmd 2>/dev/null"
3092 }
3093
3094 do_facet_create_file() {
3095         local facet="$1"
3096         local fpath="$2"
3097         local fsize="$3"
3098         local cmd="dd if=/dev/zero of='$fpath' bs=$fsize count=1"
3099         do_facet $facet "$cmd 2>/dev/null"
3100 }
3101
3102 do_nodesv() {
3103     do_nodes --verbose "$@"
3104 }
3105
3106 add() {
3107         local facet=$1
3108         shift
3109         # make sure its not already running
3110         stop ${facet} -f
3111         rm -f $TMP/${facet}active
3112         [[ $facet = mds1 ]] && combined_mgs_mds && rm -f $TMP/mgsactive
3113         do_facet ${facet} $MKFS $* || return ${PIPESTATUS[0]}
3114
3115         if [[ $(facet_fstype $facet) == zfs ]]; then
3116                 #
3117                 # After formatting a ZFS target, "cachefile=none" property will
3118                 # be set on the ZFS storage pool so that the pool is not
3119                 # automatically imported on system startup. And then the pool
3120                 # will be exported so as to leave the importing and exporting
3121                 # operations handled by mount_facet() and stop() separately.
3122                 #
3123                 refresh_partition_table $facet $(facet_vdevice $facet)
3124                 disable_zpool_cache $facet
3125                 export_zpool $facet
3126         fi
3127 }
3128
3129 # Device formatted as ost
3130 ostdevname() {
3131         local num=$1
3132         local DEVNAME=OSTDEV$num
3133
3134         local fstype=$(facet_fstype ost$num)
3135
3136         case $fstype in
3137                 ldiskfs )
3138                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
3139                         eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
3140                 zfs )
3141                         #try $OSTZFSDEVn - independent of vdev
3142                         DEVNAME=OSTZFSDEV$num
3143                         eval DEVPTR=${!DEVNAME:=${FSNAME}-ost${num}/ost${num}};;
3144                 * )
3145                         error "unknown fstype!";;
3146         esac
3147
3148     echo -n $DEVPTR
3149 }
3150
3151 # Physical device location of data
3152 ostvdevname() {
3153         local num=$1
3154         local DEVNAME
3155         local VDEVPTR
3156
3157         local fstype=$(facet_fstype ost$num)
3158
3159         case $fstype in
3160                 ldiskfs )
3161                         # vdevs are not supported by ldiskfs
3162                         eval VDEVPTR="";;
3163                 zfs )
3164                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE{n}
3165                         # Device formatted by zfs
3166                         DEVNAME=OSTDEV$num
3167                         eval VDEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
3168                 * )
3169                         error "unknown fstype!";;
3170         esac
3171
3172         echo -n $VDEVPTR
3173 }
3174
3175 # Logical device formatted for lustre
3176 mdsdevname() {
3177         local num=$1
3178         local DEVNAME=MDSDEV$num
3179
3180         local fstype=$(facet_fstype mds$num)
3181
3182         case $fstype in
3183                 ldiskfs )
3184                         #if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
3185                         eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
3186                 zfs )
3187                         # try $MDSZFSDEVn - independent of vdev
3188                         DEVNAME=MDSZFSDEV$num
3189                         eval DEVPTR=${!DEVNAME:=${FSNAME}-mdt${num}/mdt${num}};;
3190                 * )
3191                         error "unknown fstype!";;
3192         esac
3193
3194         echo -n $DEVPTR
3195 }
3196
3197 # Physical location of data
3198 mdsvdevname() {
3199         local VDEVPTR=""
3200         local num=$1
3201         local fstype=$(facet_fstype mds$num)
3202
3203         case $fstype in
3204                 ldiskfs )
3205                         # vdevs are not supported by ldiskfs
3206                         eval VDEVPTR="";;
3207                 zfs )
3208                         # if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
3209                         # Device formatted by ZFS
3210                         local DEVNAME=MDSDEV$num
3211                         eval VDEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
3212                 * )
3213                         error "unknown fstype!";;
3214         esac
3215
3216         echo -n $VDEVPTR
3217 }
3218
3219 mgsdevname() {
3220         local DEVPTR
3221         local fstype=$(facet_fstype mgs)
3222
3223         case $fstype in
3224         ldiskfs )
3225                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3226                    ( [ -z "$MGSDEV" ] || [ $MGSDEV = $(mdsdevname 1) ] ); then
3227                         DEVPTR=$(mdsdevname 1)
3228                 else
3229                         DEVPTR=$MGSDEV
3230                 fi;;
3231         zfs )
3232                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3233                     ( [ -z "$MGSZFSDEV" ] &&
3234                         [ -z "$MGSDEV" -o "$MGSDEV" = $(mdsvdevname 1) ] ); then
3235                         DEVPTR=$(mdsdevname 1)
3236                 else
3237                         DEVPTR=${MGSZFSDEV:-${FSNAME}-mgs/mgs}
3238                 fi;;
3239         * )
3240                 error "unknown fstype!";;
3241         esac
3242
3243         echo -n $DEVPTR
3244 }
3245
3246 mgsvdevname() {
3247         local VDEVPTR=""
3248
3249         local fstype=$(facet_fstype mgs)
3250
3251         case $fstype in
3252         ldiskfs )
3253                 # vdevs are not supported by ldiskfs
3254                 ;;
3255         zfs )
3256                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3257                    ( [ -z "$MGSDEV" ] &&
3258                        [ -z "$MGSZFSDEV" -o "$MGSZFSDEV" = $(mdsdevname 1) ]); then
3259                         VDEVPTR=$(mdsvdevname 1)
3260                 elif [ -n "$MGSDEV" ]; then
3261                         VDEVPTR=$MGSDEV
3262                 fi;;
3263         * )
3264                 error "unknown fstype!";;
3265         esac
3266
3267         echo -n $VDEVPTR
3268 }
3269
3270 facet_mntpt () {
3271     local facet=$1
3272     [[ $facet = mgs ]] && combined_mgs_mds && facet="mds1"
3273
3274     local var=${facet}_MOUNT
3275     eval mntpt=${!var:-${MOUNT}-$facet}
3276
3277     echo -n $mntpt
3278 }
3279
3280 mount_ldiskfs() {
3281         local facet=$1
3282         local dev=$(facet_device $facet)
3283         local mnt=${2:-$(facet_mntpt $facet)}
3284         local opts
3285
3286         if ! do_facet $facet test -b $dev; then
3287                 opts="-o loop"
3288         fi
3289         do_facet $facet mount -t ldiskfs $opts $dev $mnt
3290 }
3291
3292 unmount_ldiskfs() {
3293         local facet=$1
3294         local dev=$(facet_device $facet)
3295         local mnt=${2:-$(facet_mntpt $facet)}
3296
3297         do_facet $facet $UMOUNT $mnt
3298 }
3299
3300 var_name() {
3301         echo -n "$1" | tr -c '[:alnum:]\n' '_'
3302 }
3303
3304 mount_zfs() {
3305         local facet=$1
3306         local ds=$(facet_device $facet)
3307         local mnt=${2:-$(facet_mntpt $facet)}
3308         local canmnt
3309         local mntpt
3310
3311         import_zpool $facet
3312         canmnt=$(do_facet $facet $ZFS get -H -o value canmount $ds)
3313         mntpt=$(do_facet $facet $ZFS get -H -o value mountpoint $ds)
3314         do_facet $facet $ZFS set canmount=noauto $ds
3315         #
3316         # The "legacy" mount method is used here because "zfs unmount $mnt"
3317         # calls stat(2) on $mnt/../*, which may include $MOUNT.  If certain
3318         # targets are not available at the time, the stat(2) on $MOUNT will
3319         # hang.
3320         #
3321         do_facet $facet $ZFS set mountpoint=legacy $ds
3322         do_facet $facet mount -t zfs $ds $mnt
3323         eval export mz_$(var_name ${facet}_$ds)_canmount=$canmnt
3324         eval export mz_$(var_name ${facet}_$ds)_mountpoint=$mntpt
3325 }
3326
3327 unmount_zfs() {
3328         local facet=$1
3329         local ds=$(facet_device $facet)
3330         local mnt=${2:-$(facet_mntpt $facet)}
3331         local var_mntpt=mz_$(var_name ${facet}_$ds)_mountpoint
3332         local var_canmnt=mz_$(var_name ${facet}_$ds)_canmount
3333         local mntpt=${!var_mntpt}
3334         local canmnt=${!var_canmnt}
3335
3336         unset $var_mntpt
3337         unset $var_canmnt
3338         do_facet $facet umount $mnt
3339         do_facet $facet $ZFS set mountpoint=$mntpt $ds
3340         do_facet $facet $ZFS set canmount=$canmnt $ds
3341         export_zpool $facet
3342 }
3343
3344 mount_fstype() {
3345         local facet=$1
3346         local mnt=$2
3347         local fstype=$(facet_fstype $facet)
3348
3349         mount_$fstype $facet $mnt
3350 }
3351
3352 unmount_fstype() {
3353         local facet=$1
3354         local mnt=$2
3355         local fstype=$(facet_fstype $facet)
3356
3357         unmount_$fstype $facet $mnt
3358 }
3359
3360 ########
3361 ## MountConf setup
3362
3363 stopall() {
3364     # make sure we are using the primary server, so test-framework will
3365     # be able to clean up properly.
3366     activemds=`facet_active mds1`
3367     if [ $activemds != "mds1" ]; then
3368         fail mds1
3369     fi
3370
3371     local clients=$CLIENTS
3372     [ -z $clients ] && clients=$(hostname)
3373
3374     zconf_umount_clients $clients $MOUNT "$*" || true
3375     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
3376
3377     [ -n "$CLIENTONLY" ] && return
3378
3379     # The add fn does rm ${facet}active file, this would be enough
3380     # if we use do_facet <facet> only after the facet added, but
3381     # currently we use do_facet mds in local.sh
3382     for num in `seq $MDSCOUNT`; do
3383         stop mds$num -f
3384         rm -f ${TMP}/mds${num}active
3385     done
3386     combined_mgs_mds && rm -f $TMP/mgsactive
3387
3388     for num in `seq $OSTCOUNT`; do
3389         stop ost$num -f
3390         rm -f $TMP/ost${num}active
3391     done
3392
3393     if ! combined_mgs_mds ; then
3394         stop mgs
3395     fi
3396
3397     return 0
3398 }
3399
3400 cleanup_echo_devs () {
3401         trap 0
3402         local dev
3403         local devs=$($LCTL dl | grep echo | awk '{print $4}')
3404
3405         for dev in $devs; do
3406                 $LCTL --device $dev cleanup
3407                 $LCTL --device $dev detach
3408         done
3409 }
3410
3411 cleanupall() {
3412     nfs_client_mode && return
3413         cifs_client_mode && return
3414
3415     stopall $*
3416     cleanup_echo_devs
3417
3418     unload_modules
3419     cleanup_gss
3420 }
3421
3422 combined_mgs_mds () {
3423         [[ "$(mdsdevname 1)" = "$(mgsdevname)" ]] &&
3424                 [[ "$(facet_host mds1)" = "$(facet_host mgs)" ]]
3425 }
3426
3427 lower() {
3428         echo -n "$1" | tr '[:upper:]' '[:lower:]'
3429 }
3430
3431 upper() {
3432         echo -n "$1" | tr '[:lower:]' '[:upper:]'
3433 }
3434
3435 mkfs_opts() {
3436         local facet=$1
3437         local dev=$2
3438         local fsname=${3:-"$FSNAME"}
3439         local type=$(facet_type $facet)
3440         local index=$(facet_index $facet)
3441         local fstype=$(facet_fstype $facet)
3442         local host=$(facet_host $facet)
3443         local opts
3444         local fs_mkfs_opts
3445         local var
3446
3447         if [ $type == MGS ] || ( [ $type == MDS ] &&
3448                                  [ "$dev" == $(mgsdevname) ] &&
3449                                  [ "$host" == "$(facet_host mgs)" ] ); then
3450                 opts="--mgs"
3451         else
3452                 opts="--mgsnode=$MGSNID"
3453         fi
3454
3455         if [ $type != MGS ]; then
3456                 opts+=" --fsname=$fsname --$(lower ${type/MDS/MDT}) \
3457                         --index=$index"
3458         fi
3459
3460         var=${facet}failover_HOST
3461         if [ -n "${!var}" ] && [ ${!var} != $(facet_host $facet) ]; then
3462                 opts+=" --failnode=$(h2$NETTYPE ${!var})"
3463         fi
3464
3465         opts+=${TIMEOUT:+" --param=sys.timeout=$TIMEOUT"}
3466         opts+=${LDLM_TIMEOUT:+" --param=sys.ldlm_timeout=$LDLM_TIMEOUT"}
3467
3468         if [ $type == MDS ]; then
3469                 opts+=${MDSCAPA:+" --param-mdt.capa=$MDSCAPA"}
3470                 opts+=${STRIPE_BYTES:+" --param=lov.stripesize=$STRIPE_BYTES"}
3471                 opts+=${STRIPES_PER_OBJ:+" --param=lov.stripecount=$STRIPES_PER_OBJ"}
3472                 opts+=${L_GETIDENTITY:+" --param=mdt.identity_upcall=$L_GETIDENTITY"}
3473
3474                 if [ $fstype == ldiskfs ]; then
3475                         # Check for wide striping
3476                         if [ $OSTCOUNT -gt 160 ]; then
3477                                 MDSJOURNALSIZE=${MDSJOURNALSIZE:-4096}
3478                                 fs_mkfs_opts+="-O large_xattr"
3479                         fi
3480
3481                         var=${facet}_JRN
3482                         if [ -n "${!var}" ]; then
3483                                 fs_mkfs_opts+=" -J device=${!var}"
3484                         else
3485                                 fs_mkfs_opts+=${MDSJOURNALSIZE:+" -J size=$MDSJOURNALSIZE"}
3486                         fi
3487                         fs_mkfs_opts+=${MDSISIZE:+" -i $MDSISIZE"}
3488                 fi
3489         fi
3490
3491         if [ $type == OST ]; then
3492                 opts+=${OSSCAPA:+" --param=ost.capa=$OSSCAPA"}
3493
3494                 if [ $fstype == ldiskfs ]; then
3495                         var=${facet}_JRN
3496                         if [ -n "${!var}" ]; then
3497                                 fs_mkfs_opts+=" -J device=${!var}"
3498                         else
3499                                 fs_mkfs_opts+=${OSTJOURNALSIZE:+" -J size=$OSTJOURNALSIZE"}
3500                         fi
3501                 fi
3502         fi
3503
3504         opts+=" --backfstype=$fstype"
3505
3506         var=${type}SIZE
3507         if [ -n "${!var}" ]; then
3508                 opts+=" --device-size=${!var}"
3509         fi
3510
3511         var=$(upper $fstype)_MKFS_OPTS
3512         fs_mkfs_opts+=${!var:+" ${!var}"}
3513
3514         var=${type}_FS_MKFS_OPTS
3515         fs_mkfs_opts+=${!var:+" ${!var}"}
3516
3517         if [ -n "${fs_mkfs_opts## }" ]; then
3518                 opts+=" --mkfsoptions=\\\"${fs_mkfs_opts## }\\\""
3519         fi
3520
3521         var=${type}OPT
3522         opts+=${!var:+" ${!var}"}
3523
3524         echo -n "$opts"
3525 }
3526
3527 check_ost_indices() {
3528         local index_count=${#OST_INDICES[@]}
3529         [[ $index_count -eq 0 || $OSTCOUNT -le $index_count ]] && return 0
3530
3531         # OST count is greater than the index count in $OST_INDEX_LIST.
3532         # We need check whether there are duplicate indices.
3533         local i
3534         local j
3535         local index
3536         for i in $(seq $((index_count + 1)) $OSTCOUNT); do
3537                 index=$(facet_index ost$i)
3538                 for j in $(seq 0 $((index_count - 1))); do
3539                         [[ $index -ne ${OST_INDICES[j]} ]] ||
3540                         error "ost$i has the same index $index as ost$((j+1))"
3541                 done
3542         done
3543 }
3544
3545 format_mgs() {
3546         local quiet
3547
3548         if ! $VERBOSE; then
3549                 quiet=yes
3550         fi
3551         echo "Format mgs: $(mgsdevname)"
3552         reformat_external_journal mgs
3553         add mgs $(mkfs_opts mgs $(mgsdevname)) --reformat \
3554                 $(mgsdevname) $(mgsvdevname) ${quiet:+>/dev/null} || exit 10
3555 }
3556
3557 format_mdt() {
3558         local num=$1
3559         local quiet
3560
3561         if ! $VERBOSE; then
3562                 quiet=yes
3563         fi
3564         echo "Format mds$num: $(mdsdevname $num)"
3565         reformat_external_journal mds$num
3566         add mds$num $(mkfs_opts mds$num $(mdsdevname ${num})) \
3567                 --reformat $(mdsdevname $num) $(mdsvdevname $num) \
3568                 ${quiet:+>/dev/null} || exit 10
3569 }
3570
3571 format_ost() {
3572         local num=$1
3573
3574         if ! $VERBOSE; then
3575                 quiet=yes
3576         fi
3577         echo "Format ost$num: $(ostdevname $num)"
3578         reformat_external_journal ost$num
3579         add ost$num $(mkfs_opts ost$num $(ostdevname ${num})) \
3580                 --reformat $(ostdevname $num) $(ostvdevname ${num}) \
3581                 ${quiet:+>/dev/null} || exit 10
3582 }
3583
3584 formatall() {
3585         stopall
3586         # Set hostid for ZFS/SPL zpool import protection
3587         # (Assumes MDS version is also OSS version)
3588         if [ $(lustre_version_code $SINGLEMDS) -ge $(version_code 2.8.54) ];
3589         then
3590             do_rpc_nodes "$(comma_list $(remote_nodes_list))" set_hostid
3591         fi
3592
3593         # We need ldiskfs here, may as well load them all
3594         load_modules
3595         [ -n "$CLIENTONLY" ] && return
3596         echo Formatting mgs, mds, osts
3597         if ! combined_mgs_mds ; then
3598                 format_mgs
3599         fi
3600
3601         for num in $(seq $MDSCOUNT); do
3602                 format_mdt $num
3603         done
3604
3605         export OST_INDICES=($(hostlist_expand "$OST_INDEX_LIST"))
3606         check_ost_indices
3607         for num in $(seq $OSTCOUNT); do
3608                 format_ost $num
3609         done
3610 }
3611
3612 mount_client() {
3613     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
3614 }
3615
3616 umount_client() {
3617     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
3618 }
3619
3620 # return value:
3621 # 0: success, the old identity set already.
3622 # 1: success, the old identity does not set.
3623 # 2: fail.
3624 switch_identity() {
3625     local num=$1
3626     local switch=$2
3627     local j=`expr $num - 1`
3628     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
3629
3630     if [ -z "$MDT" ]; then
3631         return 2
3632     fi
3633
3634     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
3635
3636     if $switch; then
3637         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
3638     else
3639         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
3640     fi
3641
3642     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush=-1"
3643
3644     if [ $old = "NONE" ]; then
3645         return 1
3646     else
3647         return 0
3648     fi
3649 }
3650
3651 remount_client()
3652 {
3653         zconf_umount `hostname` $1 || error "umount failed"
3654         zconf_mount `hostname` $1 || error "mount failed"
3655 }
3656
3657 writeconf_facet() {
3658         local facet=$1
3659         local dev=$2
3660
3661         stop ${facet} -f
3662         rm -f $TMP/${facet}active
3663         do_facet ${facet} "$TUNEFS --quiet --writeconf $dev" || return 1
3664         return 0
3665 }
3666
3667 writeconf_all () {
3668         local mdt_count=${1:-$MDSCOUNT}
3669         local ost_count=${2:-$OSTCOUNT}
3670         local rc=0
3671
3672         for num in $(seq $mdt_count); do
3673                 DEVNAME=$(mdsdevname $num)
3674                 writeconf_facet mds$num $DEVNAME || rc=$?
3675         done
3676
3677         for num in $(seq $ost_count); do
3678                 DEVNAME=$(ostdevname $num)
3679                 writeconf_facet ost$num $DEVNAME || rc=$?
3680         done
3681         return $rc
3682 }
3683
3684 setupall() {
3685         nfs_client_mode && return
3686         cifs_client_mode && return
3687
3688         sanity_mount_check || error "environments are insane!"
3689
3690         load_modules
3691
3692         if [ -z "$CLIENTONLY" ]; then
3693                 echo Setup mgs, mdt, osts
3694                 echo $WRITECONF | grep -q "writeconf" && writeconf_all
3695                 if ! combined_mgs_mds ; then
3696                         start mgs $(mgsdevname) $MGS_MOUNT_OPTS
3697                 fi
3698
3699         for num in `seq $MDSCOUNT`; do
3700             DEVNAME=$(mdsdevname $num)
3701             start mds$num $DEVNAME $MDS_MOUNT_OPTS
3702
3703             # We started mds, now we should set failover variables properly.
3704             # Set mds${num}failover_HOST if it is not set (the default failnode).
3705             local varname=mds${num}failover_HOST
3706             if [ -z "${!varname}" ]; then
3707                 eval mds${num}failover_HOST=$(facet_host mds$num)
3708             fi
3709
3710             if [ $IDENTITY_UPCALL != "default" ]; then
3711                 switch_identity $num $IDENTITY_UPCALL
3712             fi
3713         done
3714         for num in `seq $OSTCOUNT`; do
3715             DEVNAME=$(ostdevname $num)
3716             start ost$num $DEVNAME $OST_MOUNT_OPTS
3717
3718             # We started ost$num, now we should set ost${num}failover variable properly.
3719             # Set ost${num}failover_HOST if it is not set (the default failnode).
3720             varname=ost${num}failover_HOST
3721             if [ -z "${!varname}" ]; then
3722                 eval ost${num}failover_HOST=$(facet_host ost${num})
3723             fi
3724
3725         done
3726     fi
3727
3728     init_gss
3729
3730     # wait a while to allow sptlrpc configuration be propogated to targets,
3731     # only needed when mounting new target devices.
3732     if $GSS; then
3733         sleep 10
3734     fi
3735
3736     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
3737     mount_client $MOUNT
3738     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
3739     clients_up
3740
3741     if [ "$MOUNT_2" ]; then
3742         mount_client $MOUNT2
3743         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
3744     fi
3745
3746     init_param_vars
3747
3748     # by remounting mdt before ost, initial connect from mdt to ost might
3749     # timeout because ost is not ready yet. wait some time to its fully
3750     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
3751     # by a context negotiation rpc with $TIMEOUT.
3752     # FIXME better by monitoring import status.
3753     if $GSS; then
3754         set_flavor_all $SEC
3755         sleep $((TIMEOUT + 5))
3756     else
3757         sleep 5
3758     fi
3759 }
3760
3761 mounted_lustre_filesystems() {
3762         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
3763 }
3764
3765 init_facet_vars () {
3766         [ -n "$CLIENTONLY" ] && return 0
3767         local facet=$1
3768         shift
3769         local device=$1
3770
3771         shift
3772
3773         eval export ${facet}_dev=${device}
3774         eval export ${facet}_opt=\"$@\"
3775
3776         local dev=${facet}_dev
3777
3778         # We need to loop for the label
3779         # in case its not initialized yet.
3780         for wait_time in {0,1,3,5,10}; do
3781
3782                 if [ $wait_time -gt 0 ]; then
3783                         echo "${!dev} not yet initialized,"\
3784                                 "waiting ${wait_time} seconds."
3785                         sleep $wait_time
3786                 fi
3787
3788                 local label=$(devicelabel ${facet} ${!dev})
3789
3790                 # Check to make sure the label does
3791                 # not include ffff at the end of the label.
3792                 # This indicates it has not been initialized yet.
3793
3794                 if [[ $label =~ [f|F]{4}$ ]]; then
3795                         # label is not initialized, unset the result
3796                         # and either try again or fail
3797                         unset label
3798                 else
3799                         break
3800                 fi
3801         done
3802
3803         [ -z "$label" ] && echo no label for ${!dev} && exit 1
3804
3805         eval export ${facet}_svc=${label}
3806
3807         local varname=${facet}failover_HOST
3808         if [ -z "${!varname}" ]; then
3809                 eval export $varname=$(facet_host $facet)
3810         fi
3811
3812         varname=${facet}_HOST
3813         if [ -z "${!varname}" ]; then
3814                 eval export $varname=$(facet_host $facet)
3815         fi
3816
3817         # ${facet}failover_dev is set in cfg file
3818         varname=${facet}failover_dev
3819         if [ -n "${!varname}" ] ; then
3820                 eval export ${facet}failover_dev=${!varname}
3821         else
3822                 eval export ${facet}failover_dev=$device
3823         fi
3824
3825         # get mount point of already mounted device
3826         # is facet_dev is already mounted then use the real
3827         #  mount point of this facet; otherwise use $(facet_mntpt $facet)
3828         # i.e. ${facet}_MOUNT if specified by user or default
3829         local mntpt=$(do_facet ${facet} cat /proc/mounts | \
3830                         awk '"'${!dev}'" == $1 && $3 == "lustre" { print $2 }')
3831         if [ -z $mntpt ]; then
3832                 mntpt=$(facet_mntpt $facet)
3833         fi
3834         eval export ${facet}_MOUNT=$mntpt
3835 }
3836
3837 init_facets_vars () {
3838         local DEVNAME
3839
3840         if ! remote_mds_nodsh; then
3841                 for num in $(seq $MDSCOUNT); do
3842                         DEVNAME=`mdsdevname $num`
3843                         init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
3844                 done
3845         fi
3846
3847         combined_mgs_mds || init_facet_vars mgs $(mgsdevname) $MGS_MOUNT_OPTS
3848
3849         if ! remote_ost_nodsh; then
3850                 for num in $(seq $OSTCOUNT); do
3851                         DEVNAME=$(ostdevname $num)
3852                         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
3853                 done
3854         fi
3855 }
3856
3857 osc_ensure_active () {
3858     local facet=$1
3859     local timeout=$2
3860     local period=0
3861
3862     while [ $period -lt $timeout ]; do
3863         count=$(do_facet $facet "lctl dl | grep ' IN osc ' 2>/dev/null | wc -l")
3864         if [ $count -eq 0 ]; then
3865             break
3866         fi
3867
3868         echo "There are $count OST are inactive, wait $period seconds, and try again"
3869         sleep 3
3870         period=$((period+3))
3871     done
3872
3873     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
3874 }
3875
3876 set_conf_param_and_check() {
3877         local myfacet=$1
3878         local TEST=$2
3879         local PARAM=$3
3880         local ORIG=$(do_facet $myfacet "$TEST")
3881         if [ $# -gt 3 ]; then
3882                 local FINAL=$4
3883         else
3884                 local -i FINAL
3885                 FINAL=$((ORIG + 5))
3886         fi
3887         echo "Setting $PARAM from $ORIG to $FINAL"
3888         do_facet mgs "$LCTL conf_param $PARAM='$FINAL'" ||
3889                 error "conf_param $PARAM failed"
3890
3891         wait_update_facet $myfacet "$TEST" "$FINAL" ||
3892                 error "check $PARAM failed!"
3893 }
3894
3895 init_param_vars () {
3896         TIMEOUT=$(lctl get_param -n timeout)
3897         TIMEOUT=${TIMEOUT:-20}
3898
3899         remote_mds_nodsh && log "Using TIMEOUT=$TIMEOUT" && return 0
3900
3901         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
3902         log "Using TIMEOUT=$TIMEOUT"
3903
3904         osc_ensure_active $SINGLEMDS $TIMEOUT
3905         osc_ensure_active client $TIMEOUT
3906
3907         if [ -n "$(lctl get_param -n mdc.*.connect_flags|grep jobstats)" ]; then
3908                 local current_jobid_var=$($LCTL get_param -n jobid_var)
3909
3910                 if [ $JOBID_VAR = "existing" ]; then
3911                         echo "keeping jobstats as $current_jobid_var"
3912                 elif [ $current_jobid_var != $JOBID_VAR ]; then
3913                         echo "seting jobstats to $JOBID_VAR"
3914
3915                         set_conf_param_and_check client                 \
3916                                 "$LCTL get_param -n jobid_var"          \
3917                                 "$FSNAME.sys.jobid_var" $JOBID_VAR
3918                 fi
3919         else
3920                 echo "jobstats not supported by server"
3921         fi
3922
3923         if [ $QUOTA_AUTO -ne 0 ]; then
3924                 if [ "$ENABLE_QUOTA" ]; then
3925                         echo "enable quota as required"
3926                         setup_quota $MOUNT || return 2
3927                 else
3928                         echo "disable quota as required"
3929                         # $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
3930                 fi
3931         fi
3932         return 0
3933 }
3934
3935 nfs_client_mode () {
3936     if [ "$NFSCLIENT" ]; then
3937         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
3938         local clients=$CLIENTS
3939         [ -z $clients ] && clients=$(hostname)
3940
3941         # FIXME: remove hostname when 19215 fixed
3942         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
3943         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
3944         if [[ ${#nfsexport[@]} -eq 0 ]]; then
3945                 error_exit NFSCLIENT=$NFSCLIENT mode, but no NFS export found!
3946         fi
3947         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
3948         return
3949     fi
3950     return 1
3951 }
3952
3953 cifs_client_mode () {
3954         [ x$CIFSCLIENT = xyes ] &&
3955                 echo "CIFSCLIENT=$CIFSCLIENT mode: setup, cleanup, check config skipped"
3956 }
3957
3958 check_config_client () {
3959     local mntpt=$1
3960
3961     local mounted=$(mount | grep " $mntpt ")
3962     if [ -n "$CLIENTONLY" ]; then
3963         # bug 18021
3964         # CLIENTONLY should not depend on *_HOST settings
3965         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
3966         # in theory someone could create a new,
3967         # client-only config file that assumed lustre was already
3968         # configured and didn't set the MGSNID. If MGSNID is not set,
3969         # then we should use the mgs nid currently being used
3970         # as the default value. bug 18021
3971         [[ x$MGSNID = x ]] &&
3972             MGSNID=${mgc//MGC/}
3973
3974         if [[ x$mgc != xMGC$MGSNID ]]; then
3975             if [ "$mgs_HOST" ]; then
3976                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
3977 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
3978 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
3979             fi
3980         fi
3981         return 0
3982     fi
3983
3984     local myMGS_host=$mgs_HOST
3985     if [ "$NETTYPE" = "ptl" ]; then
3986         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//)
3987     fi
3988
3989     echo Checking config lustre mounted on $mntpt
3990     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
3991     mgshost=$(echo $mgshost | awk -F: '{print $1}')
3992
3993 #    if [ "$mgshost" != "$myMGS_host" ]; then
3994 #            log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
3995 #                   Please use correct config or set mds_HOST correctly!"
3996 #    fi
3997
3998 }
3999
4000 check_config_clients () {
4001         local clients=${CLIENTS:-$HOSTNAME}
4002         local mntpt=$1
4003
4004         nfs_client_mode && return
4005         cifs_client_mode && return
4006
4007         do_rpc_nodes "$clients" check_config_client $mntpt
4008
4009         sanity_mount_check || error "environments are insane!"
4010 }
4011
4012 check_timeout () {
4013     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
4014     local cltimeout=$(lctl get_param -n timeout)
4015     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
4016         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
4017         return 1
4018     fi
4019 }
4020
4021 is_mounted () {
4022     local mntpt=$1
4023     [ -z $mntpt ] && return 1
4024     local mounted=$(mounted_lustre_filesystems)
4025
4026     echo $mounted' ' | grep -w -q $mntpt' '
4027 }
4028
4029 is_empty_dir() {
4030         [ $(find $1 -maxdepth 1 -print | wc -l) = 1 ] && return 0
4031         return 1
4032 }
4033
4034 # empty lustre filesystem may have empty directories lost+found and .lustre
4035 is_empty_fs() {
4036         # exclude .lustre & lost+found
4037         [ $(find $1 -maxdepth 1 -name lost+found -o -name .lustre -prune -o \
4038                 -print | wc -l) = 1 ] || return 1
4039         [ ! -d $1/lost+found ] || is_empty_dir $1/lost+found || return 1
4040         if [ $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.4.0) ]; then
4041                 # exclude .lustre/fid (LU-2780)
4042                 [ $(find $1/.lustre -maxdepth 1 -name fid -prune -o \
4043                         -print | wc -l) = 1 ] || return 1
4044         else
4045                 [ ! -d $1/.lustre ] || is_empty_dir $1/.lustre || return 1
4046         fi
4047         return 0
4048 }
4049
4050 check_and_setup_lustre() {
4051         sanitize_parameters
4052         nfs_client_mode && return
4053         cifs_client_mode && return
4054
4055         local MOUNTED=$(mounted_lustre_filesystems)
4056
4057         local do_check=true
4058         # 1.
4059         # both MOUNT and MOUNT2 are not mounted
4060         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
4061                 [ "$REFORMAT" = "yes" ] && formatall
4062                 # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
4063                 setupall
4064                 is_mounted $MOUNT || error "NAME=$NAME not mounted"
4065                 export I_MOUNTED=yes
4066                 do_check=false
4067     # 2.
4068     # MOUNT2 is mounted
4069     elif is_mounted $MOUNT2; then
4070             # 3.
4071             # MOUNT2 is mounted, while MOUNT_2 is not set
4072             if ! [ "$MOUNT_2" ]; then
4073                 cleanup_mount $MOUNT2
4074                 export I_UMOUNTED2=yes
4075
4076             # 4.
4077             # MOUNT2 is mounted, MOUNT_2 is set
4078             else
4079                 # FIXME: what to do if check_config failed?
4080                 # i.e. if:
4081                 # 1) remote client has mounted other Lustre fs ?
4082                 # 2) it has insane env ?
4083                 # let's try umount MOUNT2 on all clients and mount it again:
4084                 if ! check_config_clients $MOUNT2; then
4085                     cleanup_mount $MOUNT2
4086                     restore_mount $MOUNT2
4087                     export I_MOUNTED2=yes
4088                 fi
4089             fi
4090
4091     # 5.
4092     # MOUNT is mounted MOUNT2 is not mounted
4093     elif [ "$MOUNT_2" ]; then
4094         restore_mount $MOUNT2
4095         export I_MOUNTED2=yes
4096     fi
4097
4098     if $do_check; then
4099         # FIXME: what to do if check_config failed?
4100         # i.e. if:
4101         # 1) remote client has mounted other Lustre fs?
4102         # 2) lustre is mounted on remote_clients atall ?
4103         check_config_clients $MOUNT
4104         init_facets_vars
4105         init_param_vars
4106
4107         set_default_debug_nodes $(comma_list $(nodes_list))
4108     fi
4109
4110         if [ -z "$CLIENTONLY" -a $(lower $OSD_TRACK_DECLARES_LBUG) == 'yes' ]; then
4111                 local facets=""
4112                 [ "$(facet_fstype ost1)" = "ldiskfs" ] &&
4113                         facets="$(get_facets OST)"
4114                 [ "$(facet_fstype mds1)" = "ldiskfs" ] &&
4115                         facets="$facets,$(get_facets MDS)"
4116                 [ "$(facet_fstype mgs)" = "ldiskfs" ] &&
4117                         facets="$facets,mgs"
4118                 local nodes="$(facets_hosts ${facets})"
4119                 if [ -n "$nodes" ] ; then
4120                         do_nodes $nodes "$LCTL set_param \
4121                                  osd-ldiskfs.track_declares_assert=1 || true"
4122                 fi
4123         fi
4124
4125         init_gss
4126         if $GSS; then
4127                 set_flavor_all $SEC
4128         fi
4129
4130         if [ -z "$CLIENTONLY" ]; then
4131                 # Enable remote MDT create for testing
4132                 for num in $(seq $MDSCOUNT); do
4133                         do_facet mds$num \
4134                                 lctl set_param -n mdt.${FSNAME}*.enable_remote_dir=1 \
4135                                         2>/dev/null
4136                 done
4137         fi
4138
4139         if [ "$ONLY" == "setup" ]; then
4140                 exit 0
4141         fi
4142 }
4143
4144 restore_mount () {
4145    local clients=${CLIENTS:-$HOSTNAME}
4146    local mntpt=$1
4147
4148    zconf_mount_clients $clients $mntpt
4149 }
4150
4151 cleanup_mount () {
4152         local clients=${CLIENTS:-$HOSTNAME}
4153         local mntpt=$1
4154
4155         zconf_umount_clients $clients $mntpt
4156 }
4157
4158 cleanup_and_setup_lustre() {
4159     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
4160         lctl set_param debug=0 || true
4161         cleanupall
4162         if [ "$ONLY" == "cleanup" ]; then
4163             exit 0
4164         fi
4165     fi
4166     check_and_setup_lustre
4167 }
4168
4169 # Get all of the server target devices from a given server node and type.
4170 get_mnt_devs() {
4171         local node=$1
4172         local type=$2
4173         local devs
4174         local dev
4175
4176         if [ "$type" == ost ]; then
4177                 devs=$(get_osd_param $node "" mntdev)
4178         else
4179                 devs=$(do_node $node $LCTL get_param -n osd-*.$FSNAME-M*.mntdev)
4180         fi
4181         for dev in $devs; do
4182                 case $dev in
4183                 *loop*) do_node $node "losetup $dev" | \
4184                                 sed -e "s/.*(//" -e "s/).*//" ;;
4185                 *) echo $dev ;;
4186                 esac
4187         done
4188 }
4189
4190 # Get all of the server target devices.
4191 get_svr_devs() {
4192         local node
4193         local i
4194
4195         # Master MDS parameters used by lfsck
4196         MDTNODE=$(facet_active_host $SINGLEMDS)
4197         MDTDEV=$(echo $(get_mnt_devs $MDTNODE mdt) | awk '{print $1}')
4198
4199         # MDT devices
4200         i=0
4201         for node in $(mdts_nodes); do
4202                 MDTDEVS[i]=$(get_mnt_devs $node mdt)
4203                 i=$((i + 1))
4204         done
4205
4206         # OST devices
4207         i=0
4208         for node in $(osts_nodes); do
4209                 OSTDEVS[i]=$(get_mnt_devs $node ost)
4210                 i=$((i + 1))
4211         done
4212 }
4213
4214 # Run e2fsck on MDT or OST device.
4215 run_e2fsck() {
4216         local node=$1
4217         local target_dev=$2
4218         local extra_opts=$3
4219         local cmd="$E2FSCK -d -v -t -t -f $extra_opts $target_dev"
4220         local log=$TMP/e2fsck.log
4221         local rc=0
4222
4223         echo $cmd
4224         do_node $node $cmd 2>&1 | tee $log
4225         rc=${PIPESTATUS[0]}
4226         if [ -n "$(grep "DNE mode isn't supported" $log)" ]; then
4227                 rm -f $log
4228                 if [ $MDSCOUNT -gt 1 ]; then
4229                         skip "DNE mode isn't supported!"
4230                         cleanupall
4231                         exit_status
4232                 else
4233                         error "It's not DNE mode."
4234                 fi
4235         fi
4236         rm -f $log
4237
4238         [ $rc -le $FSCK_MAX_ERR ] ||
4239                 error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
4240
4241         return 0
4242 }
4243
4244 #
4245 # Run resize2fs on MDT or OST device.
4246 #
4247 run_resize2fs() {
4248         local facet=$1
4249         local device=$2
4250         local size=$3
4251         shift 3
4252         local opts="$@"
4253
4254         do_facet $facet "$RESIZE2FS $opts $device $size"
4255 }
4256
4257 # verify a directory is shared among nodes.
4258 check_shared_dir() {
4259         local dir=$1
4260         local list=${2:-$(comma_list $(nodes_list))}
4261
4262         [ -z "$dir" ] && return 1
4263         do_rpc_nodes "$list" check_logdir $dir
4264         check_write_access $dir "$list" || return 1
4265         return 0
4266 }
4267
4268 run_lfsck() {
4269         do_nodes $(comma_list $(mdts_nodes) $(osts_nodes)) \
4270                 $LCTL set_param printk=+lfsck
4271         do_facet $SINGLEMDS "$LCTL lfsck_start -M $FSNAME-MDT0000 -r -A -t all"
4272
4273         for k in $(seq $MDSCOUNT); do
4274                 # wait up to 10+1 minutes for LFSCK to complete
4275                 wait_update_facet --verbose mds${k} "$LCTL get_param -n \
4276                         mdd.$(facet_svc mds${k}).lfsck_layout |
4277                         awk '/^status/ { print \\\$2 }'" "completed" 600 ||
4278                         error "MDS${k} layout isn't the expected 'completed'"
4279                 wait_update_facet --verbose mds${k} "$LCTL get_param -n \
4280                         mdd.$(facet_svc mds${k}).lfsck_namespace |
4281                         awk '/^status/ { print \\\$2 }'" "completed" 60 ||
4282                         error "MDS${k} namespace isn't the expected 'completed'"
4283         done
4284         local rep_mdt=$(do_nodes $(comma_list $(mdts_nodes)) \
4285                         $LCTL get_param -n mdd.$FSNAME-*.lfsck_* |
4286                         awk '/repaired/ { print $2 }' | calc_sum)
4287         local rep_ost=$(do_nodes $(comma_list $(osts_nodes)) \
4288                         $LCTL get_param -n obdfilter.$FSNAME-*.lfsck_* |
4289                         awk '/repaired/ { print $2 }' | calc_sum)
4290         local repaired=$((rep_mdt + rep_ost))
4291         [ $repaired -eq 0 ] ||
4292                 error "lfsck repaired $rep_mdt MDT and $rep_ost OST errors"
4293 }
4294
4295 dump_file_contents() {
4296         local nodes=$1
4297         local dir=$2
4298         local logname=$3
4299         local node
4300
4301         if [ -z "$nodes" -o -z "$dir" -o -z "$logname" ]; then
4302                 error_noexit false \
4303                         "Invalid parameters for dump_file_contents()"
4304                 return 1
4305         fi
4306         for node in ${nodes}; do
4307                 do_node $node "for i in \\\$(find $dir -type f); do
4308                                 echo ====\\\${i}=======================;
4309                                 cat \\\${i};
4310                                 done" >> ${logname}.${node}.log
4311         done
4312 }
4313
4314 dump_command_output() {
4315         local nodes=$1
4316         local cmd=$2
4317         local logname=$3
4318         local node
4319
4320         if [ -z "$nodes" -o -z "$cmd" -o -z "$logname" ]; then
4321                 error_noexit false \
4322                         "Invalid parameters for dump_command_output()"
4323                 return 1
4324         fi
4325
4326         for node in ${nodes}; do
4327                 do_node $node "echo ====${cmd}=======================;
4328                                 $cmd" >> ${logname}.${node}.log
4329         done
4330 }
4331
4332 log_zfs_info() {
4333         local logname=$1
4334
4335         # dump file contents from /proc/spl in case of zfs test
4336         if [ "$(facet_fstype ost1)" = "zfs" ]; then
4337                 dump_file_contents "$(osts_nodes)" "/proc/spl" "${logname}"
4338                 dump_command_output \
4339                         "$(osts_nodes)" "zpool events -v" "${logname}"
4340         fi
4341
4342         if [ "$(facet_fstype $SINGLEMDS)" = "zfs" ]; then
4343                 dump_file_contents "$(mdts_nodes)" "/proc/spl" "${logname}"
4344                 dump_command_output \
4345                         "$(mdts_nodes)" "zpool events -v" "${logname}"
4346         fi
4347 }
4348
4349 check_and_cleanup_lustre() {
4350         if [ "$LFSCK_ALWAYS" = "yes" -a "$TESTSUITE" != "sanity-lfsck" -a \
4351              "$TESTSUITE" != "sanity-scrub" ]; then
4352                 run_lfsck
4353         fi
4354
4355         if is_mounted $MOUNT; then
4356                 if $DO_CLEANUP; then
4357                         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]* ||
4358                                 error "remove sub-test dirs failed"
4359                 else
4360                         echo "skip cleanup"
4361                 fi
4362                 [ "$ENABLE_QUOTA" ] && restore_quota || true
4363         fi
4364
4365         if [ "$I_UMOUNTED2" = "yes" ]; then
4366                 restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
4367         fi
4368
4369         if [ "$I_MOUNTED2" = "yes" ]; then
4370                 cleanup_mount $MOUNT2
4371         fi
4372
4373         if [ "$I_MOUNTED" = "yes" ]; then
4374                 cleanupall -f || error "cleanup failed"
4375                 unset I_MOUNTED
4376         fi
4377 }
4378
4379 #######
4380 # General functions
4381
4382 wait_for_function () {
4383     local quiet=""
4384
4385     # suppress fn both stderr and stdout
4386     if [ "$1" = "--quiet" ]; then
4387         shift
4388         quiet=" > /dev/null 2>&1"
4389
4390     fi
4391
4392     local fn=$1
4393     local max=${2:-900}
4394     local sleep=${3:-5}
4395
4396     local wait=0
4397
4398     while true; do
4399
4400         eval $fn $quiet && return 0
4401
4402         wait=$((wait + sleep))
4403         [ $wait -lt $max ] || return 1
4404         echo waiting $fn, $((max - wait)) secs left ...
4405         sleep $sleep
4406     done
4407 }
4408
4409 check_network() {
4410     local host=$1
4411     local max=$2
4412     local sleep=${3:-5}
4413
4414     echo `date +"%H:%M:%S (%s)"` waiting for $host network $max secs ...
4415     if ! wait_for_function --quiet "ping -c 1 -w 3 $host" $max $sleep ; then
4416         echo "Network not available!"
4417         exit 1
4418     fi
4419
4420     echo `date +"%H:%M:%S (%s)"` network interface is UP
4421 }
4422
4423 no_dsh() {
4424     shift
4425     eval $@
4426 }
4427
4428 # Convert a space-delimited list to a comma-delimited list.  If the input is
4429 # only whitespace, ensure the output is empty (i.e. "") so [ -n $list ] works
4430 comma_list() {
4431         # echo is used to convert newlines to spaces, since it doesn't
4432         # introduce a trailing space as using "tr '\n' ' '" does
4433         echo $(tr -s " " "\n" <<< $* | sort -b -u) | tr ' ' ','
4434 }
4435
4436 list_member () {
4437     local list=$1
4438     local item=$2
4439     echo $list | grep -qw $item
4440 }
4441
4442 # list, excluded are the comma separated lists
4443 exclude_items_from_list () {
4444     local list=$1
4445     local excluded=$2
4446     local item
4447
4448     list=${list//,/ }
4449     for item in ${excluded//,/ }; do
4450         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
4451     done
4452     echo $(comma_list $list)
4453 }
4454
4455 # list, expand  are the comma separated lists
4456 expand_list () {
4457     local list=${1//,/ }
4458     local expand=${2//,/ }
4459     local expanded=
4460
4461     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
4462     echo $(comma_list $expanded)
4463 }
4464
4465 testslist_filter () {
4466     local script=$LUSTRE/tests/${TESTSUITE}.sh
4467
4468     [ -f $script ] || return 0
4469
4470     local start_at=$START_AT
4471     local stop_at=$STOP_AT
4472
4473     local var=${TESTSUITE//-/_}_START_AT
4474     [ x"${!var}" != x ] && start_at=${!var}
4475     var=${TESTSUITE//-/_}_STOP_AT
4476     [ x"${!var}" != x ] && stop_at=${!var}
4477
4478     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
4479         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
4480             /^'${start_at}'$/ {flag = 0}
4481             {if (flag == 1) print $0}
4482             /^'${stop_at}'$/ { flag = 1 }'
4483 }
4484
4485 absolute_path() {
4486     (cd `dirname $1`; echo $PWD/`basename $1`)
4487 }
4488
4489 get_facets () {
4490     local types=${1:-"OST MDS MGS"}
4491
4492     local list=""
4493
4494     for entry in $types; do
4495         local name=$(echo $entry | tr "[:upper:]" "[:lower:]")
4496         local type=$(echo $entry | tr "[:lower:]" "[:upper:]")
4497
4498         case $type in
4499                 MGS ) list="$list $name";;
4500             MDS|OST|AGT ) local count=${type}COUNT
4501                        for ((i=1; i<=${!count}; i++)) do
4502                           list="$list ${name}$i"
4503                       done;;
4504                   * ) error "Invalid facet type"
4505                  exit 1;;
4506         esac
4507     done
4508     echo $(comma_list $list)
4509 }
4510
4511 ##################################
4512 # Adaptive Timeouts funcs
4513
4514 at_is_enabled() {
4515     # only check mds, we assume at_max is the same on all nodes
4516     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
4517     if [ $at_max -eq 0 ]; then
4518         return 1
4519     else
4520         return 0
4521     fi
4522 }
4523
4524 at_get() {
4525     local facet=$1
4526     local at=$2
4527
4528     # suppose that all ost-s have the same $at value set
4529     [ $facet != "ost" ] || facet=ost1
4530
4531     do_facet $facet "lctl get_param -n $at"
4532 }
4533
4534 at_max_get() {
4535     at_get $1 at_max
4536 }
4537
4538 at_min_get() {
4539         at_get $1 at_min
4540 }
4541
4542 at_max_set() {
4543     local at_max=$1
4544     shift
4545
4546     local facet
4547     local hosts
4548     for facet in $@; do
4549         if [ $facet == "ost" ]; then
4550             facet=$(get_facets OST)
4551         elif [ $facet == "mds" ]; then
4552             facet=$(get_facets MDS)
4553         fi
4554         hosts=$(expand_list $hosts $(facets_hosts $facet))
4555     done
4556
4557     do_nodes $hosts lctl set_param at_max=$at_max
4558 }
4559
4560 ##################################
4561 # OBD_FAIL funcs
4562
4563 drop_request() {
4564 # OBD_FAIL_MDS_ALL_REQUEST_NET
4565     RC=0
4566     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
4567     do_facet client "$1" || RC=$?
4568     do_facet $SINGLEMDS lctl set_param fail_loc=0
4569     return $RC
4570 }
4571
4572 drop_reply() {
4573 # OBD_FAIL_MDS_ALL_REPLY_NET
4574         RC=0
4575         do_facet $SINGLEMDS $LCTL set_param fail_loc=0x122
4576         eval "$@" || RC=$?
4577         do_facet $SINGLEMDS $LCTL set_param fail_loc=0
4578         return $RC
4579 }
4580
4581 drop_reint_reply() {
4582 # OBD_FAIL_MDS_REINT_NET_REP
4583         RC=0
4584         do_facet $SINGLEMDS $LCTL set_param fail_loc=0x119
4585         eval "$@" || RC=$?
4586         do_facet $SINGLEMDS $LCTL set_param fail_loc=0
4587         return $RC
4588 }
4589
4590 drop_update_reply() {
4591 # OBD_FAIL_OUT_UPDATE_NET_REP
4592         local index=$1
4593         shift 1
4594         RC=0
4595         do_facet mds${index} lctl set_param fail_loc=0x1701
4596         do_facet client "$@" || RC=$?
4597         do_facet mds${index} lctl set_param fail_loc=0
4598         return $RC
4599 }
4600
4601 pause_bulk() {
4602 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
4603         RC=0
4604
4605         local timeout=${2:-0}
4606         # default is (obd_timeout / 4) if unspecified
4607         echo "timeout is $timeout/$2"
4608         do_facet ost1 lctl set_param fail_val=$timeout fail_loc=0x80000214
4609         do_facet client "$1" || RC=$?
4610         do_facet client "sync"
4611         do_facet ost1 lctl set_param fail_loc=0
4612         return $RC
4613 }
4614
4615 drop_ldlm_cancel() {
4616 #define OBD_FAIL_LDLM_CANCEL_NET                        0x304
4617         local RC=0
4618         local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4619         do_nodes $list lctl set_param fail_loc=0x304
4620
4621         do_facet client "$@" || RC=$?
4622
4623         do_nodes $list lctl set_param fail_loc=0
4624         return $RC
4625 }
4626
4627 drop_bl_callback_once() {
4628         local rc=0
4629         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0
4630 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
4631         do_facet client lctl set_param fail_loc=0x80000305
4632         do_facet client "$@" || rc=$?
4633         do_facet client lctl set_param fail_loc=0
4634         do_facet client lctl set_param fail_val=0
4635         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1
4636         return $rc
4637 }
4638
4639 drop_bl_callback() {
4640         rc=0
4641         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0
4642 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
4643         do_facet client lctl set_param fail_loc=0x305
4644         do_facet client "$@" || rc=$?
4645         do_facet client lctl set_param fail_loc=0
4646         do_facet client lctl set_param fail_val=0
4647         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1
4648         return $rc
4649 }
4650
4651 drop_ldlm_reply() {
4652 #define OBD_FAIL_LDLM_REPLY              0x30c
4653     RC=0
4654     local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4655     do_nodes $list lctl set_param fail_loc=0x30c
4656
4657     do_facet client "$@" || RC=$?
4658
4659     do_nodes $list lctl set_param fail_loc=0
4660     return $RC
4661 }
4662
4663 drop_ldlm_reply_once() {
4664 #define OBD_FAIL_LDLM_REPLY              0x30c
4665     RC=0
4666     local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4667     do_nodes $list lctl set_param fail_loc=0x8000030c
4668
4669     do_facet client "$@" || RC=$?
4670
4671     do_nodes $list lctl set_param fail_loc=0
4672     return $RC
4673 }
4674
4675 clear_failloc() {
4676     facet=$1
4677     pause=$2
4678     sleep $pause
4679     echo "clearing fail_loc on $facet"
4680     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
4681 }
4682
4683 set_nodes_failloc () {
4684         local fv=${3:-0}
4685         do_nodes $(comma_list $1)  lctl set_param fail_val=$fv fail_loc=$2
4686 }
4687
4688 cancel_lru_locks() {
4689         #$LCTL mark "cancel_lru_locks $1 start"
4690         $LCTL set_param -n ldlm.namespaces.*$1*.lru_size=clear
4691         $LCTL get_param ldlm.namespaces.*$1*.lock_unused_count | grep -v '=0'
4692         #$LCTL mark "cancel_lru_locks $1 stop"
4693 }
4694
4695 default_lru_size()
4696 {
4697         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
4698         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
4699         echo "$DEFAULT_LRU_SIZE"
4700 }
4701
4702 lru_resize_enable()
4703 {
4704     lctl set_param ldlm.namespaces.*$1*.lru_size=0
4705 }
4706
4707 lru_resize_disable()
4708 {
4709     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
4710 }
4711
4712 flock_is_enabled()
4713 {
4714         local RC=0
4715         [ -z "$(mount | grep "$MOUNT.*flock" | grep -v noflock)" ] && RC=1
4716         return $RC
4717 }
4718
4719 pgcache_empty() {
4720     local FILE
4721     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
4722         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
4723             echo there is still data in page cache $FILE ?
4724             lctl get_param -n $FILE
4725             return 1
4726         fi
4727     done
4728     return 0
4729 }
4730
4731 debugsave() {
4732         DEBUGSAVE="$(lctl get_param -n debug)"
4733         DEBUGSAVE_SERVER=$(do_facet $SINGLEMDS "$LCTL get_param -n debug")
4734 }
4735
4736 debugrestore() {
4737         [ -n "$DEBUGSAVE" ] &&
4738                 do_nodes $CLIENTS "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\""||
4739                 true
4740         DEBUGSAVE=""
4741
4742         [ -n "$DEBUGSAVE_SERVER" ] &&
4743                 do_nodes $(comma_list $(all_server_nodes)) \
4744                          "$LCTL set_param debug=\\\"${DEBUGSAVE_SERVER}\\\"" ||
4745                          true
4746         DEBUGSAVE_SERVER=""
4747 }
4748
4749 debug_size_save() {
4750     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
4751 }
4752
4753 debug_size_restore() {
4754     [ -n "$DEBUG_SIZE_SAVED" ] && \
4755         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
4756     DEBUG_SIZE_SAVED=""
4757 }
4758
4759 start_full_debug_logging() {
4760     debugsave
4761     debug_size_save
4762
4763     local FULLDEBUG=-1
4764     local DEBUG_SIZE=150
4765
4766     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
4767     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
4768 }
4769
4770 stop_full_debug_logging() {
4771     debug_size_restore
4772     debugrestore
4773 }
4774
4775 # prints bash call stack
4776 print_stack_trace() {
4777         local skip=${1:-1}
4778         echo "  Trace dump:"
4779         for (( i=$skip; i < ${#BASH_LINENO[*]} ; i++ )) ; do
4780                 local src=${BASH_SOURCE[$i]}
4781                 local lineno=${BASH_LINENO[$i-1]}
4782                 local funcname=${FUNCNAME[$i]}
4783                 echo "  = $src:$lineno:$funcname()"
4784         done
4785 }
4786
4787 report_error() {
4788         local TYPE=${TYPE:-"FAIL"}
4789
4790         local dump=true
4791         # do not dump logs if $1=false
4792         if [ "x$1" = "xfalse" ]; then
4793                 shift
4794                 dump=false
4795         fi
4796
4797         log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
4798         (print_stack_trace 2) >&2
4799         mkdir -p $LOGDIR
4800         # We need to dump the logs on all nodes
4801         if $dump; then
4802                 gather_logs $(comma_list $(nodes_list))
4803         fi
4804
4805         debugrestore
4806         [ "$TESTSUITELOG" ] &&
4807                 echo "$TESTSUITE: $TYPE: $TESTNAME $@" >> $TESTSUITELOG
4808         if [ -z "$*" ]; then
4809                 echo "error() without useful message, please fix" > $LOGDIR/err
4810         else
4811                 if [[ `echo $TYPE | grep ^IGNORE` ]]; then
4812                         echo "$@" > $LOGDIR/ignore
4813                 else
4814                         echo "$@" > $LOGDIR/err
4815                 fi
4816         fi
4817
4818         # cleanup the env for failed tests
4819         reset_fail_loc
4820 }
4821
4822 ##################################
4823 # Test interface
4824 ##################################
4825
4826 error_noexit() {
4827         report_error "$@"
4828 }
4829
4830 exit_status () {
4831         local status=0
4832         local log=$TESTSUITELOG
4833
4834         [ -f "$log" ] && grep -q FAIL $log && status=1
4835         exit $status
4836 }
4837
4838 error() {
4839         report_error "$@"
4840         exit 1
4841 }
4842
4843 error_exit() {
4844         report_error "$@"
4845         exit 1
4846 }
4847
4848 # use only if we are ignoring failures for this test, bugno required.
4849 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
4850 # e.g. error_ignore bz5494 "your message" or
4851 # error_ignore LU-5494 "your message"
4852 error_ignore() {
4853         local TYPE="IGNORE ($1)"
4854         shift
4855         report_error "$@"
4856 }
4857
4858 error_and_remount() {
4859         report_error "$@"
4860         remount_client $MOUNT
4861         exit 1
4862 }
4863
4864 # Throw an error if it's not running in vm - usually for performance
4865 # verification
4866 error_not_in_vm() {
4867         local virt=$(running_in_vm)
4868         if [[ -n "$virt" ]]; then
4869                 echo "running in VM '$virt', ignore error"
4870                 error_ignore env=$virt "$@"
4871         else
4872                 error "$@"
4873         fi
4874 }
4875
4876 skip_env () {
4877         $FAIL_ON_SKIP_ENV && error false $@ || skip $@
4878 }
4879
4880 skip() {
4881         echo
4882         log " SKIP: $TESTSUITE $TESTNAME $@"
4883
4884         if [[ -n "$ALWAYS_SKIPPED" ]]; then
4885                 skip_logged $TESTNAME "$@"
4886         else
4887                 mkdir -p $LOGDIR
4888                 echo "$@" > $LOGDIR/skip
4889         fi
4890
4891         [[ -n "$TESTSUITELOG" ]] &&
4892                 echo "$TESTSUITE: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
4893 }
4894
4895 build_test_filter() {
4896     EXCEPT="$EXCEPT $(testslist_filter)"
4897
4898         for O in $ONLY; do
4899                 if [[ $O = [0-9]*-[0-9]* ]]; then
4900                         for num in $(seq $(echo $O | tr '-' ' ')); do
4901                                 eval ONLY_$num=true
4902                         done
4903                 else
4904                         eval ONLY_${O}=true
4905                 fi
4906         done
4907
4908     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
4909         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
4910     [ "$EXCEPT_SLOW" ] && \
4911         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
4912     for E in $EXCEPT; do
4913         eval EXCEPT_${E}=true
4914     done
4915     for E in $ALWAYS_EXCEPT; do
4916         eval EXCEPT_ALWAYS_${E}=true
4917     done
4918     for E in $EXCEPT_SLOW; do
4919         eval EXCEPT_SLOW_${E}=true
4920     done
4921     for G in $GRANT_CHECK_LIST; do
4922         eval GCHECK_ONLY_${G}=true
4923         done
4924 }
4925
4926 basetest() {
4927     if [[ $1 = [a-z]* ]]; then
4928         echo $1
4929     else
4930         echo ${1%%[a-z]*}
4931     fi
4932 }
4933
4934 # print a newline if the last test was skipped
4935 export LAST_SKIPPED=
4936 export ALWAYS_SKIPPED=
4937 #
4938 # Main entry into test-framework. This is called with the name and
4939 # description of a test. The name is used to find the function to run
4940 # the test using "test_$name".
4941 #
4942 # This supports a variety of methods of specifying specific test to
4943 # run or not run.  These need to be documented...
4944 #
4945 run_test() {
4946         assert_DIR
4947
4948         export base=$(basetest $1)
4949         if [ -n "$ONLY" ]; then
4950                 testname=ONLY_$1
4951                 if [ ${!testname}x != x ]; then
4952                         [ -n "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
4953                         run_one_logged $1 "$2"
4954                         return $?
4955                 fi
4956                 testname=ONLY_$base
4957                 if [ ${!testname}x != x ]; then
4958                         [ -n "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
4959                         run_one_logged $1 "$2"
4960                         return $?
4961                 fi
4962                 LAST_SKIPPED="y"
4963                 return 0
4964         fi
4965
4966         LAST_SKIPPED="y"
4967         ALWAYS_SKIPPED="y"
4968         testname=EXCEPT_$1
4969         if [ ${!testname}x != x ]; then
4970                 TESTNAME=test_$1 skip "skipping excluded test $1"
4971                 return 0
4972         fi
4973         testname=EXCEPT_$base
4974         if [ ${!testname}x != x ]; then
4975                 TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
4976                 return 0
4977         fi
4978         testname=EXCEPT_ALWAYS_$1
4979         if [ ${!testname}x != x ]; then
4980                 TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1"
4981                 return 0
4982         fi
4983         testname=EXCEPT_ALWAYS_$base
4984         if [ ${!testname}x != x ]; then
4985                 TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1 (base $base)"
4986                 return 0
4987         fi
4988         testname=EXCEPT_SLOW_$1
4989         if [ ${!testname}x != x ]; then
4990                 TESTNAME=test_$1 skip "skipping SLOW test $1"
4991                 return 0
4992         fi
4993         testname=EXCEPT_SLOW_$base
4994         if [ ${!testname}x != x ]; then
4995                 TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
4996                 return 0
4997         fi
4998
4999         LAST_SKIPPED=
5000         ALWAYS_SKIPPED=
5001         run_one_logged $1 "$2"
5002
5003         return $?
5004 }
5005
5006 log() {
5007         echo "$*" >&2
5008         load_module ../libcfs/libcfs/libcfs
5009
5010     local MSG="$*"
5011     # Get rid of '
5012     MSG=${MSG//\'/\\\'}
5013     MSG=${MSG//\(/\\\(}
5014     MSG=${MSG//\)/\\\)}
5015     MSG=${MSG//\;/\\\;}
5016     MSG=${MSG//\|/\\\|}
5017     MSG=${MSG//\>/\\\>}
5018     MSG=${MSG//\</\\\<}
5019     MSG=${MSG//\//\\\/}
5020     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
5021 }
5022
5023 trace() {
5024         log "STARTING: $*"
5025         strace -o $TMP/$1.strace -ttt $*
5026         RC=$?
5027         log "FINISHED: $*: rc $RC"
5028         return 1
5029 }
5030
5031 complete () {
5032     local duration=$1
5033
5034     banner test complete, duration $duration sec
5035     [ -f "$TESTSUITELOG" ] && egrep .FAIL $TESTSUITELOG || true
5036     echo duration $duration >>$TESTSUITELOG
5037 }
5038
5039 pass() {
5040         # Set TEST_STATUS here. It will be used for logging the result.
5041         TEST_STATUS="PASS"
5042
5043         if [[ -f $LOGDIR/err ]]; then
5044                 TEST_STATUS="FAIL"
5045         elif [[ -f $LOGDIR/skip ]]; then
5046                 TEST_STATUS="SKIP"
5047         fi
5048         echo "$TEST_STATUS $@" 2>&1 | tee -a $TESTSUITELOG
5049 }
5050
5051 check_mds() {
5052     local FFREE=$(do_node $SINGLEMDS \
5053         lctl get_param -n osd*.*MDT*.filesfree | calc_sum)
5054     local FTOTAL=$(do_node $SINGLEMDS \
5055         lctl get_param -n osd*.*MDT*.filestotal | calc_sum)
5056
5057     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
5058 }
5059
5060 reset_fail_loc () {
5061         echo -n "Resetting fail_loc on all nodes..."
5062         do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 \
5063             fail_val=0 2>/dev/null" || true
5064         echo done.
5065 }
5066
5067
5068 #
5069 # Log a message (on all nodes) padded with "=" before and after.
5070 # Also appends a timestamp and prepends the testsuite name.
5071 #
5072
5073 EQUALS="===================================================================================================="
5074 banner() {
5075     msg="== ${TESTSUITE} $*"
5076     last=${msg: -1:1}
5077     [[ $last != "=" && $last != " " ]] && msg="$msg "
5078     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
5079     # always include at least == after the message
5080     log "$msg== $(date +"%H:%M:%S (%s)")"
5081 }
5082
5083 check_dmesg_for_errors() {
5084         local res
5085         local errors="VFS: Busy inodes after unmount of\|\
5086 ldiskfs_check_descriptors: Checksum for group 0 failed\|\
5087 group descriptors corrupted"
5088
5089         res=$(do_nodes $(comma_list $(nodes_list)) "dmesg" | grep "$errors")
5090         [ -z "$res" ] && return 0
5091         echo "Kernel error detected: $res"
5092         return 1
5093 }
5094
5095 #
5096 # Run a single test function and cleanup after it.
5097 #
5098 # This function should be run in a subshell so the test func can
5099 # exit() without stopping the whole script.
5100 #
5101 run_one() {
5102         local testnum=$1
5103         local message=$2
5104         export tfile=f${testnum}.${TESTSUITE}
5105         export tdir=d${testnum}.${TESTSUITE}
5106         export TESTNAME=test_$testnum
5107         local SAVE_UMASK=`umask`
5108         umask 0022
5109
5110         if ! grep -q $DIR /proc/mounts; then
5111                 $SETUP
5112         fi
5113
5114         banner "test $testnum: $message"
5115         test_${testnum} || error "test_$testnum failed with $?"
5116         cd $SAVE_PWD
5117         reset_fail_loc
5118         check_grant ${testnum} || error "check_grant $testnum failed with $?"
5119         check_node_health
5120         check_dmesg_for_errors || error "Error in dmesg detected"
5121         if [ "$PARALLEL" != "yes" ]; then
5122                 ps auxww | grep -v grep | grep -q multiop &&
5123                                         error "multiop still running"
5124         fi
5125         unset TESTNAME
5126         unset tdir
5127         unset tfile
5128         umask $SAVE_UMASK
5129         $CLEANUP
5130         return 0
5131 }
5132
5133 #
5134 # Wrapper around run_one to ensure:
5135 #  - test runs in subshell
5136 #  - output of test is saved to separate log file for error reporting
5137 #  - test result is saved to data file
5138 #
5139 run_one_logged() {
5140         local BEFORE=$(date +%s)
5141         local TEST_ERROR
5142         local name=${TESTSUITE}.test_${1}.test_log.$(hostname -s).log
5143         local test_log=$LOGDIR/$name
5144         local zfs_log_name=${TESTSUITE}.test_${1}.zfs_log
5145         local zfs_debug_log=$LOGDIR/$zfs_log_name
5146         rm -rf $LOGDIR/err
5147         rm -rf $LOGDIR/ignore
5148         rm -rf $LOGDIR/skip
5149         local SAVE_UMASK=$(umask)
5150         umask 0022
5151
5152         echo
5153         log_sub_test_begin test_${1}
5154         (run_one $1 "$2") 2>&1 | tee -i $test_log
5155         local RC=${PIPESTATUS[0]}
5156
5157         [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] &&
5158                 echo "test_$1 returned $RC" | tee $LOGDIR/err
5159
5160         duration=$(($(date +%s) - $BEFORE))
5161         pass "$1" "(${duration}s)"
5162
5163         if [[ -f $LOGDIR/err ]]; then
5164                 TEST_ERROR=$(cat $LOGDIR/err)
5165         elif [[ -f $LOGDIR/ignore ]]; then
5166                 TEST_ERROR=$(cat $LOGDIR/ignore)
5167         elif [[ -f $LOGDIR/skip ]]; then
5168                 TEST_ERROR=$(cat $LOGDIR/skip)
5169         fi
5170         log_sub_test_end $TEST_STATUS $duration "$RC" "$TEST_ERROR"
5171
5172         if [[ "$TEST_STATUS" != "SKIP" ]] && [[ -f $TF_SKIP ]]; then
5173                 rm -f $TF_SKIP
5174         fi
5175
5176         if [ -f $LOGDIR/err ]; then
5177                 log_zfs_info "$zfs_debug_log"
5178                 $FAIL_ON_ERROR && exit $RC
5179         fi
5180
5181         umask $SAVE_UMASK
5182
5183         return 0
5184 }
5185
5186 #
5187 # Print information of skipped tests to result.yml
5188 #
5189 skip_logged(){
5190         log_sub_test_begin $1
5191         shift
5192         log_sub_test_end "SKIP" "0" "0" "$@"
5193 }
5194
5195 canonical_path() {
5196         (cd $(dirname $1); echo $PWD/$(basename $1))
5197 }
5198
5199
5200 check_grant() {
5201         export base=$(basetest $1)
5202         [ "$CHECK_GRANT" == "no" ] && return 0
5203
5204         testname=GCHECK_ONLY_${base}
5205         [ ${!testname}x == x ] && return 0
5206
5207         echo -n "checking grant......"
5208
5209         local clients=$CLIENTS
5210         [ -z "$clients" ] && clients=$(hostname)
5211
5212         # sync all the data and make sure no pending data on server
5213         do_nodes $clients sync
5214
5215         # get client grant
5216         client_grant=$(do_nodes $clients \
5217                 "$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes" |
5218                 awk '{ total += $1 } END { printf("%0.0f", total) }')
5219
5220         # get server grant
5221         server_grant=$(do_nodes $(comma_list $(osts_nodes)) \
5222                 "$LCTL get_param -n obdfilter.${FSNAME}-OST*.tot_granted" |
5223                 awk '{ total += $1 } END { printf("%0.0f", total) }')
5224
5225         # check whether client grant == server grant
5226         if [[ $client_grant -ne $server_grant ]]; then
5227                 echo "failed: client:${client_grant} server: ${server_grant}."
5228                 do_nodes $(comma_list $(osts_nodes)) \
5229                         "$LCTL get_param obdfilter.${FSNAME}-OST*.tot*"
5230                 do_nodes $clients "$LCTL get_param osc.${FSNAME}-*.cur_*_bytes"
5231                 return 1
5232         else
5233                 echo "pass: client:${client_grant} server: ${server_grant}"
5234         fi
5235 }
5236
5237 ########################
5238 # helper functions
5239
5240 osc_to_ost()
5241 {
5242     osc=$1
5243     ost=`echo $1 | awk -F_ '{print $3}'`
5244     if [ -z $ost ]; then
5245         ost=`echo $1 | sed 's/-osc.*//'`
5246     fi
5247     echo $ost
5248 }
5249
5250 ostuuid_from_index()
5251 {
5252     $LFS osts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
5253 }
5254
5255 ostname_from_index() {
5256     local uuid=$(ostuuid_from_index $1)
5257     echo ${uuid/_UUID/}
5258 }
5259
5260 index_from_ostuuid()
5261 {
5262     $LFS osts $2 | sed -ne "/${1}/s/\(.*\): .* .*$/\1/p"
5263 }
5264
5265 mdtuuid_from_index()
5266 {
5267     $LFS mdts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
5268 }
5269
5270 # Description:
5271 #   Return unique identifier for given hostname
5272 host_id() {
5273         local host_name=$1
5274         echo $host_name | md5sum | cut -d' ' -f1
5275 }
5276
5277 # Description:
5278 #   Returns list of ip addresses for each interface
5279 local_addr_list() {
5280         ip addr | awk '/inet\ / {print $2}' | awk -F\/ '{print $1}'
5281 }
5282
5283 is_local_addr() {
5284         local addr=$1
5285         # Cache address list to avoid mutiple execution of local_addr_list
5286         LOCAL_ADDR_LIST=${LOCAL_ADDR_LIST:-$(local_addr_list)}
5287         local i
5288         for i in $LOCAL_ADDR_LIST ; do
5289                 [[ "$i" == "$addr" ]] && return 0
5290         done
5291         return 1
5292 }
5293
5294 local_node() {
5295         local host_name=$1
5296         local is_local="IS_LOCAL_$(host_id $host_name)"
5297         if [ -z "${!is_local-}" ] ; then
5298                 eval $is_local=0
5299                 local host_ip=$($LUSTRE/tests/resolveip $host_name)
5300                 is_local_addr "$host_ip" && eval $is_local=1
5301         fi
5302         [[ "${!is_local}" == "1" ]]
5303 }
5304
5305 remote_node () {
5306         local node=$1
5307         local_node $node && return 1
5308         return 0
5309 }
5310
5311 remote_mds ()
5312 {
5313     local node
5314     for node in $(mdts_nodes); do
5315         remote_node $node && return 0
5316     done
5317     return 1
5318 }
5319
5320 remote_mds_nodsh()
5321 {
5322         [ -n "$CLIENTONLY" ] && return 0 || true
5323         remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
5324 }
5325
5326 require_dsh_mds()
5327 {
5328         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" &&
5329                 MSKIPPED=1 && return 1
5330         return 0
5331 }
5332
5333 remote_ost ()
5334 {
5335     local node
5336     for node in $(osts_nodes) ; do
5337         remote_node $node && return 0
5338     done
5339     return 1
5340 }
5341
5342 remote_ost_nodsh()
5343 {
5344         [ -n "$CLIENTONLY" ] && return 0 || true
5345         remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
5346 }
5347
5348 require_dsh_ost()
5349 {
5350         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
5351             OSKIPPED=1 && return 1
5352         return 0
5353 }
5354
5355 remote_mgs_nodsh()
5356 {
5357         [ -n "$CLIENTONLY" ] && return 0 || true
5358         local MGS
5359         MGS=$(facet_host mgs)
5360         remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
5361 }
5362
5363 local_mode ()
5364 {
5365     remote_mds_nodsh || remote_ost_nodsh || \
5366         $(single_local_node $(comma_list $(nodes_list)))
5367 }
5368
5369 remote_servers () {
5370     remote_ost && remote_mds
5371 }
5372
5373 # Get the active nodes for facets.
5374 facets_nodes () {
5375         local facets=$1
5376         local facet
5377         local nodes
5378         local nodes_sort
5379         local i
5380
5381         for facet in ${facets//,/ }; do
5382                 nodes="$nodes $(facet_active_host $facet)"
5383         done
5384
5385         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5386         echo -n $nodes_sort
5387 }
5388
5389 # Get all of the active MDS nodes.
5390 mdts_nodes () {
5391         echo -n $(facets_nodes $(get_facets MDS))
5392 }
5393
5394 # Get all of the active OSS nodes.
5395 osts_nodes () {
5396         echo -n $(facets_nodes $(get_facets OST))
5397 }
5398
5399 # Get all of the active AGT (HSM agent) nodes.
5400 agts_nodes () {
5401         echo -n $(facets_nodes $(get_facets AGT))
5402 }
5403
5404 # Get all of the client nodes and active server nodes.
5405 nodes_list () {
5406         local nodes=$HOSTNAME
5407         local nodes_sort
5408         local i
5409
5410         # CLIENTS (if specified) contains the local client
5411         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
5412
5413         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
5414                 nodes="$nodes $(facets_nodes $(get_facets))"
5415         fi
5416
5417         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5418         echo -n $nodes_sort
5419 }
5420
5421 # Get all of the remote client nodes and remote active server nodes.
5422 remote_nodes_list () {
5423         echo -n $(nodes_list) | sed -re "s/\<$HOSTNAME\>//g"
5424 }
5425
5426 # Get all of the MDS nodes, including active and passive nodes.
5427 all_mdts_nodes () {
5428         local host
5429         local failover_host
5430         local nodes
5431         local nodes_sort
5432         local i
5433
5434         for i in $(seq $MDSCOUNT); do
5435                 host=mds${i}_HOST
5436                 failover_host=mds${i}failover_HOST
5437                 nodes="$nodes ${!host} ${!failover_host}"
5438         done
5439
5440         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5441         echo -n $nodes_sort
5442 }
5443
5444 # Get all of the OSS nodes, including active and passive nodes.
5445 all_osts_nodes () {
5446         local host
5447         local failover_host
5448         local nodes
5449         local nodes_sort
5450         local i
5451
5452         for i in $(seq $OSTCOUNT); do
5453                 host=ost${i}_HOST
5454                 failover_host=ost${i}failover_HOST
5455                 nodes="$nodes ${!host} ${!failover_host}"
5456         done
5457
5458         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5459         echo -n $nodes_sort
5460 }
5461
5462 # Get all of the server nodes, including active and passive nodes.
5463 all_server_nodes () {
5464         local nodes
5465         local nodes_sort
5466         local i
5467
5468         nodes="$mgs_HOST $mgsfailover_HOST $(all_mdts_nodes) $(all_osts_nodes)"
5469
5470         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5471         echo -n $nodes_sort
5472 }
5473
5474 # Get all of the client and server nodes, including active and passive nodes.
5475 all_nodes () {
5476         local nodes=$HOSTNAME
5477         local nodes_sort
5478         local i
5479
5480         # CLIENTS (if specified) contains the local client
5481         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
5482
5483         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
5484                 nodes="$nodes $(all_server_nodes)"
5485         fi
5486
5487         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5488         echo -n $nodes_sort
5489 }
5490
5491 init_clients_lists () {
5492     # Sanity check: exclude the local client from RCLIENTS
5493     local clients=$(hostlist_expand "$RCLIENTS")
5494     local rclients=$(exclude_items_from_list "$clients" $HOSTNAME)
5495
5496     # Sanity check: exclude the dup entries
5497     RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)
5498
5499     clients="$SINGLECLIENT $HOSTNAME $RCLIENTS"
5500
5501     # Sanity check: exclude the dup entries from CLIENTS
5502     # for those configs which has SINGLCLIENT set to local client
5503     clients=$(for i in $clients; do echo $i; done | sort -u)
5504
5505     CLIENTS=$(comma_list $clients)
5506     local -a remoteclients=($RCLIENTS)
5507     for ((i=0; $i<${#remoteclients[@]}; i++)); do
5508             varname=CLIENT$((i + 2))
5509             eval $varname=${remoteclients[i]}
5510     done
5511
5512     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
5513 }
5514
5515 get_random_entry () {
5516     local rnodes=$1
5517
5518     rnodes=${rnodes//,/ }
5519
5520     local -a nodes=($rnodes)
5521     local num=${#nodes[@]}
5522     local i=$((RANDOM * num * 2 / 65536))
5523
5524     echo ${nodes[i]}
5525 }
5526
5527 client_only () {
5528         [ -n "$CLIENTONLY" ] || [ "x$CLIENTMODSONLY" = "xyes" ]
5529 }
5530
5531 check_versions () {
5532     [ "$(lustre_version_code client)" = "$(lustre_version_code $SINGLEMDS)" -a \
5533       "$(lustre_version_code client)" = "$(lustre_version_code ost1)" ]
5534 }
5535
5536 get_node_count() {
5537     local nodes="$@"
5538     echo $nodes | wc -w || true
5539 }
5540
5541 mixed_ost_devs () {
5542     local nodes=$(osts_nodes)
5543     local osscount=$(get_node_count "$nodes")
5544     [ ! "$OSTCOUNT" = "$osscount" ]
5545 }
5546
5547 mixed_mdt_devs () {
5548     local nodes=$(mdts_nodes)
5549     local mdtcount=$(get_node_count "$nodes")
5550     [ ! "$MDSCOUNT" = "$mdtcount" ]
5551 }
5552
5553 generate_machine_file() {
5554     local nodes=${1//,/ }
5555     local machinefile=$2
5556     rm -f $machinefile
5557     for node in $nodes; do
5558         echo $node >>$machinefile || \
5559             { echo "can not generate machinefile $machinefile" && return 1; }
5560     done
5561 }
5562
5563 get_stripe () {
5564         local file=$1/stripe
5565
5566         touch $file
5567         $LFS getstripe -v $file || error "getstripe $file failed"
5568         rm -f $file
5569 }
5570
5571 setstripe_nfsserver () {
5572         local dir=$1
5573
5574         local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
5575                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -n1)
5576
5577         [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
5578
5579         do_nodev $nfsserver lfs setstripe "$@"
5580 }
5581
5582 # Check and add a test group.
5583 add_group() {
5584         local group_id=$1
5585         local group_name=$2
5586         local rc=0
5587
5588         local gid=$(getent group $group_name | cut -d: -f3)
5589         if [[ -n "$gid" ]]; then
5590                 [[ "$gid" -eq "$group_id" ]] || {
5591                         error_noexit "inconsistent group ID:" \
5592                                      "new: $group_id, old: $gid"
5593                         rc=1
5594                 }
5595         else
5596                 groupadd -g $group_id $group_name
5597                 rc=${PIPESTATUS[0]}
5598         fi
5599
5600         return $rc
5601 }
5602
5603 # Check and add a test user.
5604 add_user() {
5605         local user_id=$1
5606         shift
5607         local user_name=$1
5608         shift
5609         local group_name=$1
5610         shift
5611         local home=$1
5612         shift
5613         local opts="$@"
5614         local rc=0
5615
5616         local uid=$(getent passwd $user_name | cut -d: -f3)
5617         if [[ -n "$uid" ]]; then
5618                 if [[ "$uid" -eq "$user_id" ]]; then
5619                         local dir=$(getent passwd $user_name | cut -d: -f6)
5620                         if [[ "$dir" != "$home" ]]; then
5621                                 mkdir -p $home
5622                                 usermod -d $home $user_name
5623                                 rc=${PIPESTATUS[0]}
5624                         fi
5625                 else
5626                         error_noexit "inconsistent user ID:" \
5627                                      "new: $user_id, old: $uid"
5628                         rc=1
5629                 fi
5630         else
5631                 mkdir -p $home
5632                 useradd -M -u $user_id -d $home -g $group_name $opts $user_name
5633                 rc=${PIPESTATUS[0]}
5634         fi
5635
5636         return $rc
5637 }
5638
5639 check_runas_id_ret() {
5640     local myRC=0
5641     local myRUNAS_UID=$1
5642     local myRUNAS_GID=$2
5643     shift 2
5644     local myRUNAS=$@
5645     if [ -z "$myRUNAS" ]; then
5646         error_exit "myRUNAS command must be specified for check_runas_id"
5647     fi
5648     if $GSS_KRB5; then
5649         $myRUNAS krb5_login.sh || \
5650             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
5651     fi
5652     mkdir $DIR/d0_runas_test
5653     chmod 0755 $DIR
5654     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
5655     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
5656     rm -rf $DIR/d0_runas_test
5657     return $myRC
5658 }
5659
5660 check_runas_id() {
5661     local myRUNAS_UID=$1
5662     local myRUNAS_GID=$2
5663     shift 2
5664     local myRUNAS=$@
5665     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
5666         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
5667         Please set RUNAS_ID to some UID which exists on MDS and client or
5668         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
5669 }
5670
5671 # obtain the UID/GID for MPI_USER
5672 get_mpiuser_id() {
5673     local mpi_user=$1
5674
5675     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
5676 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
5677
5678     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
5679 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
5680 }
5681
5682 # obtain and cache Kerberos ticket-granting ticket
5683 refresh_krb5_tgt() {
5684     local myRUNAS_UID=$1
5685     local myRUNAS_GID=$2
5686     shift 2
5687     local myRUNAS=$@
5688     if [ -z "$myRUNAS" ]; then
5689         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
5690     fi
5691
5692     CLIENTS=${CLIENTS:-$HOSTNAME}
5693     do_nodes $CLIENTS "set -x
5694 if ! $myRUNAS krb5_login.sh; then
5695     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
5696     exit 1
5697 fi"
5698 }
5699
5700 # Run multiop in the background, but wait for it to print
5701 # "PAUSING" to its stdout before returning from this function.
5702 multiop_bg_pause() {
5703     MULTIOP_PROG=${MULTIOP_PROG:-$MULTIOP}
5704     FILE=$1
5705     ARGS=$2
5706
5707     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
5708     mkfifo $TMPPIPE
5709
5710     echo "$MULTIOP_PROG $FILE v$ARGS"
5711     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
5712
5713     echo "TMPPIPE=${TMPPIPE}"
5714     read -t 60 multiop_output < $TMPPIPE
5715     if [ $? -ne 0 ]; then
5716         rm -f $TMPPIPE
5717         return 1
5718     fi
5719     rm -f $TMPPIPE
5720     if [ "$multiop_output" != "PAUSING" ]; then
5721         echo "Incorrect multiop output: $multiop_output"
5722         kill -9 $PID
5723         return 1
5724     fi
5725
5726     return 0
5727 }
5728
5729 do_and_time () {
5730     local cmd=$1
5731     local rc
5732
5733     SECONDS=0
5734     eval '$cmd'
5735
5736     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
5737
5738     echo $SECONDS
5739     return $rc
5740 }
5741
5742 inodes_available () {
5743         local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{ print $4 }' |
5744                 sort -un | head -n1) || return 1
5745         echo $((IFree))
5746 }
5747
5748 mdsrate_inodes_available () {
5749     local min_inodes=$(inodes_available)
5750     echo $((min_inodes * 99 / 100))
5751 }
5752
5753 # reset llite stat counters
5754 clear_llite_stats(){
5755         lctl set_param -n llite.*.stats 0
5756 }
5757
5758 # sum llite stat items
5759 calc_llite_stats() {
5760         local res=$(lctl get_param -n llite.*.stats |
5761                 awk '/^'"$1"'/ {sum += $2} END { printf("%0.0f", sum) }')
5762         echo $((res))
5763 }
5764
5765 # reset osc stat counters
5766 clear_osc_stats(){
5767         lctl set_param -n osc.*.osc_stats 0
5768 }
5769
5770 # sum osc stat items
5771 calc_osc_stats() {
5772         local res=$(lctl get_param -n osc.*.osc_stats |
5773                 awk '/^'"$1"'/ {sum += $2} END { printf("%0.0f", sum) }')
5774         echo $((res))
5775 }
5776
5777 calc_sum () {
5778         awk '{sum += $1} END { printf("%0.0f", sum) }'
5779 }
5780
5781 calc_osc_kbytes () {
5782         df $MOUNT > /dev/null
5783         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
5784 }
5785
5786 # save_lustre_params(comma separated facet list, parameter_mask)
5787 # generate a stream of formatted strings (<facet> <param name>=<param value>)
5788 save_lustre_params() {
5789         local facets=$1
5790         local facet
5791         local nodes
5792         local node
5793
5794         for facet in ${facets//,/ }; do
5795                 node=$(facet_active_host $facet)
5796                 [[ *\ $node\ * = " $nodes " ]] && continue
5797                 nodes="$nodes $node"
5798
5799                 do_node $node "$LCTL get_param $2 |
5800                         while read s; do echo $facet \\\$s; done"
5801         done
5802 }
5803
5804 # restore lustre parameters from input stream, produces by save_lustre_params
5805 restore_lustre_params() {
5806         local facet
5807         local name
5808         local val
5809
5810         while IFS=" =" read facet name val; do
5811                 do_facet $facet "$LCTL set_param -n $name $val"
5812         done
5813 }
5814
5815 check_node_health() {
5816         local nodes=${1:-$(comma_list $(nodes_list))}
5817
5818         for node in ${nodes//,/ }; do
5819                 check_network "$node" 5
5820                 if [ $? -eq 0 ]; then
5821                         do_node $node "rc=0;
5822                         val=\\\$($LCTL get_param -n catastrophe 2>&1);
5823                         if [[ \\\$? -eq 0 && \\\$val -ne 0 ]]; then
5824                                 echo \\\$(hostname -s): \\\$val;
5825                                 rc=\\\$val;
5826                         fi;
5827                         exit \\\$rc" || error "$node:LBUG/LASSERT detected"
5828                 fi
5829         done
5830 }
5831
5832 mdsrate_cleanup () {
5833         if [ -d $4 ]; then
5834                 mpi_run ${MACHINEFILE_OPTION} $2 -np $1 ${MDSRATE} --unlink \
5835                         --nfiles $3 --dir $4 --filefmt $5 $6
5836                 rmdir $4
5837         fi
5838 }
5839
5840 delayed_recovery_enabled () {
5841     local var=${SINGLEMDS}_svc
5842     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
5843 }
5844
5845 ########################
5846
5847 convert_facet2label() {
5848     local facet=$1
5849
5850     if [ x$facet = xost ]; then
5851        facet=ost1
5852     fi
5853
5854     local varsvc=${facet}_svc
5855
5856     if [ -n ${!varsvc} ]; then
5857         echo ${!varsvc}
5858     else
5859         error "No lablel for $facet!"
5860     fi
5861 }
5862
5863 get_clientosc_proc_path() {
5864         echo "${1}-osc-*"
5865 }
5866
5867 # If the 2.0 MDS was mounted on 1.8 device, then the OSC and LOV names
5868 # used by MDT would not be changed.
5869 # mdt lov: fsname-mdtlov
5870 # mdt osc: fsname-OSTXXXX-osc
5871 mds_on_old_device() {
5872     local mds=${1:-"$SINGLEMDS"}
5873
5874     if [ $(lustre_version_code $mds) -gt $(version_code 1.9.0) ]; then
5875         do_facet $mds "lctl list_param osc.$FSNAME-OST*-osc \
5876             > /dev/null 2>&1" && return 0
5877     fi
5878     return 1
5879 }
5880
5881 get_mdtosc_proc_path() {
5882         local mds_facet=$1
5883         local ost_label=${2:-"*OST*"}
5884
5885         [ "$mds_facet" = "mds" ] && mds_facet=$SINGLEMDS
5886         local mdt_label=$(convert_facet2label $mds_facet)
5887         local mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')
5888
5889         if [ $(lustre_version_code $mds_facet) -le $(version_code 1.8.0) ] ||
5890            mds_on_old_device $mds_facet; then
5891                 echo "${ost_label}-osc"
5892         elif [[ $ost_label = *OST* ]]; then
5893                 echo "${ost_label}-osc-${mdt_index}"
5894         else
5895                 echo "${ost_label}-osp-${mdt_index}"
5896         fi
5897 }
5898
5899 get_osc_import_name() {
5900     local facet=$1
5901     local ost=$2
5902     local label=$(convert_facet2label $ost)
5903
5904     if [ "${facet:0:3}" = "mds" ]; then
5905         get_mdtosc_proc_path $facet $label
5906         return 0
5907     fi
5908
5909     get_clientosc_proc_path $label
5910     return 0
5911 }
5912
5913 _wait_import_state () {
5914     local expected=$1
5915     local CONN_PROC=$2
5916     local maxtime=${3:-$(max_recovery_time)}
5917     local error_on_failure=${4:-1}
5918     local CONN_STATE
5919     local i=0
5920
5921         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
5922     while [ "${CONN_STATE}" != "${expected}" ]; do
5923         if [ "${expected}" == "DISCONN" ]; then
5924             # for disconn we can check after proc entry is removed
5925             [ "x${CONN_STATE}" == "x" ] && return 0
5926             #  with AT enabled, we can have connect request timeout near of
5927             # reconnect timeout and test can't see real disconnect
5928             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
5929         fi
5930         if [ $i -ge $maxtime ]; then
5931             [ $error_on_failure -ne 0 ] && \
5932                 error "can't put import for $CONN_PROC into ${expected}" \
5933                       "state after $i sec, have ${CONN_STATE}"
5934             return 1
5935         fi
5936         sleep 1
5937         # Add uniq for multi-mount case
5938         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
5939         i=$(($i + 1))
5940     done
5941
5942     log "$CONN_PROC in ${CONN_STATE} state after $i sec"
5943     return 0
5944 }
5945
5946 wait_import_state() {
5947     local state=$1
5948     local params=$2
5949     local maxtime=${3:-$(max_recovery_time)}
5950     local error_on_failure=${4:-1}
5951     local param
5952
5953     for param in ${params//,/ }; do
5954         _wait_import_state $state $param $maxtime $error_on_failure || return
5955     done
5956 }
5957
5958 wait_import_state_mount() {
5959         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
5960                 return 0
5961         fi
5962
5963         wait_import_state $*
5964 }
5965
5966 # One client request could be timed out because server was not ready
5967 # when request was sent by client.
5968 # The request timeout calculation details :
5969 # ptl_send_rpc ()
5970 #      /* We give the server rq_timeout secs to process the req, and
5971 #      add the network latency for our local timeout. */
5972 #      request->rq_deadline = request->rq_sent + request->rq_timeout +
5973 #           ptlrpc_at_get_net_latency(request) ;
5974 #
5975 # ptlrpc_connect_import ()
5976 #      request->rq_timeout = INITIAL_CONNECT_TIMEOUT
5977 #
5978 # init_imp_at () ->
5979 #   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0
5980 # ptlrpc_at_get_net_latency(request) ->
5981 #       at_get (max (iat_net_latency=0, at_min)) = at_min
5982 #
5983 # i.e.:
5984 # request->rq_timeout + ptlrpc_at_get_net_latency(request) =
5985 # INITIAL_CONNECT_TIMEOUT + at_min
5986 #
5987 # We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT
5988 # because we can not get this value in runtime,
5989 # the value depends on configure options, and it is not stored in /proc.
5990 # obd_support.h:
5991 # #define CONNECTION_SWITCH_MIN 5U
5992 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
5993
5994 request_timeout () {
5995     local facet=$1
5996
5997     # request->rq_timeout = INITIAL_CONNECT_TIMEOUT
5998     local init_connect_timeout=$TIMEOUT
5999     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
6000
6001     local at_min=$(at_get $facet at_min)
6002
6003     echo $(( init_connect_timeout + at_min ))
6004 }
6005
6006 _wait_osc_import_state() {
6007         local facet=$1
6008         local ost_facet=$2
6009         local expected=$3
6010         local target=$(get_osc_import_name $facet $ost_facet)
6011         local param="osc.${target}.ost_server_uuid"
6012         local params=$param
6013         local i=0
6014
6015         # 1. wait the deadline of client 1st request (it could be skipped)
6016         # 2. wait the deadline of client 2nd request
6017         local maxtime=$(( 2 * $(request_timeout $facet)))
6018
6019         if [[ $facet == client* ]]; then
6020                 # During setup time, the osc might not be setup, it need wait
6021                 # until list_param can return valid value. And also if there
6022                 # are mulitple osc entries we should list all of them before
6023                 # go to wait.
6024                 params=$($LCTL list_param $param 2>/dev/null || true)
6025                 while [ -z "$params" ]; do
6026                         if [ $i -ge $maxtime ]; then
6027                                 echo "can't get $param in $maxtime secs"
6028                                 return 1
6029                         fi
6030                         sleep 1
6031                         i=$((i + 1))
6032                         params=$($LCTL list_param $param 2>/dev/null || true)
6033                 done
6034         fi
6035
6036         if [[ $ost_facet = mds* ]]; then
6037                 # no OSP connection to itself
6038                 if [[ $facet = $ost_facet ]]; then
6039                         return 0
6040                 fi
6041                 param="osp.${target}.mdt_server_uuid"
6042                 params=$param
6043         fi
6044
6045         if ! do_rpc_nodes "$(facet_active_host $facet)" \
6046                         wait_import_state $expected "$params" $maxtime; then
6047                 error "import is not in ${expected} state"
6048                 return 1
6049         fi
6050
6051         return 0
6052 }
6053
6054 wait_osc_import_state() {
6055         local facet=$1
6056         local ost_facet=$2
6057         local expected=$3
6058         local num
6059
6060         if [[ $facet = mds ]]; then
6061                 for num in $(seq $MDSCOUNT); do
6062                         _wait_osc_import_state mds$num "$ost_facet" "$expected"
6063                 done
6064         else
6065                 _wait_osc_import_state "$facet" "$ost_facet" "$expected"
6066         fi
6067 }
6068
6069 _wait_mgc_import_state() {
6070         local facet=$1
6071         local expected=$2
6072         local error_on_failure=${3:-1}
6073         local param="mgc.*.mgs_server_uuid"
6074         local params=$param
6075         local i=0
6076
6077         # 1. wait the deadline of client 1st request (it could be skipped)
6078         # 2. wait the deadline of client 2nd request
6079         local maxtime=$(( 2 * $(request_timeout $facet)))
6080
6081         if [[ $facet == client* ]]; then
6082                 # During setup time, the osc might not be setup, it need wait
6083                 # until list_param can return valid value. And also if there
6084                 # are mulitple osc entries we should list all of them before
6085                 # go to wait.
6086                 params=$($LCTL list_param $param 2>/dev/null || true)
6087                 while [ -z "$params" ]; do
6088                         if [ $i -ge $maxtime ]; then
6089                                 echo "can't get $param in $maxtime secs"
6090                                 return 1
6091                         fi
6092                         sleep 1
6093                         i=$((i + 1))
6094                         params=$($LCTL list_param $param 2>/dev/null || true)
6095                 done
6096         fi
6097         if ! do_rpc_nodes "$(facet_active_host $facet)" \
6098                         wait_import_state $expected "$params" $maxtime \
6099                                           $error_on_failure; then
6100                 if [ $error_on_failure -ne 0 ]; then
6101                     error "import is not in ${expected} state"
6102                 fi
6103                 return 1
6104         fi
6105
6106         return 0
6107 }
6108
6109 wait_mgc_import_state() {
6110         local facet=$1
6111         local expected=$2
6112         local error_on_failure=${3:-1}
6113         local num
6114
6115         if [[ $facet = mds ]]; then
6116                 for num in $(seq $MDSCOUNT); do
6117                         _wait_mgc_import_state mds$num "$expected" \
6118                                                $error_on_failure || return
6119                 done
6120         else
6121                 _wait_mgc_import_state "$facet" "$expected"
6122                                        $error_on_failure || return
6123         fi
6124 }
6125
6126 wait_dne_interconnect() {
6127         local num
6128
6129         if [ $MDSCOUNT -gt 1 ]; then
6130                 for num in $(seq $MDSCOUNT); do
6131                         wait_osc_import_state mds mds$num FULL
6132                 done
6133         fi
6134 }
6135
6136 get_clientmdc_proc_path() {
6137     echo "${1}-mdc-*"
6138 }
6139
6140 get_clientmgc_proc_path() {
6141     echo "*"
6142 }
6143
6144 do_rpc_nodes () {
6145         local list=$1
6146         shift
6147
6148         [ -z "$list" ] && return 0
6149
6150         # Add paths to lustre tests for 32 and 64 bit systems.
6151         local LIBPATH="/usr/lib/lustre/tests:/usr/lib64/lustre/tests:"
6152         local TESTPATH="$RLUSTRE/tests:"
6153         local RPATH="PATH=${TESTPATH}${LIBPATH}${PATH}:/sbin:/bin:/usr/sbin:"
6154         do_nodesv $list "${RPATH} NAME=${NAME} sh rpc.sh $@ "
6155 }
6156
6157 wait_clients_import_state () {
6158         local list=$1
6159         local facet=$2
6160         local expected=$3
6161
6162         local facets=$facet
6163
6164         if [ "$FAILURE_MODE" = HARD ]; then
6165                 facets=$(facets_on_host $(facet_active_host $facet))
6166         fi
6167
6168         for facet in ${facets//,/ }; do
6169                 local label=$(convert_facet2label $facet)
6170                 local proc_path
6171                 case $facet in
6172                 ost* ) proc_path="osc.$(get_clientosc_proc_path \
6173                                   $label).ost_server_uuid" ;;
6174                 mds* ) proc_path="mdc.$(get_clientmdc_proc_path \
6175                                   $label).mds_server_uuid" ;;
6176                 mgs* ) proc_path="mgc.$(get_clientmgc_proc_path \
6177                                   $label).mgs_server_uuid" ;;
6178                 *) error "unknown facet!" ;;
6179                 esac
6180
6181                 local params=$(expand_list $params $proc_path)
6182         done
6183
6184         if ! do_rpc_nodes "$list" wait_import_state_mount $expected $params;
6185         then
6186                 error "import is not in ${expected} state"
6187                 return 1
6188         fi
6189 }
6190
6191 oos_full() {
6192         local -a AVAILA
6193         local -a GRANTA
6194         local -a TOTALA
6195         local OSCFULL=1
6196         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
6197                   $LCTL get_param obdfilter.*.kbytesavail))
6198         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
6199                   $LCTL get_param -n obdfilter.*.tot_granted))
6200         TOTALA=($(do_nodes $(comma_list $(osts_nodes)) \
6201                   $LCTL get_param -n obdfilter.*.kbytestotal))
6202         for ((i=0; i<${#AVAILA[@]}; i++)); do
6203                 local -a AVAIL1=(${AVAILA[$i]//=/ })
6204                 local -a TOTAL=(${TOTALA[$i]//=/ })
6205                 GRANT=$((${GRANTA[$i]}/1024))
6206                 # allow 1% of total space in bavail because of delayed
6207                 # allocation with ZFS which might release some free space after
6208                 # txg commit.  For small devices, we set a mininum of 8MB
6209                 local LIMIT=$((${TOTAL} / 100 + 8000))
6210                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} \
6211                         grnt=$GRANT diff=$((AVAIL1[1] - GRANT)) limit=${LIMIT}
6212                 [ $((AVAIL1[1] - GRANT)) -lt $LIMIT ] && OSCFULL=0 && \
6213                         echo " FULL" || echo
6214         done
6215         return $OSCFULL
6216 }
6217
6218 pool_list () {
6219    do_facet mgs lctl pool_list $1
6220 }
6221
6222 create_pool() {
6223     local fsname=${1%%.*}
6224     local poolname=${1##$fsname.}
6225
6226     do_facet mgs lctl pool_new $1
6227     local RC=$?
6228     # get param should return err unless pool is created
6229     [[ $RC -ne 0 ]] && return $RC
6230
6231     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
6232         2>/dev/null || echo foo" "" || RC=1
6233     if [[ $RC -eq 0 ]]; then
6234         add_pool_to_list $1
6235     else
6236         error "pool_new failed $1"
6237     fi
6238     return $RC
6239 }
6240
6241 add_pool_to_list () {
6242         local fsname=${1%%.*}
6243         local poolname=${1##$fsname.}
6244
6245         local listvar=${fsname}_CREATED_POOLS
6246         local temp=${listvar}=$(expand_list ${!listvar} $poolname)
6247         eval export $temp
6248 }
6249
6250 remove_pool_from_list () {
6251         local fsname=${1%%.*}
6252         local poolname=${1##$fsname.}
6253
6254         local listvar=${fsname}_CREATED_POOLS
6255         local temp=${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
6256         eval export $temp
6257 }
6258
6259 destroy_pool_int() {
6260     local ost
6261     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
6262         awk '$1 !~ /^Pool:/ {print $1}')
6263     for ost in $OSTS; do
6264         do_facet mgs lctl pool_remove $1 $ost
6265     done
6266     do_facet mgs lctl pool_destroy $1
6267 }
6268
6269 # <fsname>.<poolname> or <poolname>
6270 destroy_pool() {
6271     local fsname=${1%%.*}
6272     local poolname=${1##$fsname.}
6273
6274     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
6275
6276     local RC
6277
6278     pool_list $fsname.$poolname || return $?
6279
6280     destroy_pool_int $fsname.$poolname
6281     RC=$?
6282     [[ $RC -ne 0 ]] && return $RC
6283
6284     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
6285       2>/dev/null || echo foo" "foo" || RC=1
6286
6287     if [[ $RC -eq 0 ]]; then
6288         remove_pool_from_list $fsname.$poolname
6289     else
6290         error "destroy pool failed $1"
6291     fi
6292     return $RC
6293 }
6294
6295 destroy_pools () {
6296     local fsname=${1:-$FSNAME}
6297     local poolname
6298     local listvar=${fsname}_CREATED_POOLS
6299
6300     pool_list $fsname
6301
6302     [ x${!listvar} = x ] && return 0
6303
6304     echo destroy the created pools: ${!listvar}
6305     for poolname in ${!listvar//,/ }; do
6306         destroy_pool $fsname.$poolname
6307     done
6308 }
6309
6310 cleanup_pools () {
6311     local fsname=${1:-$FSNAME}
6312     trap 0
6313     destroy_pools $fsname
6314 }
6315
6316 gather_logs () {
6317     local list=$1
6318
6319     local ts=$(date +%s)
6320     local docp=true
6321
6322     if [[ ! -f "$YAML_LOG" ]]; then
6323         # init_logging is not performed before gather_logs,
6324         # so the $LOGDIR needs to be checked here
6325         check_shared_dir $LOGDIR && touch $LOGDIR/shared
6326     fi
6327
6328     [ -f $LOGDIR/shared ] && docp=false
6329
6330     # dump lustre logs, dmesg
6331
6332     prefix="$TESTLOG_PREFIX.$TESTNAME"
6333     suffix="$ts.log"
6334     echo "Dumping lctl log to ${prefix}.*.${suffix}"
6335
6336     if [ -n "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
6337         echo "Dumping logs only on local client."
6338         $LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}
6339         dmesg > ${prefix}.dmesg.$(hostname -s).${suffix}
6340         return
6341     fi
6342
6343     do_nodesv $list \
6344         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname -s).${suffix};
6345          dmesg > ${prefix}.dmesg.\\\$(hostname -s).${suffix}"
6346     if [ ! -f $LOGDIR/shared ]; then
6347         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
6348     fi
6349 }
6350
6351 do_ls () {
6352     local mntpt_root=$1
6353     local num_mntpts=$2
6354     local dir=$3
6355     local i
6356     local cmd
6357     local pids
6358     local rc=0
6359
6360     for i in $(seq 0 $num_mntpts); do
6361         cmd="ls -laf ${mntpt_root}$i/$dir"
6362         echo + $cmd;
6363         $cmd > /dev/null &
6364         pids="$pids $!"
6365     done
6366     echo pids=$pids
6367     for pid in $pids; do
6368         wait $pid || rc=$?
6369     done
6370
6371     return $rc
6372 }
6373
6374 # check_and_start_recovery_timer()
6375 #       service_time = at_est2timeout(service_time);
6376 #       service_time += 2 * INITIAL_CONNECT_TIMEOUT;
6377 #       service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC);
6378
6379 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN, obd_timeout/20)
6380 #define CONNECTION_SWITCH_MAX min(50, max(CONNECTION_SWITCH_MIN, obd_timeout))
6381 #define CONNECTION_SWITCH_MIN 5
6382 #define CONNECTION_SWITCH_INC 5
6383 max_recovery_time() {
6384         local init_connect_timeout=$((TIMEOUT / 20))
6385         ((init_connect_timeout >= 5)) || init_connect_timeout=5
6386
6387         local service_time=$(($(at_max_get client) * 9 / 4 + 5))
6388         service_time=$((service_time + 2 * (init_connect_timeout + 50 + 5)))
6389
6390         echo -n $service_time
6391 }
6392
6393 recovery_time_min() {
6394         local connection_switch_min=5
6395         local connection_switch_inc=5
6396         local connection_switch_max
6397         local reconnect_delay_max
6398         local initial_connect_timeout
6399         local max
6400         local timout_20
6401
6402         #connection_switch_max=min(50, max($connection_switch_min,$TIMEOUT)
6403         (($connection_switch_min > $TIMEOUT)) &&
6404                 max=$connection_switch_min || max=$TIMEOUT
6405         (($max < 50)) && connection_switch_max=$max || connection_switch_max=50
6406
6407         #initial_connect_timeout = max(connection_switch_min, obd_timeout/20)
6408         timeout_20=$((TIMEOUT/20))
6409         (($connection_switch_min > $timeout_20)) &&
6410                 initial_connect_timeout=$connection_switch_min ||
6411                 initial_connect_timeout=$timeout_20
6412
6413         reconnect_delay_max=$((connection_switch_max + connection_switch_inc + \
6414                                initial_connect_timeout))
6415         echo $((2 * reconnect_delay_max))
6416 }
6417
6418 get_clients_mount_count () {
6419     local clients=${CLIENTS:-`hostname`}
6420
6421     # we need to take into account the clients mounts and
6422     # exclude mds/ost mounts if any;
6423     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
6424 }
6425
6426 # gss functions
6427 PROC_CLI="srpc_info"
6428
6429 combination()
6430 {
6431     local M=$1
6432     local N=$2
6433     local R=1
6434
6435     if [ $M -lt $N ]; then
6436         R=0
6437     else
6438         N=$((N + 1))
6439         while [ $N -lt $M ]; do
6440             R=$((R * N))
6441             N=$((N + 1))
6442         done
6443     fi
6444
6445     echo $R
6446     return 0
6447 }
6448
6449 calc_connection_cnt() {
6450     local dir=$1
6451
6452     # MDT->MDT = 2 * C(M, 2)
6453     # MDT->OST = M * O
6454     # CLI->OST = C * O
6455     # CLI->MDT = C * M
6456     comb_m2=$(combination $MDSCOUNT 2)
6457
6458     local num_clients=$(get_clients_mount_count)
6459
6460     local cnt_mdt2mdt=$((comb_m2 * 2))
6461     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
6462     local cnt_cli2ost=$((num_clients * OSTCOUNT))
6463     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
6464     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
6465     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
6466     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
6467
6468     local var=cnt_$dir
6469     local res=${!var}
6470
6471     echo $res
6472 }
6473
6474 set_rule()
6475 {
6476     local tgt=$1
6477     local net=$2
6478     local dir=$3
6479     local flavor=$4
6480     local cmd="$tgt.srpc.flavor"
6481
6482     if [ $net == "any" ]; then
6483         net="default"
6484     fi
6485     cmd="$cmd.$net"
6486
6487     if [ $dir != "any" ]; then
6488         cmd="$cmd.$dir"
6489     fi
6490
6491     cmd="$cmd=$flavor"
6492     log "Setting sptlrpc rule: $cmd"
6493     do_facet mgs "$LCTL conf_param $cmd"
6494 }
6495
6496 count_flvr()
6497 {
6498     local output=$1
6499     local flavor=$2
6500     local count=0
6501
6502     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
6503     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
6504
6505     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
6506
6507     if [ "x$bulkspec" != "x" ]; then
6508         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
6509
6510         if [ "x$algs" != "x" ]; then
6511             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
6512         else
6513             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
6514             if [ $bulk == "bulkn" ]; then
6515                 bulk_count=`echo "$output" | grep "bulk flavor" \
6516                             | grep "null/null" | wc -l`
6517             elif [ $bulk == "bulki" ]; then
6518                 bulk_count=`echo "$output" | grep "bulk flavor" \
6519                             | grep "/null" | grep -v "null/" | wc -l`
6520             else
6521                 bulk_count=`echo "$output" | grep "bulk flavor" \
6522                             | grep -v "/null" | grep -v "null/" | wc -l`
6523             fi
6524         fi
6525
6526         [ $bulk_count -lt $count ] && count=$bulk_count
6527     fi
6528
6529     echo $count
6530 }
6531
6532 flvr_cnt_cli2mdt()
6533 {
6534     local flavor=$1
6535     local cnt
6536
6537     local clients=${CLIENTS:-`hostname`}
6538
6539     for c in ${clients//,/ }; do
6540         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
6541         tmpcnt=`count_flvr "$output" $flavor`
6542         cnt=$((cnt + tmpcnt))
6543     done
6544     echo $cnt
6545 }
6546
6547 flvr_cnt_cli2ost()
6548 {
6549     local flavor=$1
6550     local cnt
6551
6552     local clients=${CLIENTS:-`hostname`}
6553
6554     for c in ${clients//,/ }; do
6555         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
6556         tmpcnt=`count_flvr "$output" $flavor`
6557         cnt=$((cnt + tmpcnt))
6558     done
6559     echo $cnt
6560 }
6561
6562 flvr_cnt_mdt2mdt()
6563 {
6564     local flavor=$1
6565     local cnt=0
6566
6567     if [ $MDSCOUNT -le 1 ]; then
6568         echo 0
6569         return
6570     fi
6571
6572     for num in `seq $MDSCOUNT`; do
6573         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
6574         tmpcnt=`count_flvr "$output" $flavor`
6575         cnt=$((cnt + tmpcnt))
6576     done
6577     echo $cnt;
6578 }
6579
6580 flvr_cnt_mdt2ost()
6581 {
6582     local flavor=$1
6583     local cnt=0
6584     local mdtosc
6585
6586     for num in `seq $MDSCOUNT`; do
6587         mdtosc=$(get_mdtosc_proc_path mds$num)
6588         mdtosc=${mdtosc/-MDT*/-MDT\*}
6589         output=$(do_facet mds$num lctl get_param -n \
6590             osc.$mdtosc.$PROC_CLI 2>/dev/null)
6591         tmpcnt=`count_flvr "$output" $flavor`
6592         cnt=$((cnt + tmpcnt))
6593     done
6594     echo $cnt;
6595 }
6596
6597 flvr_cnt_mgc2mgs()
6598 {
6599     local flavor=$1
6600
6601     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
6602     count_flvr "$output" $flavor
6603 }
6604
6605 do_check_flavor()
6606 {
6607     local dir=$1        # from to
6608     local flavor=$2     # flavor expected
6609     local res=0
6610
6611     if [ $dir == "cli2mdt" ]; then
6612         res=`flvr_cnt_cli2mdt $flavor`
6613     elif [ $dir == "cli2ost" ]; then
6614         res=`flvr_cnt_cli2ost $flavor`
6615     elif [ $dir == "mdt2mdt" ]; then
6616         res=`flvr_cnt_mdt2mdt $flavor`
6617     elif [ $dir == "mdt2ost" ]; then
6618         res=`flvr_cnt_mdt2ost $flavor`
6619     elif [ $dir == "all2ost" ]; then
6620         res1=`flvr_cnt_mdt2ost $flavor`
6621         res2=`flvr_cnt_cli2ost $flavor`
6622         res=$((res1 + res2))
6623     elif [ $dir == "all2mdt" ]; then
6624         res1=`flvr_cnt_mdt2mdt $flavor`
6625         res2=`flvr_cnt_cli2mdt $flavor`
6626         res=$((res1 + res2))
6627     elif [ $dir == "all2all" ]; then
6628         res1=`flvr_cnt_mdt2ost $flavor`
6629         res2=`flvr_cnt_cli2ost $flavor`
6630         res3=`flvr_cnt_mdt2mdt $flavor`
6631         res4=`flvr_cnt_cli2mdt $flavor`
6632         res=$((res1 + res2 + res3 + res4))
6633     fi
6634
6635     echo $res
6636 }
6637
6638 wait_flavor()
6639 {
6640     local dir=$1        # from to
6641     local flavor=$2     # flavor expected
6642     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
6643
6644     local res=0
6645
6646     for ((i=0;i<20;i++)); do
6647         echo -n "checking $dir..."
6648         res=$(do_check_flavor $dir $flavor)
6649         echo "found $res/$expect $flavor connections"
6650         [ $res -ge $expect ] && return 0
6651         sleep 4
6652     done
6653
6654     echo "Error checking $flavor of $dir: expect $expect, actual $res"
6655     return 1
6656 }
6657
6658 restore_to_default_flavor()
6659 {
6660     local proc="mgs.MGS.live.$FSNAME"
6661
6662     echo "restoring to default flavor..."
6663
6664     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
6665
6666     # remove all existing rules if any
6667     if [ $nrule -ne 0 ]; then
6668         echo "$nrule existing rules"
6669         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
6670             echo "remove rule: $rule"
6671             spec=`echo $rule | awk -F = '{print $1}'`
6672             do_facet mgs "$LCTL conf_param -d $spec"
6673         done
6674     fi
6675
6676     # verify no rules left
6677     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
6678     [ $nrule -ne 0 ] && error "still $nrule rules left"
6679
6680     # wait for default flavor to be applied
6681     # currently default flavor for all connections are 'null'
6682     wait_flavor all2all null
6683     echo "now at default flavor settings"
6684 }
6685
6686 set_flavor_all()
6687 {
6688     local flavor=${1:-null}
6689
6690     echo "setting all flavor to $flavor"
6691
6692     # FIXME need parameter to this fn
6693     # and remove global vars
6694     local cnt_all2all=$(calc_connection_cnt all2all)
6695
6696     local res=$(do_check_flavor all2all $flavor)
6697     if [ $res -eq $cnt_all2all ]; then
6698         echo "already have total $res $flavor connections"
6699         return
6700     fi
6701
6702     echo "found $res $flavor out of total $cnt_all2all connections"
6703     restore_to_default_flavor
6704
6705     [[ $flavor = null ]] && return 0
6706
6707     set_rule $FSNAME any any $flavor
6708     wait_flavor all2all $flavor
6709 }
6710
6711
6712 check_logdir() {
6713     local dir=$1
6714     # Checking for shared logdir
6715     if [ ! -d $dir ]; then
6716         # Not found. Create local logdir
6717         mkdir -p $dir
6718     else
6719         touch $dir/check_file.$(hostname -s)
6720     fi
6721     return 0
6722 }
6723
6724 check_write_access() {
6725         local dir=$1
6726         local list=${2:-$(comma_list $(nodes_list))}
6727         local node
6728         local file
6729
6730         for node in ${list//,/ }; do
6731                 file=$dir/check_file.$(short_nodename $node)
6732                 if [[ ! -f "$file" ]]; then
6733                         # Logdir not accessible/writable from this node.
6734                         return 1
6735                 fi
6736                 rm -f $file || return 1
6737         done
6738         return 0
6739 }
6740
6741 init_logging() {
6742         [[ -n $YAML_LOG ]] && return
6743         local save_umask=$(umask)
6744         umask 0000
6745
6746         export YAML_LOG=${LOGDIR}/results.yml
6747         mkdir -p $LOGDIR
6748         init_clients_lists
6749
6750         # If the yaml log already exists then we will just append to it
6751         if [ ! -f $YAML_LOG ]; then
6752                 if check_shared_dir $LOGDIR; then
6753                         touch $LOGDIR/shared
6754                         echo "Logging to shared log directory: $LOGDIR"
6755                 else
6756                         echo "Logging to local directory: $LOGDIR"
6757                 fi
6758
6759                 yml_nodes_file $LOGDIR >> $YAML_LOG
6760                 yml_results_file >> $YAML_LOG
6761         fi
6762
6763         umask $save_umask
6764
6765         # If modules are not yet loaded then older "lctl lustre_build_version"
6766         # will fail.  Use lctl build version instead.
6767         log "Client: $($LCTL lustre_build_version)"
6768         log "MDS: $(do_facet $SINGLEMDS $LCTL lustre_build_version 2>/dev/null||
6769                     do_facet $SINGLEMDS $LCTL --version)"
6770         log "OSS: $(do_facet ost1 $LCTL lustre_build_version 2> /dev/null ||
6771                     do_facet ost1 $LCTL --version)"
6772 }
6773
6774 log_test() {
6775     yml_log_test $1 >> $YAML_LOG
6776 }
6777
6778 log_test_status() {
6779      yml_log_test_status $@ >> $YAML_LOG
6780 }
6781
6782 log_sub_test_begin() {
6783     yml_log_sub_test_begin "$@" >> $YAML_LOG
6784 }
6785
6786 log_sub_test_end() {
6787     yml_log_sub_test_end "$@" >> $YAML_LOG
6788 }
6789
6790 run_llverdev()
6791 {
6792         local dev=$1
6793         local llverdev_opts=$2
6794         local devname=$(basename $1)
6795         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
6796         # loop devices aren't in /proc/partitions
6797         [ "x$size" == "x" ] && local size=$(ls -l $dev | awk '{print $5}')
6798
6799         size=$(($size / 1024 / 1024)) # Gb
6800
6801         local partial_arg=""
6802         # Run in partial (fast) mode if the size
6803         # of a partition > 1 GB
6804         [ $size -gt 1 ] && partial_arg="-p"
6805
6806         llverdev --force $partial_arg $llverdev_opts $dev
6807 }
6808
6809 run_llverfs()
6810 {
6811         local dir=$1
6812         local llverfs_opts=$2
6813         local use_partial_arg=$3
6814         local partial_arg=""
6815         local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB
6816
6817         # Run in partial (fast) mode if the size
6818         # of a partition > 1 GB
6819         [ "x$use_partial_arg" != "xno" ] && [ $size -gt 1 ] && partial_arg="-p"
6820
6821         llverfs $partial_arg $llverfs_opts $dir
6822 }
6823
6824 #Remove objects from OST
6825 remove_ost_objects() {
6826         local facet=$1
6827         local ostdev=$2
6828         local group=$3
6829         shift 3
6830         local objids="$@"
6831         local mntpt=$(facet_mntpt $facet)
6832         local opts=$OST_MOUNT_OPTS
6833         local i
6834         local rc
6835
6836         echo "removing objects from $ostdev on $facet: $objids"
6837         if ! test -b $ostdev; then
6838                 opts=$(csa_add "$opts" -o loop)
6839         fi
6840         mount -t $(facet_fstype $facet) $opts $ostdev $mntpt ||
6841                 return $?
6842         rc=0
6843         for i in $objids; do
6844                 rm $mntpt/O/$group/d$((i % 32))/$i || { rc=$?; break; }
6845         done
6846         umount -f $mntpt || return $?
6847         return $rc
6848 }
6849
6850 #Remove files from MDT
6851 remove_mdt_files() {
6852         local facet=$1
6853         local mdtdev=$2
6854         shift 2
6855         local files="$@"
6856         local mntpt=$(facet_mntpt $facet)
6857         local opts=$MDS_MOUNT_OPTS
6858
6859         echo "removing files from $mdtdev on $facet: $files"
6860         if [ $(facet_fstype $facet) == ldiskfs ] &&
6861            ! do_facet $facet test -b $mdtdev; then
6862                 opts=$(csa_add "$opts" -o loop)
6863         fi
6864         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
6865                 return $?
6866         rc=0
6867         for f in $files; do
6868                 rm $mntpt/ROOT/$f || { rc=$?; break; }
6869         done
6870         umount -f $mntpt || return $?
6871         return $rc
6872 }
6873
6874 duplicate_mdt_files() {
6875         local facet=$1
6876         local mdtdev=$2
6877         shift 2
6878         local files="$@"
6879         local mntpt=$(facet_mntpt $facet)
6880         local opts=$MDS_MOUNT_OPTS
6881
6882         echo "duplicating files on $mdtdev on $facet: $files"
6883         mkdir -p $mntpt || return $?
6884         if [ $(facet_fstype $facet) == ldiskfs ] &&
6885            ! do_facet $facet test -b $mdtdev; then
6886                 opts=$(csa_add "$opts" -o loop)
6887         fi
6888         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
6889                 return $?
6890
6891     do_umount() {
6892         trap 0
6893         popd > /dev/null
6894         rm $tmp
6895         umount -f $mntpt
6896     }
6897     trap do_umount EXIT
6898
6899     tmp=$(mktemp $TMP/setfattr.XXXXXXXXXX)
6900     pushd $mntpt/ROOT > /dev/null || return $?
6901     rc=0
6902     for f in $files; do
6903         touch $f.bad || return $?
6904         getfattr -n trusted.lov $f | sed "s#$f#&.bad#" > $tmp
6905         rc=${PIPESTATUS[0]}
6906         [ $rc -eq 0 ] || return $rc
6907         setfattr --restore $tmp || return $?
6908     done
6909     do_umount
6910 }
6911
6912 run_sgpdd () {
6913     local devs=${1//,/ }
6914     shift
6915     local params=$@
6916     local rslt=$TMP/sgpdd_survey
6917
6918     # sgpdd-survey cleanups ${rslt}.* files
6919
6920     local cmd="rslt=$rslt $params scsidevs=\"$devs\" $SGPDDSURVEY"
6921     echo + $cmd
6922     eval $cmd
6923     cat ${rslt}.detail
6924 }
6925
6926 # returns the canonical name for an ldiskfs device
6927 ldiskfs_canon() {
6928         local dev="$1"
6929         local facet="$2"
6930
6931         do_facet $facet "dv=\\\$(lctl get_param -n $dev);
6932 if foo=\\\$(lvdisplay -c \\\$dv 2>/dev/null); then
6933     echo dm-\\\${foo##*:};
6934 else
6935     echo \\\$(basename \\\$dv);
6936 fi;"
6937 }
6938
6939 is_sanity_benchmark() {
6940     local benchmarks="dbench bonnie iozone fsx"
6941     local suite=$1
6942     for b in $benchmarks; do
6943         if [ "$b" == "$suite" ]; then
6944             return 0
6945         fi
6946     done
6947     return 1
6948 }
6949
6950 min_ost_size () {
6951     $LCTL get_param -n osc.*.kbytesavail | sort -n | head -n1
6952 }
6953
6954 #
6955 # Get the available size (KB) of a given obd target.
6956 #
6957 get_obd_size() {
6958         local facet=$1
6959         local obd=$2
6960         local size
6961
6962         [[ $facet != client ]] || return 0
6963
6964         size=$(do_facet $facet $LCTL get_param -n *.$obd.kbytesavail | head -n1)
6965         echo -n $size
6966 }
6967
6968 #
6969 # Get the page size (bytes) on a given facet node.
6970 #
6971 get_page_size() {
6972         local facet=$1
6973         local size=$(getconf PAGE_SIZE 2>/dev/null)
6974
6975         [ -z "$CLIENTONLY" ] && size=$(do_facet $facet getconf PAGE_SIZE)
6976         echo -n ${size:-4096}
6977 }
6978
6979 #
6980 # Get the block count of the filesystem.
6981 #
6982 get_block_count() {
6983         local facet=$1
6984         local device=$2
6985         local count
6986
6987         [ -z "$CLIENTONLY" ] && count=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
6988                 awk '/^Block count:/ {print $3}')
6989         echo -n ${count:-0}
6990 }
6991
6992 # Get the block size of the filesystem.
6993 get_block_size() {
6994         local facet=$1
6995         local device=$2
6996         local size
6997
6998         [ -z "$CLIENTONLY" ] && size=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
6999                 awk '/^Block size:/ {print $3}')
7000         echo -n ${size:-0}
7001 }
7002
7003 # Check whether the "large_xattr" feature is enabled or not.
7004 large_xattr_enabled() {
7005         [[ $(facet_fstype $SINGLEMDS) == zfs ]] && return 0
7006
7007         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
7008
7009         do_facet $SINGLEMDS "$DUMPE2FS -h $mds_dev 2>&1 |
7010                 grep -E -q '(ea_inode|large_xattr)'"
7011         return ${PIPESTATUS[0]}
7012 }
7013
7014 # Get the maximum xattr size supported by the filesystem.
7015 max_xattr_size() {
7016     local size
7017
7018     if large_xattr_enabled; then
7019         # include/linux/limits.h: #define XATTR_SIZE_MAX 65536
7020         size=65536
7021     else
7022         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
7023         local block_size=$(get_block_size $SINGLEMDS $mds_dev)
7024
7025         # maximum xattr size = size of block - size of header -
7026         #                      size of 1 entry - 4 null bytes
7027         size=$((block_size - 32 - 32 - 4))
7028     fi
7029
7030     echo $size
7031 }
7032
7033 # Dump the value of the named xattr from a file.
7034 get_xattr_value() {
7035     local xattr_name=$1
7036     local file=$2
7037
7038     echo "$(getfattr -n $xattr_name --absolute-names --only-values $file)"
7039 }
7040
7041 # Generate a string with size of $size bytes.
7042 generate_string() {
7043     local size=${1:-1024} # in bytes
7044
7045     echo "$(head -c $size < /dev/zero | tr '\0' y)"
7046 }
7047
7048 reformat_external_journal() {
7049         local facet=$1
7050         local var
7051
7052         var=${facet}_JRN
7053         if [ -n "${!var}" ]; then
7054                 local rcmd="do_facet $facet"
7055
7056                 echo "reformat external journal on $facet:${!var}"
7057                 ${rcmd} mke2fs -O journal_dev ${!var} || return 1
7058         fi
7059 }
7060
7061 # MDT file-level backup/restore
7062 mds_backup_restore() {
7063         local facet=$1
7064         local igif=$2
7065         local devname=$(mdsdevname $(facet_number $facet))
7066         local mntpt=$(facet_mntpt brpt)
7067         local rcmd="do_facet $facet"
7068         local metaea=${TMP}/backup_restore.ea
7069         local metadata=${TMP}/backup_restore.tgz
7070         local opts=${MDS_MOUNT_OPTS}
7071         local svc=${facet}_svc
7072
7073         if ! ${rcmd} test -b ${devname}; then
7074                 opts=$(csa_add "$opts" -o loop)
7075         fi
7076
7077         echo "file-level backup/restore on $facet:${devname}"
7078
7079         # step 1: build mount point
7080         ${rcmd} mkdir -p $mntpt
7081         # step 2: cleanup old backup
7082         ${rcmd} rm -f $metaea $metadata
7083         # step 3: mount dev
7084         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
7085         if [ ! -z $igif ]; then
7086                 # step 3.5: rm .lustre
7087                 ${rcmd} rm -rf $mntpt/ROOT/.lustre || return 1
7088         fi
7089         # step 4: backup metaea
7090         echo "backup EA"
7091         ${rcmd} "cd $mntpt && getfattr -R -d -m '.*' -P . > $metaea && cd -" ||
7092                 return 2
7093         # step 5: backup metadata
7094         echo "backup data"
7095         ${rcmd} tar zcf $metadata -C $mntpt/ . > /dev/null 2>&1 || return 3
7096         # step 6: umount
7097         ${rcmd} $UMOUNT $mntpt || return 4
7098         # step 8: reformat dev
7099         echo "reformat new device"
7100         format_mdt $(facet_number $facet)
7101         # step 9: mount dev
7102         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 7
7103         # step 10: restore metadata
7104         echo "restore data"
7105         ${rcmd} tar zxfp $metadata -C $mntpt > /dev/null 2>&1 || return 8
7106         # step 11: restore metaea
7107         echo "restore EA"
7108         ${rcmd} "cd $mntpt && setfattr --restore=$metaea && cd - " || return 9
7109         # step 12: remove recovery logs
7110         echo "remove recovery logs"
7111         ${rcmd} rm -fv $mntpt/OBJECTS/* $mntpt/CATALOGS
7112         # step 13: umount dev
7113         ${rcmd} $UMOUNT $mntpt || return 10
7114         # step 14: cleanup tmp backup
7115         ${rcmd} rm -f $metaea $metadata
7116         # step 15: reset device label - it's not virgin on
7117         ${rcmd} e2label $devname ${!svc}
7118 }
7119
7120 # remove OI files
7121 mds_remove_ois() {
7122         local facet=$1
7123         local idx=$2
7124         local devname=$(mdsdevname $(facet_number $facet))
7125         local mntpt=$(facet_mntpt brpt)
7126         local rcmd="do_facet $facet"
7127         local opts=${MDS_MOUNT_OPTS}
7128
7129         if ! ${rcmd} test -b ${devname}; then
7130                 opts=$(csa_add "$opts" -o loop)
7131         fi
7132
7133         echo "removing OI files on $facet: idx=${idx}"
7134
7135         # step 1: build mount point
7136         ${rcmd} mkdir -p $mntpt
7137         # step 2: mount dev
7138         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
7139         if [ -z $idx ]; then
7140                 # step 3: remove all OI files
7141                 ${rcmd} rm -fv $mntpt/oi.16*
7142         elif [ $idx -lt 2 ]; then
7143                 ${rcmd} rm -fv $mntpt/oi.16.${idx}
7144         else
7145                 local i
7146
7147                 # others, rm oi.16.[idx, idx * idx, idx ** ...]
7148                 for ((i=${idx}; i<64; i=$((i * idx)))); do
7149                         ${rcmd} rm -fv $mntpt/oi.16.${i}
7150                 done
7151         fi
7152         # step 4: umount
7153         ${rcmd} $UMOUNT $mntpt || return 2
7154         # OI files will be recreated when mounted as lustre next time.
7155 }
7156
7157 # generate maloo upload-able log file name
7158 # \param logname specify unique part of file name
7159 generate_logname() {
7160         local logname=${1:-"default_logname"}
7161
7162         echo "$TESTLOG_PREFIX.$TESTNAME.$logname.$(hostname -s).log"
7163 }
7164
7165 # make directory on different MDTs
7166 test_mkdir() {
7167         local path
7168         local p_option
7169         local stripe_count=2
7170         local stripe_index=-1
7171         local OPTIND=1
7172
7173         while getopts "c:i:p" opt; do
7174                 case $opt in
7175                         c) stripe_count=$OPTARG;;
7176                         i) stripe_index=$OPTARG;;
7177                         p) p_option="-p";;
7178                         \?) error "only support -i -c -p";;
7179                 esac
7180         done
7181
7182         shift $((OPTIND - 1))
7183         [ $# -eq 1 ] || error "Only creating single directory is supported"
7184         path="$*"
7185
7186         if [ "$p_option" == "-p" ]; then
7187                 local parent=$(dirname $path)
7188
7189                 [ -d $path ] && return 0
7190                 [ ! -d ${parent} ] && mkdir -p ${parent}
7191         fi
7192
7193         if [ $MDSCOUNT -le 1 ]; then
7194                 mkdir $path
7195         else
7196                 local test_num=$(echo $testnum | sed -e 's/[^0-9]*//g')
7197                 local mdt_index
7198
7199                 if [ $stripe_index -eq -1 ]; then
7200                         mdt_index=$((test_num % MDSCOUNT))
7201                 else
7202                         mdt_index=$stripe_index
7203                 fi
7204                 echo "striped dir -i$mdt_index -c$stripe_count $path"
7205                 $LFS setdirstripe -i$mdt_index -c$stripe_count $path
7206         fi
7207 }
7208
7209 # find the smallest and not in use file descriptor
7210 free_fd()
7211 {
7212         local max_fd=$(ulimit -n)
7213         local fd=3
7214         while [[ $fd -le $max_fd && -e /proc/self/fd/$fd ]]; do
7215                 ((++fd))
7216         done
7217         [ $fd -lt $max_fd ] || error "finding free file descriptor failed"
7218         echo $fd
7219 }
7220
7221 check_mount_and_prep()
7222 {
7223         is_mounted $MOUNT || setupall
7224
7225         rm -rf $DIR/[df][0-9]* || error "Fail to cleanup the env!"
7226         mkdir $DIR/$tdir || error "Fail to mkdir $DIR/$tdir."
7227         for idx in $(seq $MDSCOUNT); do
7228                 local name="MDT$(printf '%04x' $((idx - 1)))"
7229                 rm -rf $MOUNT/.lustre/lost+found/$name/*
7230         done
7231 }
7232
7233 # calcule how many ost-objects to be created.
7234 precreated_ost_obj_count()
7235 {
7236         local mdt_idx=$1
7237         local ost_idx=$2
7238         local mdt_name="MDT$(printf '%04x' $mdt_idx)"
7239         local ost_name="OST$(printf '%04x' $ost_idx)"
7240         local proc_path="${FSNAME}-${ost_name}-osc-${mdt_name}"
7241         local last_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \
7242                         osp.$proc_path.prealloc_last_id)
7243         local next_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \
7244                         osp.$proc_path.prealloc_next_id)
7245         echo $((last_id - next_id + 1))
7246 }
7247
7248 check_file_in_pool()
7249 {
7250         local file=$1
7251         local pool=$2
7252         local tlist="$3"
7253         local res=$($GETSTRIPE $file | grep 0x | cut -f2)
7254         for i in $res
7255         do
7256                 for t in $tlist ; do
7257                         [ "$i" -eq "$t" ] && continue 2
7258                 done
7259
7260                 echo "pool list: $tlist"
7261                 echo "striping: $res"
7262                 error_noexit "$file not allocated in $pool"
7263                 return 1
7264         done
7265         return 0
7266 }
7267
7268 pool_add() {
7269         echo "Creating new pool"
7270         local pool=$1
7271
7272         create_pool $FSNAME.$pool ||
7273                 { error_noexit "No pool created, result code $?"; return 1; }
7274         [ $($LFS pool_list $FSNAME | grep -c "$FSNAME.${pool}\$") -eq 1 ] ||
7275                 { error_noexit "$pool not in lfs pool_list"; return 2; }
7276 }
7277
7278 pool_add_targets() {
7279         echo "Adding targets to pool"
7280         local pool=$1
7281         local first=$2
7282         local last=$3
7283         local step=${4:-1}
7284
7285         local list=$(seq $first $step $last)
7286
7287         local t=$(for i in $list; do printf "$FSNAME-OST%04x_UUID " $i; done)
7288         do_facet mgs $LCTL pool_add \
7289                         $FSNAME.$pool $FSNAME-OST[$first-$last/$step]
7290         wait_update $HOSTNAME "lctl get_param -n lov.$FSNAME-*.pools.$pool \
7291                         | sort -u | tr '\n' ' ' " "$t" || {
7292                 error_noexit "Add to pool failed"
7293                 return 1
7294         }
7295         local lfscount=$($LFS pool_list $FSNAME.$pool | grep -c "\-OST")
7296         local addcount=$(((last - first) / step + 1))
7297         [ $lfscount -eq $addcount ] || {
7298                 error_noexit "lfs pool_list bad ost count" \
7299                                                 "$lfscount != $addcount"
7300                 return 2
7301         }
7302 }
7303
7304 pool_set_dir() {
7305         local pool=$1
7306         local tdir=$2
7307         echo "Setting pool on directory $tdir"
7308
7309         $SETSTRIPE -c 2 -p $pool $tdir && return 0
7310
7311         error_noexit "Cannot set pool $pool to $tdir"
7312         return 1
7313 }
7314
7315 pool_check_dir() {
7316         local pool=$1
7317         local tdir=$2
7318         echo "Checking pool on directory $tdir"
7319
7320         local res=$($GETSTRIPE --pool $tdir | sed "s/\s*$//")
7321         [ "$res" = "$pool" ] && return 0
7322
7323         error_noexit "Pool on '$tdir' is '$res', not '$pool'"
7324         return 1
7325 }
7326
7327 pool_dir_rel_path() {
7328         echo "Testing relative path works well"
7329         local pool=$1
7330         local tdir=$2
7331         local root=$3
7332
7333         mkdir -p $root/$tdir/$tdir
7334         cd $root/$tdir
7335         pool_set_dir $pool $tdir          || return 1
7336         pool_set_dir $pool ./$tdir        || return 2
7337         pool_set_dir $pool ../$tdir       || return 3
7338         pool_set_dir $pool ../$tdir/$tdir || return 4
7339         rm -rf $tdir; cd - > /dev/null
7340 }
7341
7342 pool_alloc_files() {
7343         echo "Checking files allocation from directory pool"
7344         local pool=$1
7345         local tdir=$2
7346         local count=$3
7347         local tlist="$4"
7348
7349         local failed=0
7350         for i in $(seq -w 1 $count)
7351         do
7352                 local file=$tdir/file-$i
7353                 touch $file
7354                 check_file_in_pool $file $pool "$tlist" || \
7355                         failed=$((failed + 1))
7356         done
7357         [ "$failed" = 0 ] && return 0
7358
7359         error_noexit "$failed files not allocated in $pool"
7360         return 1
7361 }
7362
7363 pool_create_files() {
7364         echo "Creating files in pool"
7365         local pool=$1
7366         local tdir=$2
7367         local count=$3
7368         local tlist="$4"
7369
7370         mkdir -p $tdir
7371         local failed=0
7372         for i in $(seq -w 1 $count)
7373         do
7374                 local file=$tdir/spoo-$i
7375                 $SETSTRIPE -p $pool $file
7376                 check_file_in_pool $file $pool "$tlist" || \
7377                         failed=$((failed + 1))
7378         done
7379         [ "$failed" = 0 ] && return 0
7380
7381         error_noexit "$failed files not allocated in $pool"
7382         return 1
7383 }
7384
7385 pool_lfs_df() {
7386         echo "Checking 'lfs df' output"
7387         local pool=$1
7388
7389         local t=$($LCTL get_param -n lov.$FSNAME-clilov-*.pools.$pool |
7390                         tr '\n' ' ')
7391         local res=$($LFS df --pool $FSNAME.$pool |
7392                         awk '{print $1}' |
7393                         grep "$FSNAME-OST" |
7394                         tr '\n' ' ')
7395         [ "$res" = "$t" ] && return 0
7396
7397         error_noexit "Pools OSTs '$t' is not '$res' that lfs df reports"
7398         return 1
7399 }
7400
7401 pool_file_rel_path() {
7402         echo "Creating files in a pool with relative pathname"
7403         local pool=$1
7404         local tdir=$2
7405
7406         mkdir -p $tdir ||
7407                 { error_noexit "unable to create $tdir"; return 1 ; }
7408         local file="/..$tdir/$tfile-1"
7409         $SETSTRIPE -p $pool $file ||
7410                 { error_noexit "unable to create $file" ; return 2 ; }
7411
7412         cd $tdir
7413         $SETSTRIPE -p $pool $tfile-2 || {
7414                 error_noexit "unable to create $tfile-2 in $tdir"
7415                 return 3
7416         }
7417 }
7418
7419 pool_remove_first_target() {
7420         echo "Removing first target from a pool"
7421         local pool=$1
7422
7423         local pname="lov.$FSNAME-*.pools.$pool"
7424         local t=$($LCTL get_param -n $pname | head -1)
7425         do_facet mgs $LCTL pool_remove $FSNAME.$pool $t
7426         wait_update $HOSTNAME "lctl get_param -n $pname | grep $t" "" || {
7427                 error_noexit "$t not removed from $FSNAME.$pool"
7428                 return 1
7429         }
7430 }
7431
7432 pool_remove_all_targets() {
7433         echo "Removing all targets from pool"
7434         local pool=$1
7435         local file=$2
7436         local pname="lov.$FSNAME-*.pools.$pool"
7437         for t in $($LCTL get_param -n $pname | sort -u)
7438         do
7439                 do_facet mgs $LCTL pool_remove $FSNAME.$pool $t
7440         done
7441         wait_update $HOSTNAME "lctl get_param -n $pname" "" || {
7442                 error_noexit "Pool $FSNAME.$pool cannot be drained"
7443                 return 1
7444         }
7445         # striping on an empty/nonexistant pool should fall back
7446         # to "pool of everything"
7447         touch $file || {
7448                 error_noexit "failed to use fallback striping for empty pool"
7449                 return 2
7450         }
7451         # setstripe on an empty pool should fail
7452         $SETSTRIPE -p $pool $file 2>/dev/null && {
7453                 error_noexit "expected failure when creating file" \
7454                                                         "with empty pool"
7455                 return 3
7456         }
7457         return 0
7458 }
7459
7460 pool_remove() {
7461         echo "Destroying pool"
7462         local pool=$1
7463         local file=$2
7464
7465         do_facet mgs $LCTL pool_destroy $FSNAME.$pool
7466
7467         sleep 2
7468         # striping on an empty/nonexistant pool should fall back
7469         # to "pool of everything"
7470         touch $file || {
7471                 error_noexit "failed to use fallback striping for missing pool"
7472                 return 1
7473         }
7474         # setstripe on an empty pool should fail
7475         $SETSTRIPE -p $pool $file 2>/dev/null && {
7476                 error_noexit "expected failure when creating file" \
7477                                                         "with missing pool"
7478                 return 2
7479         }
7480
7481         # get param should return err once pool is gone
7482         if wait_update $HOSTNAME "lctl get_param -n \
7483                 lov.$FSNAME-*.pools.$pool 2>/dev/null || echo foo" "foo"
7484         then
7485                 remove_pool_from_list $FSNAME.$pool
7486                 return 0
7487         fi
7488         error_noexit "Pool $FSNAME.$pool is not destroyed"
7489         return 3
7490 }
7491
7492 # Get and check the actual stripe count of one file.
7493 # Usage: check_stripe_count <file> <expected_stripe_count>
7494 check_stripe_count() {
7495         local file=$1
7496         local expected=$2
7497         local actual
7498
7499         [[ -z "$file" || -z "$expected" ]] &&
7500                 error "check_stripe_count: invalid argument"
7501
7502         local cmd="$GETSTRIPE -c $file"
7503         actual=$($cmd) || error "$cmd failed"
7504         actual=${actual%% *}
7505
7506         if [[ $actual -ne $expected ]]; then
7507                 [[ $expected -eq -1 ]] ||
7508                         error "$cmd wrong: found $actual, expected $expected"
7509                 [[ $actual -eq $OSTCOUNT ]] ||
7510                         error "$cmd wrong: found $actual, expected $OSTCOUNT"
7511         fi
7512 }
7513
7514 # Get and check the actual list of OST indices on one file.
7515 # Usage: check_obdidx <file> <expected_comma_separated_list_of_ost_indices>
7516 check_obdidx() {
7517         local file=$1
7518         local expected=$2
7519         local obdidx
7520
7521         [[ -z "$file" || -z "$expected" ]] &&
7522                 error "check_obdidx: invalid argument!"
7523
7524         obdidx=$(comma_list $($GETSTRIPE $file | grep -A $OSTCOUNT obdidx |
7525                               grep -v obdidx | awk '{print $1}' | xargs))
7526
7527         [[ $obdidx = $expected ]] ||
7528                 error "list of OST indices on $file is $obdidx," \
7529                       "should be $expected"
7530 }
7531
7532 # Get and check the actual OST index of the first stripe on one file.
7533 # Usage: check_start_ost_idx <file> <expected_start_ost_idx>
7534 check_start_ost_idx() {
7535         local file=$1
7536         local expected=$2
7537         local start_ost_idx
7538
7539         [[ -z "$file" || -z "$expected" ]] &&
7540                 error "check_start_ost_idx: invalid argument!"
7541
7542         start_ost_idx=$($GETSTRIPE $file | grep -A 1 obdidx | grep -v obdidx |
7543                         awk '{print $1}')
7544
7545         [[ $start_ost_idx = $expected ]] ||
7546                 error "OST index of the first stripe on $file is" \
7547                       "$start_ost_idx, should be $expected"
7548 }
7549
7550 killall_process () {
7551         local clients=${1:-$(hostname)}
7552         local name=$2
7553         local signal=$3
7554         local rc=0
7555
7556         do_nodes $clients "killall $signal $name"
7557 }