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