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