Whamcloud - gitweb
LU-2827 ldlm: wrong handling of ldlm resends
[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         eval "$@" || 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         eval "$@" || 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     local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4386     do_nodes $list lctl set_param fail_loc=0x30c
4387
4388     do_facet client "$@" || RC=$?
4389
4390     do_nodes $list lctl set_param fail_loc=0
4391     return $RC
4392 }
4393
4394 drop_ldlm_reply_once() {
4395 #define OBD_FAIL_LDLM_REPLY              0x30c
4396     RC=0
4397     local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4398     do_nodes $list lctl set_param fail_loc=0x8000030c
4399
4400     do_facet client "$@" || RC=$?
4401
4402     do_nodes $list lctl set_param fail_loc=0
4403     return $RC
4404 }
4405
4406 clear_failloc() {
4407     facet=$1
4408     pause=$2
4409     sleep $pause
4410     echo "clearing fail_loc on $facet"
4411     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
4412 }
4413
4414 set_nodes_failloc () {
4415         do_nodes $(comma_list $1)  lctl set_param fail_val=0 fail_loc=$2
4416 }
4417
4418 cancel_lru_locks() {
4419     $LCTL mark "cancel_lru_locks $1 start"
4420     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
4421         $LCTL set_param -n $d=clear
4422     done
4423     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
4424     $LCTL mark "cancel_lru_locks $1 stop"
4425 }
4426
4427 default_lru_size()
4428 {
4429         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
4430         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
4431         echo "$DEFAULT_LRU_SIZE"
4432 }
4433
4434 lru_resize_enable()
4435 {
4436     lctl set_param ldlm.namespaces.*$1*.lru_size=0
4437 }
4438
4439 lru_resize_disable()
4440 {
4441     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
4442 }
4443
4444 flock_is_enabled()
4445 {
4446         local RC=0
4447         [ -z "$(mount | grep "$MOUNT.*flock" | grep -v noflock)" ] && RC=1
4448         return $RC
4449 }
4450
4451 pgcache_empty() {
4452     local FILE
4453     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
4454         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
4455             echo there is still data in page cache $FILE ?
4456             lctl get_param -n $FILE
4457             return 1
4458         fi
4459     done
4460     return 0
4461 }
4462
4463 debugsave() {
4464     DEBUGSAVE="$(lctl get_param -n debug)"
4465 }
4466
4467 debugrestore() {
4468     [ -n "$DEBUGSAVE" ] && \
4469         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
4470     DEBUGSAVE=""
4471 }
4472
4473 debug_size_save() {
4474     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
4475 }
4476
4477 debug_size_restore() {
4478     [ -n "$DEBUG_SIZE_SAVED" ] && \
4479         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
4480     DEBUG_SIZE_SAVED=""
4481 }
4482
4483 start_full_debug_logging() {
4484     debugsave
4485     debug_size_save
4486
4487     local FULLDEBUG=-1
4488     local DEBUG_SIZE=150
4489
4490     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
4491     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
4492 }
4493
4494 stop_full_debug_logging() {
4495     debug_size_restore
4496     debugrestore
4497 }
4498
4499 # prints bash call stack
4500 log_trace_dump() {
4501         echo "  Trace dump:"
4502         for (( i=1; i < ${#BASH_LINENO[*]} ; i++ )) ; do
4503                 local s=${BASH_SOURCE[$i]}
4504                 local l=${BASH_LINENO[$i-1]}
4505                 local f=${FUNCNAME[$i]}
4506                 echo "  = $s:$l:$f()"
4507         done
4508 }
4509
4510 ##################################
4511 # Test interface
4512 ##################################
4513
4514 error_noexit() {
4515         local TYPE=${TYPE:-"FAIL"}
4516
4517         local dump=true
4518         # do not dump logs if $1=false
4519         if [ "x$1" = "xfalse" ]; then
4520                 shift
4521                 dump=false
4522         fi
4523
4524
4525         log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
4526         log_trace_dump
4527
4528         mkdir -p $LOGDIR
4529         # We need to dump the logs on all nodes
4530         if $dump; then
4531                 gather_logs $(comma_list $(nodes_list))
4532         fi
4533
4534         debugrestore
4535         [ "$TESTSUITELOG" ] &&
4536                 echo "$TESTSUITE: $TYPE: $TESTNAME $@" >> $TESTSUITELOG
4537         if [ -z "$*" ]; then
4538                 echo "error() without useful message, please fix" > $LOGDIR/err
4539         else
4540                 if [[ `echo $TYPE | grep ^IGNORE` ]]; then
4541                         echo "$@" > $LOGDIR/ignore
4542                 else
4543                         echo "$@" > $LOGDIR/err
4544                 fi
4545         fi
4546 }
4547
4548 exit_status () {
4549         local status=0
4550         local log=$TESTSUITELOG
4551
4552         [ -f "$log" ] && grep -q FAIL $log && status=1
4553         exit $status
4554 }
4555
4556 error() {
4557         error_noexit "$@"
4558         exit 1
4559 }
4560
4561 error_exit() {
4562         error "$@"
4563 }
4564
4565 # use only if we are ignoring failures for this test, bugno required.
4566 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
4567 # e.g. error_ignore bz5494 "your message" or
4568 # error_ignore LU-5494 "your message"
4569 error_ignore() {
4570         local TYPE="IGNORE ($1)"
4571         shift
4572         error_noexit "$@"
4573 }
4574
4575 error_and_remount() {
4576         error_noexit "$@"
4577         remount_client $MOUNT
4578         exit 1
4579 }
4580
4581 skip_env () {
4582         $FAIL_ON_SKIP_ENV && error false $@ || skip $@
4583 }
4584
4585 skip() {
4586         echo
4587         log " SKIP: $TESTSUITE $TESTNAME $@"
4588
4589         if [[ -n "$ALWAYS_SKIPPED" ]]; then
4590                 skip_logged $TESTNAME "$@"
4591         else
4592                 mkdir -p $LOGDIR
4593                 echo "$@" > $LOGDIR/skip
4594         fi
4595
4596         [[ -n "$TESTSUITELOG" ]] &&
4597                 echo "$TESTSUITE: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
4598 }
4599
4600 build_test_filter() {
4601     EXCEPT="$EXCEPT $(testslist_filter)"
4602
4603         for O in $ONLY; do
4604                 if [[ $O = [0-9]*-[0-9]* ]]; then
4605                         for num in $(seq $(echo $O | tr '-' ' ')); do
4606                                 eval ONLY_$num=true
4607                         done
4608                 else
4609                         eval ONLY_${O}=true
4610                 fi
4611         done
4612
4613     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
4614         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
4615     [ "$EXCEPT_SLOW" ] && \
4616         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
4617     for E in $EXCEPT; do
4618         eval EXCEPT_${E}=true
4619     done
4620     for E in $ALWAYS_EXCEPT; do
4621         eval EXCEPT_ALWAYS_${E}=true
4622     done
4623     for E in $EXCEPT_SLOW; do
4624         eval EXCEPT_SLOW_${E}=true
4625     done
4626     for G in $GRANT_CHECK_LIST; do
4627         eval GCHECK_ONLY_${G}=true
4628         done
4629 }
4630
4631 basetest() {
4632     if [[ $1 = [a-z]* ]]; then
4633         echo $1
4634     else
4635         echo ${1%%[a-z]*}
4636     fi
4637 }
4638
4639 # print a newline if the last test was skipped
4640 export LAST_SKIPPED=
4641 export ALWAYS_SKIPPED=
4642 #
4643 # Main entry into test-framework. This is called with the name and
4644 # description of a test. The name is used to find the function to run
4645 # the test using "test_$name".
4646 #
4647 # This supports a variety of methods of specifying specific test to
4648 # run or not run.  These need to be documented...
4649 #
4650 run_test() {
4651         assert_DIR
4652
4653         export base=$(basetest $1)
4654         if [ -n "$ONLY" ]; then
4655                 testname=ONLY_$1
4656                 if [ ${!testname}x != x ]; then
4657                         [ -n "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
4658                         run_one_logged $1 "$2"
4659                         return $?
4660                 fi
4661                 testname=ONLY_$base
4662                 if [ ${!testname}x != x ]; then
4663                         [ -n "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
4664                         run_one_logged $1 "$2"
4665                         return $?
4666                 fi
4667                 LAST_SKIPPED="y"
4668                 return 0
4669         fi
4670
4671         LAST_SKIPPED="y"
4672         ALWAYS_SKIPPED="y"
4673         testname=EXCEPT_$1
4674         if [ ${!testname}x != x ]; then
4675                 TESTNAME=test_$1 skip "skipping excluded test $1"
4676                 return 0
4677         fi
4678         testname=EXCEPT_$base
4679         if [ ${!testname}x != x ]; then
4680                 TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
4681                 return 0
4682         fi
4683         testname=EXCEPT_ALWAYS_$1
4684         if [ ${!testname}x != x ]; then
4685                 TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1"
4686                 return 0
4687         fi
4688         testname=EXCEPT_ALWAYS_$base
4689         if [ ${!testname}x != x ]; then
4690                 TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1 (base $base)"
4691                 return 0
4692         fi
4693         testname=EXCEPT_SLOW_$1
4694         if [ ${!testname}x != x ]; then
4695                 TESTNAME=test_$1 skip "skipping SLOW test $1"
4696                 return 0
4697         fi
4698         testname=EXCEPT_SLOW_$base
4699         if [ ${!testname}x != x ]; then
4700                 TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
4701                 return 0
4702         fi
4703
4704         LAST_SKIPPED=
4705         ALWAYS_SKIPPED=
4706         run_one_logged $1 "$2"
4707
4708         return $?
4709 }
4710
4711 log() {
4712     echo "$*"
4713     module_loaded lnet || load_modules
4714
4715     local MSG="$*"
4716     # Get rid of '
4717     MSG=${MSG//\'/\\\'}
4718     MSG=${MSG//\(/\\\(}
4719     MSG=${MSG//\)/\\\)}
4720     MSG=${MSG//\;/\\\;}
4721     MSG=${MSG//\|/\\\|}
4722     MSG=${MSG//\>/\\\>}
4723     MSG=${MSG//\</\\\<}
4724     MSG=${MSG//\//\\\/}
4725     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
4726 }
4727
4728 trace() {
4729         log "STARTING: $*"
4730         strace -o $TMP/$1.strace -ttt $*
4731         RC=$?
4732         log "FINISHED: $*: rc $RC"
4733         return 1
4734 }
4735
4736 complete () {
4737     local duration=$1
4738
4739     banner test complete, duration $duration sec
4740     [ -f "$TESTSUITELOG" ] && egrep .FAIL $TESTSUITELOG || true
4741     echo duration $duration >>$TESTSUITELOG
4742 }
4743
4744 pass() {
4745         # Set TEST_STATUS here. It will be used for logging the result.
4746         TEST_STATUS="PASS"
4747
4748         if [[ -f $LOGDIR/err ]]; then
4749                 TEST_STATUS="FAIL"
4750         elif [[ -f $LOGDIR/skip ]]; then
4751                 TEST_STATUS="SKIP"
4752         fi
4753         echo "$TEST_STATUS $@" 2>&1 | tee -a $TESTSUITELOG
4754 }
4755
4756 check_mds() {
4757     local FFREE=$(do_node $SINGLEMDS \
4758         lctl get_param -n osd*.*MDT*.filesfree | calc_sum)
4759     local FTOTAL=$(do_node $SINGLEMDS \
4760         lctl get_param -n osd*.*MDT*.filestotal | calc_sum)
4761
4762     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
4763 }
4764
4765 reset_fail_loc () {
4766     echo -n "Resetting fail_loc on all nodes..."
4767     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
4768     echo done.
4769 }
4770
4771
4772 #
4773 # Log a message (on all nodes) padded with "=" before and after. 
4774 # Also appends a timestamp and prepends the testsuite name.
4775
4776
4777 EQUALS="===================================================================================================="
4778 banner() {
4779     msg="== ${TESTSUITE} $*"
4780     last=${msg: -1:1}
4781     [[ $last != "=" && $last != " " ]] && msg="$msg "
4782     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
4783     # always include at least == after the message
4784     log "$msg== $(date +"%H:%M:%S (%s)")"
4785 }
4786
4787 #
4788 # Run a single test function and cleanup after it.
4789 #
4790 # This function should be run in a subshell so the test func can
4791 # exit() without stopping the whole script.
4792 #
4793 run_one() {
4794         local testnum=$1
4795         local message=$2
4796         export tfile=f${testnum}.${TESTSUITE}
4797         export tdir=d${testnum}.${TESTSUITE}
4798         export TESTNAME=test_$testnum
4799         local SAVE_UMASK=`umask`
4800         umask 0022
4801
4802         banner "test $testnum: $message"
4803         test_${testnum} || error "test_$testnum failed with $?"
4804         cd $SAVE_PWD
4805         reset_fail_loc
4806         check_grant ${testnum} || error "check_grant $testnum failed with $?"
4807         check_catastrophe || error "LBUG/LASSERT detected"
4808         if [ "$PARALLEL" != "yes" ]; then
4809                 ps auxww | grep -v grep | grep -q multiop &&
4810                                         error "multiop still running"
4811         fi
4812         unset TESTNAME
4813         unset tdir
4814         unset tfile
4815         umask $SAVE_UMASK
4816         return 0
4817 }
4818
4819 #
4820 # Wrapper around run_one to ensure:
4821 #  - test runs in subshell
4822 #  - output of test is saved to separate log file for error reporting
4823 #  - test result is saved to data file
4824 #
4825 run_one_logged() {
4826         local BEFORE=$(date +%s)
4827         local TEST_ERROR
4828         local name=${TESTSUITE}.test_${1}.test_log.$(hostname -s).log
4829         local test_log=$LOGDIR/$name
4830         rm -rf $LOGDIR/err
4831         rm -rf $LOGDIR/ignore
4832         rm -rf $LOGDIR/skip
4833         local SAVE_UMASK=$(umask)
4834         umask 0022
4835
4836         echo
4837         log_sub_test_begin test_${1}
4838         (run_one $1 "$2") 2>&1 | tee -i $test_log
4839         local RC=${PIPESTATUS[0]}
4840
4841         [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] &&
4842                 echo "test_$1 returned $RC" | tee $LOGDIR/err
4843
4844         duration=$(($(date +%s) - $BEFORE))
4845         pass "$1" "(${duration}s)"
4846
4847         if [[ -f $LOGDIR/err ]]; then
4848                 TEST_ERROR=$(cat $LOGDIR/err)
4849         elif [[ -f $LOGDIR/ignore ]]; then
4850                 TEST_ERROR=$(cat $LOGDIR/ignore)
4851         elif [[ -f $LOGDIR/skip ]]; then
4852                 TEST_ERROR=$(cat $LOGDIR/skip)
4853         fi
4854         log_sub_test_end $TEST_STATUS $duration "$RC" "$TEST_ERROR"
4855
4856         if [[ "$TEST_STATUS" != "SKIP" ]] && [[ -f $TF_SKIP ]]; then
4857                 rm -f $TF_SKIP
4858         fi
4859
4860         if [ -f $LOGDIR/err ]; then
4861                 $FAIL_ON_ERROR && exit $RC
4862         fi
4863
4864         umask $SAVE_UMASK
4865
4866         return 0
4867 }
4868
4869 #
4870 # Print information of skipped tests to result.yml
4871 #
4872 skip_logged(){
4873         log_sub_test_begin $1
4874         shift
4875         log_sub_test_end "SKIP" "0" "0" "$@"
4876 }
4877
4878 canonical_path() {
4879         (cd $(dirname $1); echo $PWD/$(basename $1))
4880 }
4881
4882
4883 check_grant() {
4884         export base=$(basetest $1)
4885         [ "$CHECK_GRANT" == "no" ] && return 0
4886
4887         testname=GCHECK_ONLY_${base}
4888         [ ${!testname}x == x ] && return 0
4889
4890         echo -n "checking grant......"
4891
4892         local clients=$CLIENTS
4893         [ -z "$clients" ] && clients=$(hostname)
4894
4895         # sync all the data and make sure no pending data on server
4896         do_nodes $clients sync
4897
4898         # get client grant
4899         client_grant=$(do_nodes $clients \
4900                 "$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes" |
4901                 awk '{ total += $1 } END { printf("%0.0f", total) }')
4902
4903         # get server grant
4904         server_grant=$(do_nodes $(comma_list $(osts_nodes)) \
4905                 "$LCTL get_param -n obdfilter.${FSNAME}-OST*.tot_granted" |
4906                 awk '{ total += $1 } END { printf("%0.0f", total) }')
4907
4908         # check whether client grant == server grant
4909         if [[ $client_grant -ne $server_grant ]]; then
4910                 echo "failed: client:${client_grant} server: ${server_grant}."
4911                 do_nodes $(comma_list $(osts_nodes)) \
4912                         "$LCTL get_param obdfilter.${FSNAME}-OST*.tot*"
4913                 do_nodes $clients "$LCTL get_param osc.${FSNAME}-*.cur_*_bytes"
4914                 return 1
4915         else
4916                 echo "pass: client:${client_grant} server: ${server_grant}"
4917         fi
4918 }
4919
4920 ########################
4921 # helper functions
4922
4923 osc_to_ost()
4924 {
4925     osc=$1
4926     ost=`echo $1 | awk -F_ '{print $3}'`
4927     if [ -z $ost ]; then
4928         ost=`echo $1 | sed 's/-osc.*//'`
4929     fi
4930     echo $ost
4931 }
4932
4933 ostuuid_from_index()
4934 {
4935     $LFS osts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
4936 }
4937
4938 ostname_from_index() {
4939     local uuid=$(ostuuid_from_index $1)
4940     echo ${uuid/_UUID/}
4941 }
4942
4943 index_from_ostuuid()
4944 {
4945     $LFS osts $2 | sed -ne "/${1}/s/\(.*\): .* .*$/\1/p"
4946 }
4947
4948 mdtuuid_from_index()
4949 {
4950     $LFS mdts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
4951 }
4952
4953 # Description:
4954 #   Return unique identifier for given hostname
4955 host_id() {
4956         local host_name=$1
4957         echo $host_name | md5sum | cut -d' ' -f1
4958 }
4959
4960 # Description:
4961 #   Returns list of ip addresses for each interface
4962 local_addr_list() {
4963         ip addr | awk '/inet\ / {print $2}' | awk -F\/ '{print $1}'
4964 }
4965
4966 is_local_addr() {
4967         local addr=$1
4968         # Cache address list to avoid mutiple execution of local_addr_list
4969         LOCAL_ADDR_LIST=${LOCAL_ADDR_LIST:-$(local_addr_list)}
4970         local i
4971         for i in $LOCAL_ADDR_LIST ; do
4972                 [[ "$i" == "$addr" ]] && return 0
4973         done
4974         return 1
4975 }
4976
4977 local_node() {
4978         local host_name=$1
4979         local is_local="IS_LOCAL_$(host_id $host_name)"
4980         if [ -z "${!is_local-}" ] ; then
4981                 eval $is_local=0
4982                 local host_ip=$($LUSTRE/tests/resolveip $host_name)
4983                 is_local_addr "$host_ip" && eval $is_local=1
4984         fi
4985         [[ "${!is_local}" == "1" ]]
4986 }
4987
4988 remote_node () {
4989         local node=$1
4990         local_node $node && return 1
4991         return 0
4992 }
4993
4994 remote_mds ()
4995 {
4996     local node
4997     for node in $(mdts_nodes); do
4998         remote_node $node && return 0
4999     done
5000     return 1
5001 }
5002
5003 remote_mds_nodsh()
5004 {
5005     [ "$CLIENTONLY" ] && return 0 || true
5006     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
5007 }
5008
5009 require_dsh_mds()
5010 {
5011         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
5012             MSKIPPED=1 && return 1
5013         return 0
5014 }
5015
5016 remote_ost ()
5017 {
5018     local node
5019     for node in $(osts_nodes) ; do
5020         remote_node $node && return 0
5021     done
5022     return 1
5023 }
5024
5025 remote_ost_nodsh()
5026 {
5027     [ "$CLIENTONLY" ] && return 0 || true 
5028     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
5029 }
5030
5031 require_dsh_ost()
5032 {
5033         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
5034             OSKIPPED=1 && return 1
5035         return 0
5036 }
5037
5038 remote_mgs_nodsh()
5039 {
5040     local MGS 
5041     MGS=$(facet_host mgs)
5042     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
5043 }
5044
5045 local_mode ()
5046 {
5047     remote_mds_nodsh || remote_ost_nodsh || \
5048         $(single_local_node $(comma_list $(nodes_list)))
5049 }
5050
5051 remote_servers () {
5052     remote_ost && remote_mds
5053 }
5054
5055 # Get the active nodes for facets.
5056 facets_nodes () {
5057         local facets=$1
5058         local facet
5059         local nodes
5060         local nodes_sort
5061         local i
5062
5063         for facet in ${facets//,/ }; do
5064                 nodes="$nodes $(facet_active_host $facet)"
5065         done
5066
5067         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5068         echo -n $nodes_sort
5069 }
5070
5071 # Get all of the active MDS nodes.
5072 mdts_nodes () {
5073         echo -n $(facets_nodes $(get_facets MDS))
5074 }
5075
5076 # Get all of the active OSS nodes.
5077 osts_nodes () {
5078         echo -n $(facets_nodes $(get_facets OST))
5079 }
5080
5081 # Get all of the active AGT (HSM agent) nodes.
5082 agts_nodes () {
5083         echo -n $(facets_nodes $(get_facets AGT))
5084 }
5085
5086 # Get all of the client nodes and active server nodes.
5087 nodes_list () {
5088         local nodes=$HOSTNAME
5089         local nodes_sort
5090         local i
5091
5092         # CLIENTS (if specified) contains the local client
5093         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
5094
5095         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
5096                 nodes="$nodes $(facets_nodes $(get_facets))"
5097         fi
5098
5099         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5100         echo -n $nodes_sort
5101 }
5102
5103 # Get all of the remote client nodes and remote active server nodes.
5104 remote_nodes_list () {
5105         echo -n $(nodes_list) | sed -re "s/\<$HOSTNAME\>//g"
5106 }
5107
5108 # Get all of the MDS nodes, including active and passive nodes.
5109 all_mdts_nodes () {
5110         local host
5111         local failover_host
5112         local nodes
5113         local nodes_sort
5114         local i
5115
5116         for i in $(seq $MDSCOUNT); do
5117                 host=mds${i}_HOST
5118                 failover_host=mds${i}failover_HOST
5119                 nodes="$nodes ${!host} ${!failover_host}"
5120         done
5121
5122         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5123         echo -n $nodes_sort
5124 }
5125
5126 # Get all of the OSS nodes, including active and passive nodes.
5127 all_osts_nodes () {
5128         local host
5129         local failover_host
5130         local nodes
5131         local nodes_sort
5132         local i
5133
5134         for i in $(seq $OSTCOUNT); do
5135                 host=ost${i}_HOST
5136                 failover_host=ost${i}failover_HOST
5137                 nodes="$nodes ${!host} ${!failover_host}"
5138         done
5139
5140         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5141         echo -n $nodes_sort
5142 }
5143
5144 # Get all of the server nodes, including active and passive nodes.
5145 all_server_nodes () {
5146         local nodes
5147         local nodes_sort
5148         local i
5149
5150         nodes="$mgs_HOST $mgsfailover_HOST $(all_mdts_nodes) $(all_osts_nodes)"
5151
5152         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5153         echo -n $nodes_sort
5154 }
5155
5156 # Get all of the client and server nodes, including active and passive nodes.
5157 all_nodes () {
5158         local nodes=$HOSTNAME
5159         local nodes_sort
5160         local i
5161
5162         # CLIENTS (if specified) contains the local client
5163         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
5164
5165         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
5166                 nodes="$nodes $(all_server_nodes)"
5167         fi
5168
5169         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5170         echo -n $nodes_sort
5171 }
5172
5173 init_clients_lists () {
5174     # Sanity check: exclude the local client from RCLIENTS
5175     local clients=$(hostlist_expand "$RCLIENTS")
5176     local rclients=$(exclude_items_from_list "$clients" $HOSTNAME)
5177
5178     # Sanity check: exclude the dup entries
5179     RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)
5180
5181     clients="$SINGLECLIENT $HOSTNAME $RCLIENTS"
5182
5183     # Sanity check: exclude the dup entries from CLIENTS
5184     # for those configs which has SINGLCLIENT set to local client
5185     clients=$(for i in $clients; do echo $i; done | sort -u)
5186
5187     CLIENTS=$(comma_list $clients)
5188     local -a remoteclients=($RCLIENTS)
5189     for ((i=0; $i<${#remoteclients[@]}; i++)); do
5190             varname=CLIENT$((i + 2))
5191             eval $varname=${remoteclients[i]}
5192     done
5193
5194     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
5195 }
5196
5197 get_random_entry () {
5198     local rnodes=$1
5199
5200     rnodes=${rnodes//,/ }
5201
5202     local -a nodes=($rnodes)
5203     local num=${#nodes[@]} 
5204     local i=$((RANDOM * num * 2 / 65536))
5205
5206     echo ${nodes[i]}
5207 }
5208
5209 client_only () {
5210     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
5211 }
5212
5213 is_patchless ()
5214 {
5215     lctl get_param version | grep -q patchless
5216 }
5217
5218 check_versions () {
5219     [ "$(lustre_version_code client)" = "$(lustre_version_code $SINGLEMDS)" -a \
5220       "$(lustre_version_code client)" = "$(lustre_version_code ost1)" ]
5221 }
5222
5223 get_node_count() {
5224     local nodes="$@"
5225     echo $nodes | wc -w || true
5226 }
5227
5228 mixed_ost_devs () {
5229     local nodes=$(osts_nodes)
5230     local osscount=$(get_node_count "$nodes")
5231     [ ! "$OSTCOUNT" = "$osscount" ]
5232 }
5233
5234 mixed_mdt_devs () {
5235     local nodes=$(mdts_nodes)
5236     local mdtcount=$(get_node_count "$nodes")
5237     [ ! "$MDSCOUNT" = "$mdtcount" ]
5238 }
5239
5240 generate_machine_file() {
5241     local nodes=${1//,/ }
5242     local machinefile=$2
5243     rm -f $machinefile
5244     for node in $nodes; do
5245         echo $node >>$machinefile || \
5246             { echo "can not generate machinefile $machinefile" && return 1; }
5247     done
5248 }
5249
5250 get_stripe () {
5251         local file=$1/stripe
5252
5253         touch $file
5254         $LFS getstripe -v $file || error "getstripe $file failed"
5255         rm -f $file
5256 }
5257
5258 setstripe_nfsserver () {
5259         local dir=$1
5260
5261         local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
5262                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -n1)
5263
5264         [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
5265
5266         do_nodev $nfsserver lfs setstripe "$@"
5267 }
5268
5269 # Check and add a test group.
5270 add_group() {
5271         local group_id=$1
5272         local group_name=$2
5273         local rc=0
5274
5275         local gid=$(getent group $group_name | cut -d: -f3)
5276         if [[ -n "$gid" ]]; then
5277                 [[ "$gid" -eq "$group_id" ]] || {
5278                         error_noexit "inconsistent group ID:" \
5279                                      "new: $group_id, old: $gid"
5280                         rc=1
5281                 }
5282         else
5283                 groupadd -g $group_id $group_name
5284                 rc=${PIPESTATUS[0]}
5285         fi
5286
5287         return $rc
5288 }
5289
5290 # Check and add a test user.
5291 add_user() {
5292         local user_id=$1
5293         shift
5294         local user_name=$1
5295         shift
5296         local group_name=$1
5297         shift
5298         local home=$1
5299         shift
5300         local opts="$@"
5301         local rc=0
5302
5303         local uid=$(getent passwd $user_name | cut -d: -f3)
5304         if [[ -n "$uid" ]]; then
5305                 if [[ "$uid" -eq "$user_id" ]]; then
5306                         local dir=$(getent passwd $user_name | cut -d: -f6)
5307                         if [[ "$dir" != "$home" ]]; then
5308                                 mkdir -p $home
5309                                 usermod -d $home $user_name
5310                                 rc=${PIPESTATUS[0]}
5311                         fi
5312                 else
5313                         error_noexit "inconsistent user ID:" \
5314                                      "new: $user_id, old: $uid"
5315                         rc=1
5316                 fi
5317         else
5318                 mkdir -p $home
5319                 useradd -M -u $user_id -d $home -g $group_name $opts $user_name
5320                 rc=${PIPESTATUS[0]}
5321         fi
5322
5323         return $rc
5324 }
5325
5326 check_runas_id_ret() {
5327     local myRC=0
5328     local myRUNAS_UID=$1
5329     local myRUNAS_GID=$2
5330     shift 2
5331     local myRUNAS=$@
5332     if [ -z "$myRUNAS" ]; then
5333         error_exit "myRUNAS command must be specified for check_runas_id"
5334     fi
5335     if $GSS_KRB5; then
5336         $myRUNAS krb5_login.sh || \
5337             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
5338     fi
5339     mkdir $DIR/d0_runas_test
5340     chmod 0755 $DIR
5341     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
5342     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
5343     rm -rf $DIR/d0_runas_test
5344     return $myRC
5345 }
5346
5347 check_runas_id() {
5348     local myRUNAS_UID=$1
5349     local myRUNAS_GID=$2
5350     shift 2
5351     local myRUNAS=$@
5352     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
5353         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
5354         Please set RUNAS_ID to some UID which exists on MDS and client or
5355         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
5356 }
5357
5358 # obtain the UID/GID for MPI_USER
5359 get_mpiuser_id() {
5360     local mpi_user=$1
5361
5362     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
5363 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
5364
5365     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
5366 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
5367 }
5368
5369 # obtain and cache Kerberos ticket-granting ticket
5370 refresh_krb5_tgt() {
5371     local myRUNAS_UID=$1
5372     local myRUNAS_GID=$2
5373     shift 2
5374     local myRUNAS=$@
5375     if [ -z "$myRUNAS" ]; then
5376         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
5377     fi
5378
5379     CLIENTS=${CLIENTS:-$HOSTNAME}
5380     do_nodes $CLIENTS "set -x
5381 if ! $myRUNAS krb5_login.sh; then
5382     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
5383     exit 1
5384 fi"
5385 }
5386
5387 # Run multiop in the background, but wait for it to print
5388 # "PAUSING" to its stdout before returning from this function.
5389 multiop_bg_pause() {
5390     MULTIOP_PROG=${MULTIOP_PROG:-$MULTIOP}
5391     FILE=$1
5392     ARGS=$2
5393
5394     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
5395     mkfifo $TMPPIPE
5396
5397     echo "$MULTIOP_PROG $FILE v$ARGS"
5398     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
5399
5400     echo "TMPPIPE=${TMPPIPE}"
5401     read -t 60 multiop_output < $TMPPIPE
5402     if [ $? -ne 0 ]; then
5403         rm -f $TMPPIPE
5404         return 1
5405     fi
5406     rm -f $TMPPIPE
5407     if [ "$multiop_output" != "PAUSING" ]; then
5408         echo "Incorrect multiop output: $multiop_output"
5409         kill -9 $PID
5410         return 1
5411     fi
5412
5413     return 0
5414 }
5415
5416 do_and_time () {
5417     local cmd=$1
5418     local rc
5419
5420     SECONDS=0
5421     eval '$cmd'
5422
5423     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
5424
5425     echo $SECONDS
5426     return $rc
5427 }
5428
5429 inodes_available () {
5430         local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{ print $4 }' |
5431                 sort -un | head -n1) || return 1
5432         echo $((IFree))
5433 }
5434
5435 mdsrate_inodes_available () {
5436     local min_inodes=$(inodes_available)
5437     echo $((min_inodes * 99 / 100))
5438 }
5439
5440 # reset llite stat counters
5441 clear_llite_stats(){
5442         lctl set_param -n llite.*.stats 0
5443 }
5444
5445 # sum llite stat items
5446 calc_llite_stats() {
5447         local res=$(lctl get_param -n llite.*.stats |
5448                 awk '/^'"$1"'/ {sum += $2} END { printf("%0.0f", sum) }')
5449         echo $((res))
5450 }
5451
5452 # reset osc stat counters
5453 clear_osc_stats(){
5454         lctl set_param -n osc.*.osc_stats 0
5455 }
5456
5457 # sum osc stat items
5458 calc_osc_stats() {
5459         local res=$(lctl get_param -n osc.*.osc_stats |
5460                 awk '/^'"$1"'/ {sum += $2} END { printf("%0.0f", sum) }')
5461         echo $((res))
5462 }
5463
5464 calc_sum () {
5465         awk '{sum += $1} END { printf("%0.0f", sum) }'
5466 }
5467
5468 calc_osc_kbytes () {
5469         df $MOUNT > /dev/null
5470         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
5471 }
5472
5473 # save_lustre_params(comma separated facet list, parameter_mask)
5474 # generate a stream of formatted strings (<facet> <param name>=<param value>)
5475 save_lustre_params() {
5476         local facets=$1
5477         local facet
5478         local nodes
5479         local node
5480
5481         for facet in ${facets//,/ }; do
5482                 node=$(facet_active_host $facet)
5483                 [[ *\ $node\ * = " $nodes " ]] && continue
5484                 nodes="$nodes $node"
5485
5486                 do_node $node "$LCTL get_param $2 |
5487                         while read s; do echo $facet \\\$s; done"
5488         done
5489 }
5490
5491 # restore lustre parameters from input stream, produces by save_lustre_params
5492 restore_lustre_params() {
5493         local facet
5494         local name
5495         local val
5496
5497         while IFS=" =" read facet name val; do
5498                 do_facet $facet "$LCTL set_param -n $name $val"
5499         done
5500 }
5501
5502 check_catastrophe() {
5503         local rnodes=${1:-$(comma_list $(remote_nodes_list))}
5504         local C=$CATASTROPHE
5505         [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
5506
5507         [ -z "$rnodes" ] && return 0
5508
5509         local data
5510         data=$(do_nodes "$rnodes" "rc=\\\$([ -f $C ] &&
5511                 echo \\\$(< $C) || echo 0);
5512                 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
5513                 exit \\\$rc")
5514         local rc=$?
5515         if [ -n "$data" ]; then
5516             echo $data
5517             return $rc
5518         fi
5519         return 0
5520 }
5521
5522 # CMD: determine mds index where directory inode presents
5523 get_mds_dir () {
5524     local dir=$1
5525     local file=$dir/f0.get_mds_dir_tmpfile
5526
5527     mkdir -p $dir
5528     rm -f $file
5529     sleep 1
5530     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
5531     local -a oldused=($iused)
5532
5533     openfile -f O_CREAT:O_LOV_DELAY_CREATE -m 0644 $file > /dev/null
5534     sleep 1
5535     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
5536     local -a newused=($iused)
5537
5538     local num=0
5539     for ((i=0; i<${#newused[@]}; i++)); do
5540          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
5541              echo $(( i + 1 ))
5542              rm -f $file
5543              return 0
5544          fi
5545     done
5546     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
5547 }
5548
5549 mdsrate_cleanup () {
5550         if [ -d $4 ]; then
5551                 mpi_run ${MACHINEFILE_OPTION} $2 -np $1 ${MDSRATE} --unlink \
5552                         --nfiles $3 --dir $4 --filefmt $5 $6
5553                 rmdir $4
5554         fi
5555 }
5556
5557 delayed_recovery_enabled () {
5558     local var=${SINGLEMDS}_svc
5559     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
5560 }
5561
5562 ########################
5563
5564 convert_facet2label() {
5565     local facet=$1
5566
5567     if [ x$facet = xost ]; then
5568        facet=ost1
5569     fi
5570
5571     local varsvc=${facet}_svc
5572
5573     if [ -n ${!varsvc} ]; then
5574         echo ${!varsvc}
5575     else
5576         error "No lablel for $facet!"
5577     fi
5578 }
5579
5580 get_clientosc_proc_path() {
5581     echo "${1}-osc-*"
5582 }
5583
5584 get_lustre_version () {
5585     local facet=${1:-"$SINGLEMDS"}    
5586     do_facet $facet $LCTL get_param -n version | awk '/^lustre:/ {print $2}'
5587 }
5588
5589 lustre_version_code() {
5590     local facet=${1:-"$SINGLEMDS"}
5591     version_code $(get_lustre_version $1)
5592 }
5593
5594 # If the 2.0 MDS was mounted on 1.8 device, then the OSC and LOV names
5595 # used by MDT would not be changed.
5596 # mdt lov: fsname-mdtlov
5597 # mdt osc: fsname-OSTXXXX-osc
5598 mds_on_old_device() {
5599     local mds=${1:-"$SINGLEMDS"}
5600
5601     if [ $(lustre_version_code $mds) -gt $(version_code 1.9.0) ]; then
5602         do_facet $mds "lctl list_param osc.$FSNAME-OST*-osc \
5603             > /dev/null 2>&1" && return 0
5604     fi
5605     return 1
5606 }
5607
5608 get_mdtosc_proc_path() {
5609     local mds_facet=$1
5610     local ost_label=${2:-"*OST*"}
5611
5612     [ "$mds_facet" = "mds" ] && mds_facet=$SINGLEMDS
5613     local mdt_label=$(convert_facet2label $mds_facet)
5614     local mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')
5615
5616     if [ $(lustre_version_code $mds_facet) -le $(version_code 1.8.0) ] ||
5617        mds_on_old_device $mds_facet; then
5618         echo "${ost_label}-osc"
5619     else
5620         echo "${ost_label}-osc-${mdt_index}"
5621     fi
5622 }
5623
5624 get_osc_import_name() {
5625     local facet=$1
5626     local ost=$2
5627     local label=$(convert_facet2label $ost)
5628
5629     if [ "${facet:0:3}" = "mds" ]; then
5630         get_mdtosc_proc_path $facet $label
5631         return 0
5632     fi
5633
5634     get_clientosc_proc_path $label
5635     return 0
5636 }
5637
5638 _wait_import_state () {
5639     local expected=$1
5640     local CONN_PROC=$2
5641     local maxtime=${3:-$(max_recovery_time)}
5642     local CONN_STATE
5643     local i=0
5644
5645         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
5646     while [ "${CONN_STATE}" != "${expected}" ]; do
5647         if [ "${expected}" == "DISCONN" ]; then
5648             # for disconn we can check after proc entry is removed
5649             [ "x${CONN_STATE}" == "x" ] && return 0
5650             #  with AT enabled, we can have connect request timeout near of
5651             # reconnect timeout and test can't see real disconnect
5652             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
5653         fi
5654         [ $i -ge $maxtime ] && \
5655             error "can't put import for $CONN_PROC into ${expected} state after $i sec, have ${CONN_STATE}" && \
5656             return 1
5657         sleep 1
5658         # Add uniq for multi-mount case
5659         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
5660         i=$(($i + 1))
5661     done
5662
5663     log "$CONN_PROC in ${CONN_STATE} state after $i sec"
5664     return 0
5665 }
5666
5667 wait_import_state() {
5668     local state=$1
5669     local params=$2
5670     local maxtime=${3:-$(max_recovery_time)}
5671     local param
5672
5673     for param in ${params//,/ }; do
5674         _wait_import_state $state $param $maxtime || return
5675     done
5676 }
5677
5678 wait_import_state_mount() {
5679         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
5680                 return 0
5681         fi
5682
5683         wait_import_state $*
5684 }
5685
5686 # One client request could be timed out because server was not ready
5687 # when request was sent by client.
5688 # The request timeout calculation details :
5689 # ptl_send_rpc ()
5690 #      /* We give the server rq_timeout secs to process the req, and
5691 #      add the network latency for our local timeout. */
5692 #      request->rq_deadline = request->rq_sent + request->rq_timeout +
5693 #           ptlrpc_at_get_net_latency(request) ;
5694 #
5695 # ptlrpc_connect_import ()
5696 #      request->rq_timeout = INITIAL_CONNECT_TIMEOUT
5697 #
5698 # init_imp_at () ->
5699 #   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0
5700 # ptlrpc_at_get_net_latency(request) ->
5701 #       at_get (max (iat_net_latency=0, at_min)) = at_min
5702 #
5703 # i.e.:
5704 # request->rq_timeout + ptlrpc_at_get_net_latency(request) =
5705 # INITIAL_CONNECT_TIMEOUT + at_min
5706 #
5707 # We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT
5708 # because we can not get this value in runtime,
5709 # the value depends on configure options, and it is not stored in /proc.
5710 # obd_support.h:
5711 # #define CONNECTION_SWITCH_MIN 5U
5712 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
5713
5714 request_timeout () {
5715     local facet=$1
5716
5717     # request->rq_timeout = INITIAL_CONNECT_TIMEOUT
5718     local init_connect_timeout=$TIMEOUT
5719     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
5720
5721     local at_min=$(at_get $facet at_min)
5722
5723     echo $(( init_connect_timeout + at_min ))
5724 }
5725
5726 _wait_osc_import_state() {
5727         local facet=$1
5728         local ost_facet=$2
5729         local expected=$3
5730         local ost=$(get_osc_import_name $facet $ost_facet)
5731         local param="osc.${ost}.ost_server_uuid"
5732         local params=$param
5733         local i=0
5734
5735         # 1. wait the deadline of client 1st request (it could be skipped)
5736         # 2. wait the deadline of client 2nd request
5737         local maxtime=$(( 2 * $(request_timeout $facet)))
5738
5739         if [[ $facet == client* ]]; then
5740                 # During setup time, the osc might not be setup, it need wait
5741                 # until list_param can return valid value. And also if there
5742                 # are mulitple osc entries we should list all of them before
5743                 # go to wait.
5744                 params=$($LCTL list_param $param 2>/dev/null || true)
5745                 while [ -z "$params" ]; do
5746                         if [ $i -ge $maxtime ]; then
5747                                 echo "can't get $param in $maxtime secs"
5748                                 return 1
5749                         fi
5750                         sleep 1
5751                         i=$((i + 1))
5752                         params=$($LCTL list_param $param 2>/dev/null || true)
5753                 done
5754         fi
5755         if ! do_rpc_nodes "$(facet_active_host $facet)" \
5756                         wait_import_state $expected "$params" $maxtime; then
5757                 error "import is not in ${expected} state"
5758                 return 1
5759         fi
5760
5761         return 0
5762 }
5763
5764 wait_osc_import_state() {
5765         local facet=$1
5766         local ost_facet=$2
5767         local expected=$3
5768         local num
5769
5770         if [[ $facet = mds ]]; then
5771                 for num in $(seq $MDSCOUNT); do
5772                         _wait_osc_import_state mds$num "$ost_facet" "$expected"
5773                 done
5774         else
5775                 _wait_osc_import_state "$facet" "$ost_facet" "$expected"
5776         fi
5777 }
5778
5779 get_clientmdc_proc_path() {
5780     echo "${1}-mdc-*"
5781 }
5782
5783 do_rpc_nodes () {
5784         local list=$1
5785         shift
5786
5787         [ -z "$list" ] && return 0
5788
5789         # Add paths to lustre tests for 32 and 64 bit systems.
5790         local LIBPATH="/usr/lib/lustre/tests:/usr/lib64/lustre/tests:"
5791         local TESTPATH="$RLUSTRE/tests:"
5792         local RPATH="PATH=${TESTPATH}${LIBPATH}${PATH}:/sbin:/bin:/usr/sbin:"
5793         do_nodesv $list "${RPATH} NAME=${NAME} sh rpc.sh $@ "
5794 }
5795
5796 wait_clients_import_state () {
5797     local list=$1
5798     local facet=$2
5799     local expected=$3
5800
5801     local facets=$facet
5802
5803     if [ "$FAILURE_MODE" = HARD ]; then
5804         facets=$(facets_on_host $(facet_active_host $facet))
5805     fi
5806
5807     for facet in ${facets//,/ }; do
5808     local label=$(convert_facet2label $facet)
5809     local proc_path
5810     case $facet in
5811         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
5812         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
5813         *) error "unknown facet!" ;;
5814     esac
5815     local params=$(expand_list $params $proc_path)
5816     done
5817
5818         if ! do_rpc_nodes "$list" wait_import_state_mount $expected $params; then
5819                 error "import is not in ${expected} state"
5820                 return 1
5821         fi
5822 }
5823
5824 oos_full() {
5825         local -a AVAILA
5826         local -a GRANTA
5827         local -a TOTALA
5828         local OSCFULL=1
5829         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
5830                   $LCTL get_param obdfilter.*.kbytesavail))
5831         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
5832                   $LCTL get_param -n obdfilter.*.tot_granted))
5833         TOTALA=($(do_nodes $(comma_list $(osts_nodes)) \
5834                   $LCTL get_param -n obdfilter.*.kbytestotal))
5835         for ((i=0; i<${#AVAILA[@]}; i++)); do
5836                 local -a AVAIL1=(${AVAILA[$i]//=/ })
5837                 local -a TOTAL=(${TOTALA[$i]//=/ })
5838                 GRANT=$((${GRANTA[$i]}/1024))
5839                 # allow 1% of total space in bavail because of delayed
5840                 # allocation with ZFS which might release some free space after
5841                 # txg commit.  For small devices, we set a mininum of 8MB
5842                 local LIMIT=$((${TOTAL} / 100 + 8000))
5843                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} \
5844                         grnt=$GRANT diff=$((AVAIL1[1] - GRANT)) limit=${LIMIT}
5845                 [ $((AVAIL1[1] - GRANT)) -lt $LIMIT ] && OSCFULL=0 && \
5846                         echo " FULL" || echo
5847         done
5848         return $OSCFULL
5849 }
5850
5851 pool_list () {
5852    do_facet mgs lctl pool_list $1
5853 }
5854
5855 create_pool() {
5856     local fsname=${1%%.*}
5857     local poolname=${1##$fsname.}
5858
5859     do_facet mgs lctl pool_new $1
5860     local RC=$?
5861     # get param should return err unless pool is created
5862     [[ $RC -ne 0 ]] && return $RC
5863
5864     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
5865         2>/dev/null || echo foo" "" || RC=1
5866     if [[ $RC -eq 0 ]]; then
5867         add_pool_to_list $1
5868     else
5869         error "pool_new failed $1"
5870     fi
5871     return $RC
5872 }
5873
5874 add_pool_to_list () {
5875     local fsname=${1%%.*}
5876     local poolname=${1##$fsname.}
5877
5878     local listvar=${fsname}_CREATED_POOLS
5879     eval export ${listvar}=$(expand_list ${!listvar} $poolname)
5880 }
5881
5882 remove_pool_from_list () {
5883     local fsname=${1%%.*}
5884     local poolname=${1##$fsname.}
5885
5886     local listvar=${fsname}_CREATED_POOLS
5887     eval export ${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
5888 }
5889
5890 destroy_pool_int() {
5891     local ost
5892     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
5893         awk '$1 !~ /^Pool:/ {print $1}')
5894     for ost in $OSTS; do
5895         do_facet mgs lctl pool_remove $1 $ost
5896     done
5897     do_facet mgs lctl pool_destroy $1
5898 }
5899
5900 # <fsname>.<poolname> or <poolname>
5901 destroy_pool() {
5902     local fsname=${1%%.*}
5903     local poolname=${1##$fsname.}
5904
5905     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
5906
5907     local RC
5908
5909     pool_list $fsname.$poolname || return $?
5910
5911     destroy_pool_int $fsname.$poolname
5912     RC=$?
5913     [[ $RC -ne 0 ]] && return $RC
5914
5915     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
5916       2>/dev/null || echo foo" "foo" || RC=1
5917
5918     if [[ $RC -eq 0 ]]; then
5919         remove_pool_from_list $fsname.$poolname
5920     else
5921         error "destroy pool failed $1"
5922     fi
5923     return $RC
5924 }
5925
5926 destroy_pools () {
5927     local fsname=${1:-$FSNAME}
5928     local poolname
5929     local listvar=${fsname}_CREATED_POOLS
5930
5931     pool_list $fsname
5932
5933     [ x${!listvar} = x ] && return 0
5934
5935     echo destroy the created pools: ${!listvar}
5936     for poolname in ${!listvar//,/ }; do
5937         destroy_pool $fsname.$poolname
5938     done
5939 }
5940
5941 cleanup_pools () {
5942     local fsname=${1:-$FSNAME}
5943     trap 0
5944     destroy_pools $fsname
5945 }
5946
5947 gather_logs () {
5948     local list=$1
5949
5950     local ts=$(date +%s)
5951     local docp=true
5952
5953     if [[ ! -f "$YAML_LOG" ]]; then
5954         # init_logging is not performed before gather_logs,
5955         # so the $LOGDIR needs to be checked here
5956         check_shared_dir $LOGDIR && touch $LOGDIR/shared
5957     fi
5958
5959     [ -f $LOGDIR/shared ] && docp=false
5960
5961     # dump lustre logs, dmesg
5962
5963     prefix="$TESTLOG_PREFIX.$TESTNAME"
5964     suffix="$ts.log"
5965     echo "Dumping lctl log to ${prefix}.*.${suffix}"
5966
5967     if [ "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
5968         echo "Dumping logs only on local client."
5969         $LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}
5970         dmesg > ${prefix}.dmesg.$(hostname -s).${suffix}
5971         return
5972     fi
5973
5974     do_nodesv $list \
5975         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname -s).${suffix};
5976          dmesg > ${prefix}.dmesg.\\\$(hostname -s).${suffix}"
5977     if [ ! -f $LOGDIR/shared ]; then
5978         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
5979     fi
5980 }
5981
5982 do_ls () {
5983     local mntpt_root=$1
5984     local num_mntpts=$2
5985     local dir=$3
5986     local i
5987     local cmd
5988     local pids
5989     local rc=0
5990
5991     for i in $(seq 0 $num_mntpts); do
5992         cmd="ls -laf ${mntpt_root}$i/$dir"
5993         echo + $cmd;
5994         $cmd > /dev/null &
5995         pids="$pids $!"
5996     done
5997     echo pids=$pids
5998     for pid in $pids; do
5999         wait $pid || rc=$?
6000     done
6001
6002     return $rc
6003 }
6004
6005 # target_start_and_reset_recovery_timer()
6006 #        service_time = at_est2timeout(service_time);
6007 #        service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC +
6008 #                             INITIAL_CONNECT_TIMEOUT);
6009 # CONNECTION_SWITCH_MAX : min(25U, max(CONNECTION_SWITCH_MIN,obd_timeout))
6010 #define CONNECTION_SWITCH_INC 1
6011 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
6012 #define CONNECTION_SWITCH_MIN 5U
6013
6014 max_recovery_time () {
6015     local init_connect_timeout=$(( TIMEOUT / 20 ))
6016     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
6017
6018     local service_time=$(( $(at_max_get client) + $(( 2 * $(( 25 + 1  + init_connect_timeout)) )) ))
6019
6020     echo $service_time 
6021 }
6022
6023 get_clients_mount_count () {
6024     local clients=${CLIENTS:-`hostname`}
6025
6026     # we need to take into account the clients mounts and
6027     # exclude mds/ost mounts if any;
6028     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
6029 }
6030
6031 # gss functions
6032 PROC_CLI="srpc_info"
6033
6034 combination()
6035 {
6036     local M=$1
6037     local N=$2
6038     local R=1
6039
6040     if [ $M -lt $N ]; then
6041         R=0
6042     else
6043         N=$((N + 1))
6044         while [ $N -lt $M ]; do
6045             R=$((R * N))
6046             N=$((N + 1))
6047         done
6048     fi
6049
6050     echo $R
6051     return 0
6052 }
6053
6054 calc_connection_cnt() {
6055     local dir=$1
6056
6057     # MDT->MDT = 2 * C(M, 2)
6058     # MDT->OST = M * O
6059     # CLI->OST = C * O
6060     # CLI->MDT = C * M
6061     comb_m2=$(combination $MDSCOUNT 2)
6062
6063     local num_clients=$(get_clients_mount_count)
6064
6065     local cnt_mdt2mdt=$((comb_m2 * 2))
6066     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
6067     local cnt_cli2ost=$((num_clients * OSTCOUNT))
6068     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
6069     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
6070     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
6071     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
6072
6073     local var=cnt_$dir
6074     local res=${!var}
6075
6076     echo $res
6077 }
6078
6079 set_rule()
6080 {
6081     local tgt=$1
6082     local net=$2
6083     local dir=$3
6084     local flavor=$4
6085     local cmd="$tgt.srpc.flavor"
6086
6087     if [ $net == "any" ]; then
6088         net="default"
6089     fi
6090     cmd="$cmd.$net"
6091
6092     if [ $dir != "any" ]; then
6093         cmd="$cmd.$dir"
6094     fi
6095
6096     cmd="$cmd=$flavor"
6097     log "Setting sptlrpc rule: $cmd"
6098     do_facet mgs "$LCTL conf_param $cmd"
6099 }
6100
6101 count_flvr()
6102 {
6103     local output=$1
6104     local flavor=$2
6105     local count=0
6106
6107     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
6108     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
6109
6110     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
6111
6112     if [ "x$bulkspec" != "x" ]; then
6113         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
6114
6115         if [ "x$algs" != "x" ]; then
6116             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
6117         else
6118             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
6119             if [ $bulk == "bulkn" ]; then
6120                 bulk_count=`echo "$output" | grep "bulk flavor" \
6121                             | grep "null/null" | wc -l`
6122             elif [ $bulk == "bulki" ]; then
6123                 bulk_count=`echo "$output" | grep "bulk flavor" \
6124                             | grep "/null" | grep -v "null/" | wc -l`
6125             else
6126                 bulk_count=`echo "$output" | grep "bulk flavor" \
6127                             | grep -v "/null" | grep -v "null/" | wc -l`
6128             fi
6129         fi
6130
6131         [ $bulk_count -lt $count ] && count=$bulk_count
6132     fi
6133
6134     echo $count
6135 }
6136
6137 flvr_cnt_cli2mdt()
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 mdc.*-MDT*-mdc-*.$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_cli2ost()
6153 {
6154     local flavor=$1
6155     local cnt
6156
6157     local clients=${CLIENTS:-`hostname`}
6158
6159     for c in ${clients//,/ }; do
6160         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
6161         tmpcnt=`count_flvr "$output" $flavor`
6162         cnt=$((cnt + tmpcnt))
6163     done
6164     echo $cnt
6165 }
6166
6167 flvr_cnt_mdt2mdt()
6168 {
6169     local flavor=$1
6170     local cnt=0
6171
6172     if [ $MDSCOUNT -le 1 ]; then
6173         echo 0
6174         return
6175     fi
6176
6177     for num in `seq $MDSCOUNT`; do
6178         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
6179         tmpcnt=`count_flvr "$output" $flavor`
6180         cnt=$((cnt + tmpcnt))
6181     done
6182     echo $cnt;
6183 }
6184
6185 flvr_cnt_mdt2ost()
6186 {
6187     local flavor=$1
6188     local cnt=0
6189     local mdtosc
6190
6191     for num in `seq $MDSCOUNT`; do
6192         mdtosc=$(get_mdtosc_proc_path mds$num)
6193         mdtosc=${mdtosc/-MDT*/-MDT\*}
6194         output=$(do_facet mds$num lctl get_param -n \
6195             osc.$mdtosc.$PROC_CLI 2>/dev/null)
6196         tmpcnt=`count_flvr "$output" $flavor`
6197         cnt=$((cnt + tmpcnt))
6198     done
6199     echo $cnt;
6200 }
6201
6202 flvr_cnt_mgc2mgs()
6203 {
6204     local flavor=$1
6205
6206     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
6207     count_flvr "$output" $flavor
6208 }
6209
6210 do_check_flavor()
6211 {
6212     local dir=$1        # from to
6213     local flavor=$2     # flavor expected
6214     local res=0
6215
6216     if [ $dir == "cli2mdt" ]; then
6217         res=`flvr_cnt_cli2mdt $flavor`
6218     elif [ $dir == "cli2ost" ]; then
6219         res=`flvr_cnt_cli2ost $flavor`
6220     elif [ $dir == "mdt2mdt" ]; then
6221         res=`flvr_cnt_mdt2mdt $flavor`
6222     elif [ $dir == "mdt2ost" ]; then
6223         res=`flvr_cnt_mdt2ost $flavor`
6224     elif [ $dir == "all2ost" ]; then
6225         res1=`flvr_cnt_mdt2ost $flavor`
6226         res2=`flvr_cnt_cli2ost $flavor`
6227         res=$((res1 + res2))
6228     elif [ $dir == "all2mdt" ]; then
6229         res1=`flvr_cnt_mdt2mdt $flavor`
6230         res2=`flvr_cnt_cli2mdt $flavor`
6231         res=$((res1 + res2))
6232     elif [ $dir == "all2all" ]; then
6233         res1=`flvr_cnt_mdt2ost $flavor`
6234         res2=`flvr_cnt_cli2ost $flavor`
6235         res3=`flvr_cnt_mdt2mdt $flavor`
6236         res4=`flvr_cnt_cli2mdt $flavor`
6237         res=$((res1 + res2 + res3 + res4))
6238     fi
6239
6240     echo $res
6241 }
6242
6243 wait_flavor()
6244 {
6245     local dir=$1        # from to
6246     local flavor=$2     # flavor expected
6247     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
6248
6249     local res=0
6250
6251     for ((i=0;i<20;i++)); do
6252         echo -n "checking $dir..."
6253         res=$(do_check_flavor $dir $flavor)
6254         echo "found $res/$expect $flavor connections"
6255         [ $res -ge $expect ] && return 0
6256         sleep 4
6257     done
6258
6259     echo "Error checking $flavor of $dir: expect $expect, actual $res"
6260     return 1
6261 }
6262
6263 restore_to_default_flavor()
6264 {
6265     local proc="mgs.MGS.live.$FSNAME"
6266
6267     echo "restoring to default flavor..."
6268
6269     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
6270
6271     # remove all existing rules if any
6272     if [ $nrule -ne 0 ]; then
6273         echo "$nrule existing rules"
6274         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
6275             echo "remove rule: $rule"
6276             spec=`echo $rule | awk -F = '{print $1}'`
6277             do_facet mgs "$LCTL conf_param -d $spec"
6278         done
6279     fi
6280
6281     # verify no rules left
6282     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
6283     [ $nrule -ne 0 ] && error "still $nrule rules left"
6284
6285     # wait for default flavor to be applied
6286     # currently default flavor for all connections are 'null'
6287     wait_flavor all2all null
6288     echo "now at default flavor settings"
6289 }
6290
6291 set_flavor_all()
6292 {
6293     local flavor=${1:-null}
6294
6295     echo "setting all flavor to $flavor"
6296
6297     # FIXME need parameter to this fn
6298     # and remove global vars
6299     local cnt_all2all=$(calc_connection_cnt all2all)
6300
6301     local res=$(do_check_flavor all2all $flavor)
6302     if [ $res -eq $cnt_all2all ]; then
6303         echo "already have total $res $flavor connections"
6304         return
6305     fi
6306
6307     echo "found $res $flavor out of total $cnt_all2all connections"
6308     restore_to_default_flavor
6309
6310     [[ $flavor = null ]] && return 0
6311
6312     set_rule $FSNAME any any $flavor
6313     wait_flavor all2all $flavor
6314 }
6315
6316
6317 check_logdir() {
6318     local dir=$1
6319     # Checking for shared logdir
6320     if [ ! -d $dir ]; then
6321         # Not found. Create local logdir
6322         mkdir -p $dir
6323     else
6324         touch $dir/check_file.$(hostname -s)
6325     fi
6326     return 0
6327 }
6328
6329 check_write_access() {
6330         local dir=$1
6331         local list=${2:-$(comma_list $(nodes_list))}
6332         local node
6333         local file
6334
6335         for node in ${list//,/ }; do
6336                 file=$dir/check_file.$(short_nodename $node)
6337                 if [[ ! -f "$file" ]]; then
6338                         # Logdir not accessible/writable from this node.
6339                         return 1
6340                 fi
6341                 rm -f $file || return 1
6342         done
6343         return 0
6344 }
6345
6346 init_logging() {
6347     if [[ -n $YAML_LOG ]]; then
6348         return
6349     fi
6350     local SAVE_UMASK=`umask`
6351     umask 0000
6352
6353     export YAML_LOG=${LOGDIR}/results.yml
6354     mkdir -p $LOGDIR
6355     init_clients_lists
6356
6357     if [ ! -f $YAML_LOG ]; then       # If the yaml log already exists then we will just append to it
6358       if check_shared_dir $LOGDIR; then
6359           touch $LOGDIR/shared
6360           echo "Logging to shared log directory: $LOGDIR"
6361       else
6362           echo "Logging to local directory: $LOGDIR"
6363       fi
6364
6365       yml_nodes_file $LOGDIR >> $YAML_LOG
6366       yml_results_file >> $YAML_LOG
6367     fi
6368
6369     umask $SAVE_UMASK
6370 }
6371
6372 log_test() {
6373     yml_log_test $1 >> $YAML_LOG
6374 }
6375
6376 log_test_status() {
6377      yml_log_test_status $@ >> $YAML_LOG
6378 }
6379
6380 log_sub_test_begin() {
6381     yml_log_sub_test_begin "$@" >> $YAML_LOG
6382 }
6383
6384 log_sub_test_end() {
6385     yml_log_sub_test_end "$@" >> $YAML_LOG
6386 }
6387
6388 run_llverdev()
6389 {
6390         local dev=$1
6391         local llverdev_opts=$2
6392         local devname=$(basename $1)
6393         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
6394         # loop devices aren't in /proc/partitions
6395         [ "x$size" == "x" ] && local size=$(ls -l $dev | awk '{print $5}')
6396
6397         size=$(($size / 1024 / 1024)) # Gb
6398
6399         local partial_arg=""
6400         # Run in partial (fast) mode if the size
6401         # of a partition > 1 GB
6402         [ $size -gt 1 ] && partial_arg="-p"
6403
6404         llverdev --force $partial_arg $llverdev_opts $dev
6405 }
6406
6407 run_llverfs()
6408 {
6409         local dir=$1
6410         local llverfs_opts=$2
6411         local use_partial_arg=$3
6412         local partial_arg=""
6413         local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB
6414
6415         # Run in partial (fast) mode if the size
6416         # of a partition > 1 GB
6417         [ "x$use_partial_arg" != "xno" ] && [ $size -gt 1 ] && partial_arg="-p"
6418
6419         llverfs $partial_arg $llverfs_opts $dir
6420 }
6421
6422 #Remove objects from OST
6423 remove_ost_objects() {
6424         local facet=$1
6425         local ostdev=$2
6426         local group=$3
6427         shift 3
6428         local objids="$@"
6429         local mntpt=$(facet_mntpt $facet)
6430         local opts=$OST_MOUNT_OPTS
6431         local i
6432         local rc
6433
6434         echo "removing objects from $ostdev on $facet: $objids"
6435         if ! test -b $ostdev; then
6436                 opts=$(csa_add "$opts" -o loop)
6437         fi
6438         mount -t $(facet_fstype $facet) $opts $ostdev $mntpt ||
6439                 return $?
6440         rc=0
6441         for i in $objids; do
6442                 rm $mntpt/O/$group/d$((i % 32))/$i || { rc=$?; break; }
6443         done
6444         umount -f $mntpt || return $?
6445         return $rc
6446 }
6447
6448 #Remove files from MDT
6449 remove_mdt_files() {
6450         local facet=$1
6451         local mdtdev=$2
6452         shift 2
6453         local files="$@"
6454         local mntpt=$(facet_mntpt $facet)
6455         local opts=$MDS_MOUNT_OPTS
6456
6457         echo "removing files from $mdtdev on $facet: $files"
6458         if [ $(facet_fstype $facet) == ldiskfs ] &&
6459            ! do_facet $facet test -b $mdtdev; then
6460                 opts=$(csa_add "$opts" -o loop)
6461         fi
6462         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
6463                 return $?
6464         rc=0
6465         for f in $files; do
6466                 rm $mntpt/ROOT/$f || { rc=$?; break; }
6467         done
6468         umount -f $mntpt || return $?
6469         return $rc
6470 }
6471
6472 duplicate_mdt_files() {
6473         local facet=$1
6474         local mdtdev=$2
6475         shift 2
6476         local files="$@"
6477         local mntpt=$(facet_mntpt $facet)
6478         local opts=$MDS_MOUNT_OPTS
6479
6480         echo "duplicating files on $mdtdev on $facet: $files"
6481         mkdir -p $mntpt || return $?
6482         if [ $(facet_fstype $facet) == ldiskfs ] &&
6483            ! do_facet $facet test -b $mdtdev; then
6484                 opts=$(csa_add "$opts" -o loop)
6485         fi
6486         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
6487                 return $?
6488
6489     do_umount() {
6490         trap 0
6491         popd > /dev/null
6492         rm $tmp
6493         umount -f $mntpt
6494     }
6495     trap do_umount EXIT
6496
6497     tmp=$(mktemp $TMP/setfattr.XXXXXXXXXX)
6498     pushd $mntpt/ROOT > /dev/null || return $?
6499     rc=0
6500     for f in $files; do
6501         touch $f.bad || return $?
6502         getfattr -n trusted.lov $f | sed "s#$f#&.bad#" > $tmp
6503         rc=${PIPESTATUS[0]}
6504         [ $rc -eq 0 ] || return $rc
6505         setfattr --restore $tmp || return $?
6506     done
6507     do_umount
6508 }
6509
6510 run_sgpdd () {
6511     local devs=${1//,/ }
6512     shift
6513     local params=$@
6514     local rslt=$TMP/sgpdd_survey
6515
6516     # sgpdd-survey cleanups ${rslt}.* files
6517
6518     local cmd="rslt=$rslt $params scsidevs=\"$devs\" $SGPDDSURVEY"
6519     echo + $cmd
6520     eval $cmd
6521     cat ${rslt}.detail
6522 }
6523
6524 # returns the canonical name for an ldiskfs device
6525 ldiskfs_canon() {
6526         local dev="$1"
6527         local facet="$2"
6528
6529         do_facet $facet "dv=\\\$(lctl get_param -n $dev);
6530 if foo=\\\$(lvdisplay -c \\\$dv 2>/dev/null); then
6531     echo dm-\\\${foo##*:};
6532 else
6533     echo \\\$(basename \\\$dv);
6534 fi;"
6535 }
6536
6537 is_sanity_benchmark() {
6538     local benchmarks="dbench bonnie iozone fsx"
6539     local suite=$1
6540     for b in $benchmarks; do
6541         if [ "$b" == "$suite" ]; then
6542             return 0
6543         fi
6544     done
6545     return 1
6546 }
6547
6548 min_ost_size () {
6549     $LCTL get_param -n osc.*.kbytesavail | sort -n | head -n1
6550 }
6551
6552 #
6553 # Get the available size (KB) of a given obd target.
6554 #
6555 get_obd_size() {
6556         local facet=$1
6557         local obd=$2
6558         local size
6559
6560         [[ $facet != client ]] || return 0
6561
6562         size=$(do_facet $facet $LCTL get_param -n *.$obd.kbytesavail | head -n1)
6563         echo -n $size
6564 }
6565
6566 #
6567 # Get the page size (bytes) on a given facet node.
6568 #
6569 get_page_size() {
6570         local facet=$1
6571         local size
6572
6573         size=$(do_facet $facet getconf PAGE_SIZE)
6574         [[ ${PIPESTATUS[0]} = 0 && -n "$size" ]] || size=4096
6575         echo -n $size
6576 }
6577
6578 #
6579 # Get the block count of the filesystem.
6580 #
6581 get_block_count() {
6582         local facet=$1
6583         local device=$2
6584         local count
6585
6586         count=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
6587                 awk '/^Block count:/ {print $3}')
6588         echo -n $count
6589 }
6590
6591 # Get the block size of the filesystem.
6592 get_block_size() {
6593     local facet=$1
6594     local device=$2
6595     local size
6596
6597     size=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
6598            awk '/^Block size:/ {print $3}')
6599     echo $size
6600 }
6601
6602 # Check whether the "large_xattr" feature is enabled or not.
6603 large_xattr_enabled() {
6604         [[ $(facet_fstype $SINGLEMDS) == zfs ]] && return 0
6605
6606         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
6607
6608         do_facet $SINGLEMDS "$DUMPE2FS -h $mds_dev 2>&1 |
6609                 grep -E -q '(ea_inode|large_xattr)'"
6610         return ${PIPESTATUS[0]}
6611 }
6612
6613 # Get the maximum xattr size supported by the filesystem.
6614 max_xattr_size() {
6615     local size
6616
6617     if large_xattr_enabled; then
6618         # include/linux/limits.h: #define XATTR_SIZE_MAX 65536
6619         size=65536
6620     else
6621         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
6622         local block_size=$(get_block_size $SINGLEMDS $mds_dev)
6623
6624         # maximum xattr size = size of block - size of header -
6625         #                      size of 1 entry - 4 null bytes
6626         size=$((block_size - 32 - 32 - 4))
6627     fi
6628
6629     echo $size
6630 }
6631
6632 # Dump the value of the named xattr from a file.
6633 get_xattr_value() {
6634     local xattr_name=$1
6635     local file=$2
6636
6637     echo "$(getfattr -n $xattr_name --absolute-names --only-values $file)"
6638 }
6639
6640 # Generate a string with size of $size bytes.
6641 generate_string() {
6642     local size=${1:-1024} # in bytes
6643
6644     echo "$(head -c $size < /dev/zero | tr '\0' y)"
6645 }
6646
6647 reformat_external_journal() {
6648         local facet=$1
6649
6650         if [ ! -z ${EJOURNAL} ]; then
6651                 local rcmd="do_facet $facet"
6652
6653                 echo "reformat external journal on $facet:${EJOURNAL}"
6654                 ${rcmd} mke2fs -O journal_dev ${EJOURNAL} || return 1
6655         fi
6656 }
6657
6658 # MDT file-level backup/restore
6659 mds_backup_restore() {
6660         local facet=$1
6661         local igif=$2
6662         local devname=$(mdsdevname $(facet_number $facet))
6663         local mntpt=$(facet_mntpt brpt)
6664         local rcmd="do_facet $facet"
6665         local metaea=${TMP}/backup_restore.ea
6666         local metadata=${TMP}/backup_restore.tgz
6667         local opts=${MDS_MOUNT_OPTS}
6668         local svc=${facet}_svc
6669
6670         if ! ${rcmd} test -b ${devname}; then
6671                 opts=$(csa_add "$opts" -o loop)
6672         fi
6673
6674         echo "file-level backup/restore on $facet:${devname}"
6675
6676         # step 1: build mount point
6677         ${rcmd} mkdir -p $mntpt
6678         # step 2: cleanup old backup
6679         ${rcmd} rm -f $metaea $metadata
6680         # step 3: mount dev
6681         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
6682         if [ ! -z $igif ]; then
6683                 # step 3.5: rm .lustre
6684                 ${rcmd} rm -rf $mntpt/ROOT/.lustre || return 1
6685         fi
6686         # step 4: backup metaea
6687         echo "backup EA"
6688         ${rcmd} "cd $mntpt && getfattr -R -d -m '.*' -P . > $metaea && cd -" ||
6689                 return 2
6690         # step 5: backup metadata
6691         echo "backup data"
6692         ${rcmd} tar zcf $metadata -C $mntpt/ . > /dev/null 2>&1 || return 3
6693         # step 6: umount
6694         ${rcmd} umount -d $mntpt || return 4
6695         # step 7: reformat external journal if needed
6696         reformat_external_journal $facet || return 5
6697         # step 8: reformat dev
6698         echo "reformat new device"
6699         add $facet $(mkfs_opts $facet ${devname}) --backfstype ldiskfs \
6700                 --reformat ${devname} $(mdsvdevname $(facet_number $facet)) \
6701                 > /dev/null || exit 6
6702         # step 9: mount dev
6703         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 7
6704         # step 10: restore metadata
6705         echo "restore data"
6706         ${rcmd} tar zxfp $metadata -C $mntpt > /dev/null 2>&1 || return 8
6707         # step 11: restore metaea
6708         echo "restore EA"
6709         ${rcmd} "cd $mntpt && setfattr --restore=$metaea && cd - " || return 9
6710         # step 12: remove recovery logs
6711         echo "remove recovery logs"
6712         ${rcmd} rm -fv $mntpt/OBJECTS/* $mntpt/CATALOGS
6713         # step 13: umount dev
6714         ${rcmd} umount -d $mntpt || return 10
6715         # step 14: cleanup tmp backup
6716         ${rcmd} rm -f $metaea $metadata
6717         # step 15: reset device label - it's not virgin on
6718         ${rcmd} e2label $devname ${!svc}
6719 }
6720
6721 # remove OI files
6722 mds_remove_ois() {
6723         local facet=$1
6724         local idx=$2
6725         local devname=$(mdsdevname $(facet_number $facet))
6726         local mntpt=$(facet_mntpt brpt)
6727         local rcmd="do_facet $facet"
6728         local opts=${MDS_MOUNT_OPTS}
6729
6730         if ! ${rcmd} test -b ${devname}; then
6731                 opts=$(csa_add "$opts" -o loop)
6732         fi
6733
6734         echo "removing OI files on $facet: idx=${idx}"
6735
6736         # step 1: build mount point
6737         ${rcmd} mkdir -p $mntpt
6738         # step 2: mount dev
6739         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
6740         if [ -z $idx ]; then
6741                 # step 3: remove all OI files
6742                 ${rcmd} rm -fv $mntpt/oi.16*
6743         elif [ $idx -lt 2 ]; then
6744                 ${rcmd} rm -fv $mntpt/oi.16.${idx}
6745         else
6746                 local i
6747
6748                 # others, rm oi.16.[idx, idx * idx, idx ** ...]
6749                 for ((i=${idx}; i<64; i=$((i * idx)))); do
6750                         ${rcmd} rm -fv $mntpt/oi.16.${i}
6751                 done
6752         fi
6753         # step 4: umount
6754         ${rcmd} umount -d $mntpt || return 2
6755         # OI files will be recreated when mounted as lustre next time.
6756 }
6757
6758 # generate maloo upload-able log file name
6759 # \param logname specify unique part of file name
6760 generate_logname() {
6761         local logname=${1:-"default_logname"}
6762
6763         echo "$TESTLOG_PREFIX.$TESTNAME.$logname.$(hostname -s).log"
6764 }
6765
6766 # make directory on different MDTs
6767 test_mkdir() {
6768         local option
6769         local parent
6770         local child
6771         local path
6772         local p_option
6773         local option2
6774         local stripe_count=2
6775         local rc=0
6776
6777         case $# in
6778                 1) path=$1;;
6779                 2) option=$1
6780                    path=$2;;
6781                 3) option=$1
6782                    option2=$2
6783                    path=$3;;
6784                 *) error "Only creating single directory is supported";;
6785         esac
6786
6787         child=$(basename $path)
6788         parent=$(dirname $path)
6789
6790         if [ "$option" == "-p" -o "$option2" == "-p" ]; then
6791                 if [ -d $parent/$child ]; then
6792                         return $rc
6793                 fi
6794                 p_option="-p"
6795         fi
6796
6797         if [ "${option:0:2}" == "-c" ]; then
6798                 stripe_count=$(echo $option | sed 's/^-c//')
6799         fi
6800
6801         if [ "${option2:0:2}" == "-c" ]; then
6802                 stripe_count=$(echo $option2 | sed 's/^-c//')
6803         fi
6804
6805         if [ ! -d ${parent} ]; then
6806                 if [ "$p_option" == "-p" ]; then
6807                         mkdir -p ${parent}
6808                 else
6809                         return 1
6810                 fi
6811         fi
6812
6813         if [ $MDSCOUNT -le 1 ]; then
6814                 mkdir $p_option $parent/$child || rc=$?
6815         else
6816                 local mdt_idx=$($LFS getstripe -M $parent)
6817                 local test_num=$(echo $testnum | sed -e 's/[^0-9]*//g')
6818
6819                 mdt_idx=$((test_num % MDSCOUNT))
6820                 echo "striped dir -i$mdt_idx -c$stripe_count $path"
6821                 $LFS setdirstripe -i$mdt_idx -c$stripe_count $path || rc=$?
6822         fi
6823         return $rc
6824 }
6825
6826 # find the smallest and not in use file descriptor
6827 free_fd()
6828 {
6829         local max_fd=$(ulimit -n)
6830         local fd=3
6831         while [[ $fd -le $max_fd && -e /proc/self/fd/$fd ]]; do
6832                 ((++fd))
6833         done
6834         [ $fd -lt $max_fd ] || error "finding free file descriptor failed"
6835         echo $fd
6836 }
6837
6838 check_mount_and_prep()
6839 {
6840         is_mounted $MOUNT || setupall
6841
6842         rm -rf $DIR/[df][0-9]* || error "Fail to cleanup the env!"
6843         mkdir $DIR/$tdir || error "Fail to mkdir $DIR/$tdir."
6844 }
6845
6846 # calcule how many ost-objects to be created.
6847 precreated_ost_obj_count()
6848 {
6849         local mdt_idx=$1
6850         local ost_idx=$2
6851         local mdt_name="MDT$(printf '%04x' $mdt_idx)"
6852         local ost_name="OST$(printf '%04x' $ost_idx)"
6853         local proc_path="${FSNAME}-${ost_name}-osc-${mdt_name}"
6854         local last_id=$(do_facet mds${mdt_idx} lctl get_param -n \
6855                         osp.$proc_path.prealloc_last_id)
6856         local next_id=$(do_facet mds${mdt_idx} lctl get_param -n \
6857                         osp.$proc_path.prealloc_next_id)
6858
6859         echo $((last_id - next_id + 1))
6860 }