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