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