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