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