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