Whamcloud - gitweb
LU-1182 tests: run accounting tests when OFD is used
[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 REFORMAT=${REFORMAT:-""}
9 export WRITECONF=${WRITECONF:-""}
10 export VERBOSE=${VERBOSE:-false}
11 export CATASTROPHE=${CATASTROPHE:-/proc/sys/lnet/catastrophe}
12 export GSS=false
13 export GSS_KRB5=false
14 export GSS_PIPEFS=false
15 export IDENTITY_UPCALL=default
16 export QUOTA_AUTO=1
17
18 # LOAD_LLOOP: LU-409: only load llite_lloop module if kernel < 2.6.32 or
19 #             LOAD_LLOOP is true. LOAD_LLOOP is false by default.
20 export LOAD_LLOOP=${LOAD_LLOOP:-false}
21
22 #export PDSH="pdsh -S -Rssh -w"
23
24 # function used by scripts run on remote nodes
25 LUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}
26 . $LUSTRE/tests/functions.sh
27 . $LUSTRE/tests/yaml.sh
28
29 LUSTRE_TESTS_CFG_DIR=${LUSTRE_TESTS_CFG_DIR:-${LUSTRE}/tests/cfg}
30
31 EXCEPT_LIST_FILE=${EXCEPT_LIST_FILE:-${LUSTRE_TESTS_CFG_DIR}/tests-to-skip.sh}
32
33 if [ -f "$EXCEPT_LIST_FILE" ]; then
34     echo "Reading test skip list from $EXCEPT_LIST_FILE"
35     cat $EXCEPT_LIST_FILE
36     . $EXCEPT_LIST_FILE
37 fi
38
39 # check config files for options in decreasing order of preference
40 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/lustre.conf ] &&
41     MODPROBECONF=/etc/modprobe.d/lustre.conf
42 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/Lustre ] &&
43     MODPROBECONF=/etc/modprobe.d/Lustre
44 [ -z "$MODPROBECONF" -a -f /etc/modprobe.conf ] &&
45     MODPROBECONF=/etc/modprobe.conf
46
47 assert_DIR () {
48     local failed=""
49     [[ $DIR/ = $MOUNT/* ]] || \
50         { failed=1 && echo "DIR=$DIR not in $MOUNT. Aborting."; }
51     [[ $DIR1/ = $MOUNT1/* ]] || \
52         { failed=1 && echo "DIR1=$DIR1 not in $MOUNT1. Aborting."; }
53     [[ $DIR2/ = $MOUNT2/* ]] || \
54         { failed=1 && echo "DIR2=$DIR2 not in $MOUNT2. Aborting"; }
55
56     [ -n "$failed" ] && exit 99 || true
57 }
58
59 usage() {
60     echo "usage: $0 [-r] [-f cfgfile]"
61     echo "       -r: reformat"
62
63     exit
64 }
65
66 print_summary () {
67     trap 0
68     [ "$TESTSUITE" == "lfsck" ] && return 0
69     [ -n "$ONLY" ] && echo "WARNING: ONLY is set to $(echo $ONLY)"
70     local details
71     local form="%-13s %-17s %-9s %s %s\n"
72     printf "$form" "status" "script" "Total(sec)" "E(xcluded) S(low)"
73     echo "------------------------------------------------------------------------------------"
74     for O in $DEFAULT_SUITES; do
75         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
76         [ "${!O}" = "no" ] && continue || true
77         local o=$(echo $O  | tr "[:upper:]_" "[:lower:]-")
78         local log=${TMP}/${o}.log
79         if is_sanity_benchmark $o; then
80             log=${TMP}/sanity-benchmark.log
81         fi
82         local slow=
83         local skipped=
84         local total=
85         local status=Unfinished
86         if [ -f $log ]; then
87             skipped=$(grep excluded $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
88             slow=$(egrep "^PASS|^FAIL" $log | tr -d "("| sed s/s\)$//g | sort -nr -k 3  | head -5 |  awk '{ print $2":"$3"s" }')
89             total=$(grep duration $log | awk '{ print $2}')
90             if [ "${!O}" = "done" ]; then
91                 status=Done
92             fi
93             if $DDETAILS; then
94                 local durations=$(egrep "^PASS|^FAIL" $log |  tr -d "("| sed s/s\)$//g | awk '{ print $2":"$3"|" }')
95                 details=$(printf "%s\n%s %s %s\n" "$details" "DDETAILS" "$O" "$(echo $durations)")
96             fi
97         fi
98         printf "$form" $status "$O" "${total}" "E=$skipped"
99         printf "$form" "-" "-" "-" "S=$(echo $slow)"
100     done
101
102     for O in $DEFAULT_SUITES; do
103         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
104         if [ "${!O}" = "no" ]; then
105             printf "$form" "Skipped" "$O" ""
106         fi
107     done
108
109     # print the detailed tests durations if DDETAILS=true
110     if $DDETAILS; then
111         echo "$details"
112     fi
113 }
114
115 init_test_env() {
116     export LUSTRE=`absolute_path $LUSTRE`
117     export TESTSUITE=`basename $0 .sh`
118     export TEST_FAILED=false
119     export FAIL_ON_SKIP_ENV=${FAIL_ON_SKIP_ENV:-false}
120
121     export MKE2FS=${MKE2FS:-mke2fs}
122     export DEBUGFS=${DEBUGFS:-debugfs}
123     export TUNE2FS=${TUNE2FS:-tune2fs}
124     export E2LABEL=${E2LABEL:-e2label}
125     export DUMPE2FS=${DUMPE2FS:-dumpe2fs}
126     export E2FSCK=${E2FSCK:-e2fsck}
127     export LFSCK_BIN=${LFSCK_BIN:-lfsck}
128
129     export LFSCK_ALWAYS=${LFSCK_ALWAYS:-"no"} # check fs after each test suite
130     export FSCK_MAX_ERR=4   # File system errors left uncorrected
131
132         export ZFS=${ZFS:-zfs}
133         export ZPOOL=${ZPOOL:-zpool}
134         export ZDB=${ZDB:-zdb}
135
136     #[ -d /r ] && export ROOT=${ROOT:-/r}
137     export TMP=${TMP:-$ROOT/tmp}
138     export TESTSUITELOG=${TMP}/${TESTSUITE}.log
139     export LOGDIR=${LOGDIR:-${TMP}/test_logs/$(date +%s)}
140     export TESTLOG_PREFIX=$LOGDIR/$TESTSUITE
141
142     export HOSTNAME=${HOSTNAME:-$(hostname -s)}
143     if ! echo $PATH | grep -q $LUSTRE/utils; then
144         export PATH=$LUSTRE/utils:$PATH
145     fi
146     if ! echo $PATH | grep -q $LUSTRE/utils/gss; then
147         export PATH=$LUSTRE/utils/gss:$PATH
148     fi
149     if ! echo $PATH | grep -q $LUSTRE/tests; then
150         export PATH=$LUSTRE/tests:$PATH
151     fi
152     if ! echo $PATH | grep -q $LUSTRE/../lustre-iokit/sgpdd-survey; then
153         export PATH=$LUSTRE/../lustre-iokit/sgpdd-survey:$PATH
154     fi
155     export LST=${LST:-"$LUSTRE/../lnet/utils/lst"}
156     [ ! -f "$LST" ] && export LST=$(which lst)
157     export SGPDDSURVEY=${SGPDDSURVEY:-"$LUSTRE/../lustre-iokit/sgpdd-survey/sgpdd-survey")}
158     [ ! -f "$SGPDDSURVEY" ] && export SGPDDSURVEY=$(which sgpdd-survey)
159     # Ubuntu, at least, has a truncate command in /usr/bin
160     # so fully path our truncate command.
161     export TRUNCATE=${TRUNCATE:-$LUSTRE/tests/truncate}
162     export MDSRATE=${MDSRATE:-"$LUSTRE/tests/mpi/mdsrate"}
163     [ ! -f "$MDSRATE" ] && export MDSRATE=$(which mdsrate 2> /dev/null)
164     if ! echo $PATH | grep -q $LUSTRE/tests/racer; then
165         export PATH=$LUSTRE/tests/racer:$PATH:
166     fi
167     if ! echo $PATH | grep -q $LUSTRE/tests/mpi; then
168         export PATH=$LUSTRE/tests/mpi:$PATH
169     fi
170     export RSYNC_RSH=${RSYNC_RSH:-rsh}
171
172     export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
173     [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
174     export LFS=${LFS:-"$LUSTRE/utils/lfs"}
175     [ ! -f "$LFS" ] && export LFS=$(which lfs)
176     SETSTRIPE=${SETSTRIPE:-"$LFS setstripe"}
177     GETSTRIPE=${GETSTRIPE:-"$LFS getstripe"}
178
179     export L_GETIDENTITY=${L_GETIDENTITY:-"$LUSTRE/utils/l_getidentity"}
180     if [ ! -f "$L_GETIDENTITY" ]; then
181         if `which l_getidentity > /dev/null 2>&1`; then
182             export L_GETIDENTITY=$(which l_getidentity)
183         else
184             export L_GETIDENTITY=NONE
185         fi
186     fi
187     export LL_DECODE_FILTER_FID=${LL_DECODE_FILTER_FID:-"$LUSTRE/utils/ll_decode_filter_fid"}
188     [ ! -f "$LL_DECODE_FILTER_FID" ] && export LL_DECODE_FILTER_FID=$(which ll_decode_filter_fid)
189     export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
190     [ ! -f "$MKFS" ] && export MKFS=$(which mkfs.lustre)
191     export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
192     [ ! -f "$TUNEFS" ] && export TUNEFS=$(which tunefs.lustre)
193     export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
194     export LUSTRE_RMMOD=${LUSTRE_RMMOD:-$LUSTRE/scripts/lustre_rmmod}
195     [ ! -f "$LUSTRE_RMMOD" ] &&
196         export LUSTRE_RMMOD=$(which lustre_rmmod 2> /dev/null)
197     export LFS_MIGRATE=${LFS_MIGRATE:-$LUSTRE/scripts/lfs_migrate}
198     [ ! -f "$LFS_MIGRATE" ] &&
199         export LFS_MIGRATE=$(which lfs_migrate 2> /dev/null)
200     export NAME=${NAME:-local}
201     export LGSSD=${LGSSD:-"$LUSTRE/utils/gss/lgssd"}
202     [ "$GSS_PIPEFS" = "true" ] && [ ! -f "$LGSSD" ] && \
203         export LGSSD=$(which lgssd)
204     export LSVCGSSD=${LSVCGSSD:-"$LUSTRE/utils/gss/lsvcgssd"}
205     [ ! -f "$LSVCGSSD" ] && export LSVCGSSD=$(which lsvcgssd 2> /dev/null)
206     export KRB5DIR=${KRB5DIR:-"/usr/kerberos"}
207     export DIR2
208     export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
209     export AT_MAX_PATH
210
211     if [ "$ACCEPTOR_PORT" ]; then
212         export PORT_OPT="--port $ACCEPTOR_PORT"
213     fi
214
215     case "x$SEC" in
216         xkrb5*)
217             echo "Using GSS/krb5 ptlrpc security flavor"
218             which lgss_keyring > /dev/null 2>&1 || \
219                 error_exit "built with gss disabled! SEC=$SEC"
220             GSS=true
221             GSS_KRB5=true
222             ;;
223     esac
224
225     case "x$IDUP" in
226         xtrue)
227             IDENTITY_UPCALL=true
228             ;;
229         xfalse)
230             IDENTITY_UPCALL=false
231             ;;
232     esac
233     export LOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}
234
235     # Paths on remote nodes, if different
236     export RLUSTRE=${RLUSTRE:-$LUSTRE}
237     export RPWD=${RPWD:-$PWD}
238     export I_MOUNTED=${I_MOUNTED:-"no"}
239     if [ ! -f /lib/modules/$(uname -r)/kernel/fs/lustre/mds.ko -a \
240         ! -f /lib/modules/$(uname -r)/updates/kernel/fs/lustre/mds.ko -a \
241         ! -f `dirname $0`/../mds/mds.ko ]; then
242         export CLIENTMODSONLY=yes
243     fi
244
245     export SHUTDOWN_ATTEMPTS=${SHUTDOWN_ATTEMPTS:-3}
246
247     # command line
248
249     while getopts "rvwf:" opt $*; do
250         case $opt in
251             f) CONFIG=$OPTARG;;
252             r) REFORMAT=--reformat;;
253             v) VERBOSE=true;;
254             w) WRITECONF=writeconf;;
255             \?) usage;;
256         esac
257     done
258
259     shift $((OPTIND - 1))
260     ONLY=${ONLY:-$*}
261
262     # print the durations of each test if "true"
263     DDETAILS=${DDETAILS:-false}
264     [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
265     rm -f $TMP/*active
266 }
267
268 version_code() {
269     # split arguments like "1.8.6-wc3" into "1", "8", "6", "wc3"
270     eval set -- $(tr "[:punct:]" " " <<< $*)
271
272     echo -n $((($1 << 16) | ($2 << 8) | $3))
273 }
274
275 export LINUX_VERSION=$(uname -r | sed -e "s/[-.]/ /3" -e "s/ .*//")
276 export LINUX_VERSION_CODE=$(version_code ${LINUX_VERSION//\./ })
277
278 module_loaded () {
279    /sbin/lsmod | grep -q "^\<$1\>"
280 }
281
282 # Load a module on the system where this is running.
283 #
284 # Synopsis: load_module module_name [module arguments for insmod/modprobe]
285 #
286 # If module arguments are not given but MODOPTS_<MODULE> is set, then its value
287 # will be used as the arguments.  Otherwise arguments will be obtained from
288 # /etc/modprobe.conf, from /etc/modprobe.d/Lustre, or else none will be used.
289 #
290 load_module() {
291     local optvar
292     EXT=".ko"
293     module=$1
294     shift
295     BASE=`basename $module $EXT`
296
297     module_loaded ${BASE} && return
298
299     # If no module arguments were passed, get them from $MODOPTS_<MODULE>, else from
300     # modprobe.conf
301     if [ $# -eq 0 ]; then
302         # $MODOPTS_<MODULE>; we could use associative arrays, but that's not in
303         # Bash until 4.x, so we resort to eval.
304         optvar="MODOPTS_$(basename $module | tr a-z A-Z)"
305         eval set -- \$$optvar
306         if [ $# -eq 0 -a -n "$MODPROBECONF" ]; then
307             # Nothing in $MODOPTS_<MODULE>; try modprobe.conf
308             set -- $(grep -P "^options\\s+${BASE}" $MODPROBECONF)
309             # Get rid of "options $module"
310             (($# > 0)) && shift 2
311
312             # Ensure we have accept=all for lnet
313             if [ $(basename $module) = lnet ]; then
314                 # OK, this is a bit wordy...
315                 local arg accept_all_present=false
316                 for arg in "$@"; do
317                     [ "$arg" = accept=all ] && accept_all_present=true
318                 done
319                 $accept_all_present || set -- "$@" accept=all
320             fi
321         fi
322     fi
323
324     [ $# -gt 0 ] && echo "${module} options: '$*'"
325
326     # Note that insmod will ignore anything in modprobe.conf, which is why we're
327     # passing options on the command-line.
328     if [ "$BASE" == "lnet_selftest" ] && \
329             [ -f ${LUSTRE}/../lnet/selftest/${module}${EXT} ]; then
330         insmod ${LUSTRE}/../lnet/selftest/${module}${EXT}
331     elif [ -f ${LUSTRE}/${module}${EXT} ]; then
332         insmod ${LUSTRE}/${module}${EXT} "$@"
333     else
334         # must be testing a "make install" or "rpm" installation
335         # note failed to load ptlrpc_gss is considered not fatal
336         if [ "$BASE" == "ptlrpc_gss" ]; then
337             modprobe $BASE "$@" 2>/dev/null || echo "gss/krb5 is not supported"
338         else
339             modprobe $BASE "$@"
340         fi
341     fi
342 }
343
344 llite_lloop_enabled() {
345     local n1=$(uname -r | cut -d. -f1)
346     local n2=$(uname -r | cut -d. -f2)
347     local n3=$(uname -r | cut -d- -f1 | cut -d. -f3)
348
349     # load the llite_lloop module for < 2.6.32 kernels
350     if [[ $n1 -lt 2 ]] || [[ $n1 -eq 2 && $n2 -lt 6 ]] || \
351        [[ $n1 -eq 2 && $n2 -eq 6 && $n3 -lt 32 ]] || \
352         $LOAD_LLOOP; then
353         return 0
354     fi
355     return 1
356 }
357
358 load_modules_local() {
359         if [ "$USE_OFD" == yes ]; then
360                 if module_loaded obdfilter; then
361                         if ! $LUSTRE_RMMOD ldiskfs; then
362                                 echo "$HOSTNAME may still be using obdfilter.ko"
363                                 return 1
364                         fi
365                 fi
366         else
367                 if module_loaded ofd; then
368                         if ! $LUSTRE_RMMOD ldiskfs; then
369                                 echo "$HOSTNAME may still be using ofd.ko"
370                                 return 1
371                         fi
372                 fi
373         fi
374
375         if [ -n "$MODPROBE" ]; then
376                 # use modprobe
377                 echo "Using modprobe to load modules"
378                 return 0
379         fi
380
381     echo Loading modules from $LUSTRE
382     load_module ../libcfs/libcfs/libcfs
383     [ "$PTLDEBUG" ] && lctl set_param debug="$PTLDEBUG"
384     [ "$SUBSYSTEM" ] && lctl set_param subsystem_debug="${SUBSYSTEM# }"
385     load_module ../lnet/lnet/lnet
386     LNETLND=${LNETLND:-"socklnd/ksocklnd"}
387     load_module ../lnet/klnds/$LNETLND
388     load_module lvfs/lvfs
389     load_module obdclass/obdclass
390     load_module ptlrpc/ptlrpc
391     load_module ptlrpc/gss/ptlrpc_gss
392     load_module fld/fld
393     load_module fid/fid
394     load_module lmv/lmv
395     load_module mdc/mdc
396     load_module osc/osc
397     load_module lov/lov
398     load_module mgc/mgc
399     if ! client_only; then
400         SYMLIST=/proc/kallsyms
401         grep -q crc16 $SYMLIST || { modprobe crc16 2>/dev/null || true; }
402         grep -q -w jbd $SYMLIST || { modprobe jbd 2>/dev/null || true; }
403         grep -q -w jbd2 $SYMLIST || { modprobe jbd2 2>/dev/null || true; }
404                 if [[ $(node_fstypes $HOSTNAME) == *ldiskfs* ]]; then
405                         grep -q exportfs_decode_fh $SYMLIST ||
406                         { modprobe exportfs 2> /dev/null || true; }
407                         load_module ../ldiskfs/ldiskfs/ldiskfs
408                 fi
409                 [ "$LQUOTA" != "no" ] && load_module quota/lquota $LQUOTAOPTS
410                 load_module mgs/mgs
411                 load_module mds/mds
412                 load_module mdd/mdd
413                 load_module mdt/mdt
414                 load_module lvfs/fsfilt_ldiskfs
415                 load_module cmm/cmm
416                 load_module osd-ldiskfs/osd_ldiskfs
417                 load_module ost/ost
418                 if [ "$USE_OFD" == yes ]; then
419                         load_module ofd/ofd
420                 else
421                         load_module obdfilter/obdfilter
422                 fi
423     fi
424
425
426     load_module llite/lustre
427     llite_lloop_enabled && load_module llite/llite_lloop
428     [ -d /r ] && OGDB=${OGDB:-"/r/tmp"}
429     OGDB=${OGDB:-$TMP}
430     rm -f $OGDB/ogdb-$HOSTNAME
431     $LCTL modules > $OGDB/ogdb-$HOSTNAME
432
433     # 'mount' doesn't look in $PATH, just sbin
434     if [ -f $LUSTRE/utils/mount.lustre ] && \
435        ! grep -qe "/sbin/mount\.lustre " /proc/mounts; then
436         [ ! -f /sbin/mount.lustre ] && touch /sbin/mount.lustre
437         mount --bind $LUSTRE/utils/mount.lustre /sbin/mount.lustre || true
438     fi
439 }
440
441 load_modules () {
442         load_modules_local
443         # bug 19124
444         # load modules on remote nodes optionally
445         # lustre-tests have to be installed on these nodes
446         if $LOAD_MODULES_REMOTE ; then
447                 local list=$(comma_list $(remote_nodes_list))
448                 echo loading modules on $list
449                 do_rpc_nodes $list load_modules_local
450         fi
451 }
452
453 check_mem_leak () {
454     LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
455     LEAK_PORTALS=$(dmesg | tail -n 20 | grep "Portals memory leaked" || true)
456     if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
457         echo "$LEAK_LUSTRE" 1>&2
458         echo "$LEAK_PORTALS" 1>&2
459         mv $TMP/debug $TMP/debug-leak.`date +%s` || true
460         echo "Memory leaks detected"
461         [ -n "$IGNORE_LEAK" ] && { echo "ignoring leaks" && return 0; } || true
462         return 1
463     fi
464 }
465
466 unload_modules() {
467         wait_exit_ST client # bug 12845
468
469         $LUSTRE_RMMOD ldiskfs || return 2
470
471         if $LOAD_MODULES_REMOTE ; then
472                 local list=$(comma_list $(remote_nodes_list))
473                 if [ ! -z $list ]; then
474                         echo unloading modules on $list
475                         do_rpc_nodes $list $LUSTRE_RMMOD ldiskfs
476                         do_rpc_nodes $list check_mem_leak
477                 fi
478         fi
479
480     if grep -qe "/sbin/mount\.lustre" /proc/mounts; then
481         umount /sbin/mount.lustre || true
482         [ -w /sbin/mount.lustre -a ! -s /sbin/mount.lustre ] && \
483             rm -f /sbin/mount.lustre || true
484     fi
485
486     check_mem_leak || return 254
487
488     echo "modules unloaded."
489     return 0
490 }
491
492 check_gss_daemon_nodes() {
493     local list=$1
494     dname=$2
495
496     do_nodesv $list "num=\\\$(ps -o cmd -C $dname | grep $dname | wc -l);
497 if [ \\\"\\\$num\\\" -ne 1 ]; then
498     echo \\\$num instance of $dname;
499     exit 1;
500 fi; "
501 }
502
503 check_gss_daemon_facet() {
504     facet=$1
505     dname=$2
506
507     num=`do_facet $facet ps -o cmd -C $dname | grep $dname | wc -l`
508     if [ $num -ne 1 ]; then
509         echo "$num instance of $dname on $facet"
510         return 1
511     fi
512     return 0
513 }
514
515 send_sigint() {
516     local list=$1
517     shift
518     echo Stopping $@ on $list
519     do_nodes $list "killall -2 $@ 2>/dev/null || true"
520 }
521
522 # start gss daemons on all nodes, or
523 # "daemon" on "list" if set
524 start_gss_daemons() {
525     local list=$1
526     local daemon=$2
527
528     if [ "$list" ] && [ "$daemon" ] ; then
529         echo "Starting gss daemon on nodes: $list"
530         do_nodes $list "$daemon" || return 8
531         return 0
532     fi
533
534     local list=$(comma_list $(mdts_nodes))
535
536     echo "Starting gss daemon on mds: $list"
537     do_nodes $list "$LSVCGSSD -v" || return 1
538     if $GSS_PIPEFS; then
539         do_nodes $list "$LGSSD -v" || return 2
540     fi
541
542     list=$(comma_list $(osts_nodes))
543     echo "Starting gss daemon on ost: $list"
544     do_nodes $list "$LSVCGSSD -v" || return 3
545     # starting on clients
546
547     local clients=${CLIENTS:-`hostname`}
548     if $GSS_PIPEFS; then
549         echo "Starting $LGSSD on clients $clients "
550         do_nodes $clients  "$LGSSD -v" || return 4
551     fi
552
553     # wait daemons entering "stable" status
554     sleep 5
555
556     #
557     # check daemons are running
558     #
559     list=$(comma_list $(mdts_nodes) $(osts_nodes))
560     check_gss_daemon_nodes $list lsvcgssd || return 5
561     if $GSS_PIPEFS; then
562         list=$(comma_list $(mdts_nodes))
563         check_gss_daemon_nodes $list lgssd || return 6
564     fi
565     if $GSS_PIPEFS; then
566         check_gss_daemon_nodes $clients lgssd || return 7
567     fi
568 }
569
570 stop_gss_daemons() {
571     local list=$(comma_list $(mdts_nodes))
572     
573     send_sigint $list lsvcgssd lgssd
574
575     list=$(comma_list $(osts_nodes))
576     send_sigint $list lsvcgssd
577
578     list=${CLIENTS:-`hostname`}
579     send_sigint $list lgssd
580 }
581
582 init_gss() {
583     if $GSS; then
584         if ! module_loaded ptlrpc_gss; then
585             load_module ptlrpc/gss/ptlrpc_gss
586             module_loaded ptlrpc_gss ||
587                 error_exit "init_gss : GSS=$GSS, but gss/krb5 is not supported!"
588         fi
589         start_gss_daemons || error_exit "start gss daemon failed! rc=$?"
590
591         if [ -n "$LGSS_KEYRING_DEBUG" ]; then
592             echo $LGSS_KEYRING_DEBUG > /proc/fs/lustre/sptlrpc/gss/lgss_keyring/debug_level
593         fi
594     fi
595 }
596
597 cleanup_gss() {
598     if $GSS; then
599         stop_gss_daemons
600         # maybe cleanup credential cache?
601     fi
602 }
603
604 facet_type() {
605         local facet=$1
606
607         echo -n $facet | sed -e 's/^fs[0-9]\+//' -e 's/[0-9]\+//' |
608                 tr '[:lower:]' '[:upper:]'
609 }
610
611 facet_number() {
612         local facet=$1
613
614         if [ $facet == mgs ]; then
615                 return 1
616         fi
617
618         echo -n $facet | sed -e 's/^fs[0-9]\+//' | sed -e 's/^[a-z]\+//'
619 }
620
621 facet_fstype() {
622         local facet=$1
623         local var
624
625         var=${facet}_FSTYPE
626         if [ -n "${!var}" ]; then
627                 echo -n ${!var}
628                 return
629         fi
630
631         var=$(facet_type $facet)FSTYPE
632         if [ -n "${!var}" ]; then
633                 echo -n ${!var}
634                 return
635         fi
636
637         if [ -n "$FSTYPE" ]; then
638                 echo -n $FSTYPE
639                 return
640         fi
641
642         return 1
643 }
644
645 node_fstypes() {
646         local node=$1
647         local fstypes
648         local fstype
649         local facets=$(get_facets)
650         local facet
651
652         for facet in ${facets//,/ }; do
653                 if [ $node == $(facet_host $facet) ] ||
654                    [ $node == "$(facet_failover_host $facet)" ]; then
655                         fstype=$(facet_fstype $facet)
656                         if [[ $fstypes != *$fstype* ]]; then
657                                 fstypes+="${fstypes:+,}$fstype"
658                         fi
659                 fi
660         done
661         echo -n $fstypes
662 }
663
664 devicelabel() {
665         local facet=$1
666         local dev=$2
667         local label
668         local fstype=$(facet_fstype $facet)
669
670         case $fstype in
671         ldiskfs)
672                 label=$(do_facet ${facet} "$E2LABEL ${dev} 2>/dev/null");;
673         zfs)
674                 label=$(do_facet ${facet} "$ZFS get -H -o value lustre:svname \
675                                            ${dev} 2>/dev/null");;
676         *)
677                 error "unknown fstype!";;
678         esac
679
680         echo -n $label
681 }
682
683 mdsdevlabel() {
684         local num=$1
685         local device=$(mdsdevname $num)
686         local label=$(devicelabel mds$num ${device} | grep -v "CMD: ")
687         echo -n $label
688 }
689
690 ostdevlabel() {
691         local num=$1
692         local device=$(ostdevname $num)
693         local label=$(devicelabel ost$num ${device} | grep -v "CMD: ")
694         echo -n $label
695 }
696
697 set_debug_size () {
698     local dz=${1:-$DEBUG_SIZE}
699
700     if [ -f /sys/devices/system/cpu/possible ]; then
701         local cpus=$(($(cut -d "-" -f 2 /sys/devices/system/cpu/possible)+1))
702     else
703         local cpus=$(getconf _NPROCESSORS_CONF)
704     fi
705
706     # bug 19944, adjust size to be -gt num_possible_cpus()
707     # promise 2MB for every cpu at least
708     if [ -n "$cpus" ] && [ $((cpus * 2)) -gt $dz ]; then
709         dz=$((cpus * 2))
710     fi
711     lctl set_param debug_mb=$dz
712 }
713
714 set_default_debug () {
715     local debug=${1:-"$PTLDEBUG"}
716     local subsys=${2:-"$SUBSYSTEM"}
717     local debug_size=${3:-$DEBUG_SIZE}
718
719     [ -n "$debug" ] && lctl set_param debug="$debug" >/dev/null
720     [ -n "$subsys" ] && lctl set_param subsystem_debug="${subsys# }" >/dev/null
721
722     [ -n "$debug_size" ] && set_debug_size $debug_size > /dev/null
723 }
724
725 set_default_debug_nodes () {
726     local nodes=$1
727
728     if [[ ,$nodes, = *,$HOSTNAME,* ]]; then
729         nodes=$(exclude_items_from_list "$nodes" "$HOSTNAME")
730             set_default_debug
731     fi
732
733     [[ -n $nodes ]] && do_rpc_nodes $nodes set_default_debug \
734         \\\"$PTLDEBUG\\\" \\\"$SUBSYSTEM\\\" $DEBUG_SIZE || true
735 }
736
737 set_default_debug_facet () {
738     local facet=$1
739     local node=$(facet_active_host $facet)
740     [ -z "$node" ] && echo "No host defined for facet $facet" && exit 1
741
742     set_default_debug_nodes $node
743 }
744
745 # Facet functions
746 mount_facets () {
747         local facets=${1:-$(get_facets)}
748         local facet
749
750         for facet in ${facets//,/ }; do
751                 mount_facet $facet
752                 local RC=$?
753                 [ $RC -eq 0 ] && continue
754
755                 if [ "$TESTSUITE.$TESTNAME" = "replay-dual.test_0a" ]; then
756                         skip "Restart of $facet failed!." && touch $LU482_FAILED
757                 else
758                         error "Restart of $facet failed!"
759                 fi
760                 return $RC
761         done
762 }
763
764 #
765 # Add argument "arg" (e.g., "loop") to the comma-separated list
766 # of arguments for option "opt" (e.g., "-o") on command
767 # line "opts" (e.g., "-o flock").
768 #
769 csa_add() {
770         local opts=$1
771         local opt=$2
772         local arg=$3
773         local opt_pattern="\([[:space:]]\+\|^\)$opt"
774
775         if echo "$opts" | grep -q $opt_pattern; then
776                 opts=$(echo "$opts" | sed -e \
777                         "s/$opt_pattern[[:space:]]*[^[:space:]]\+/&,$arg/")
778         else
779                 opts+="${opts:+ }$opt $arg"
780         fi
781         echo -n "$opts"
782 }
783
784 mount_facet() {
785         local facet=$1
786         shift
787         local dev=$(facet_active $facet)_dev
788         local opt=${facet}_opt
789         local mntpt=$(facet_mntpt $facet)
790         local opts="${!opt} $@"
791
792         if [ $(facet_fstype $facet) == ldiskfs ] &&
793            ! do_facet $facet test -b ${!dev}; then
794                 opts=$(csa_add "$opts" -o loop)
795         fi
796
797         echo "Starting ${facet}: $opts ${!dev} $mntpt"
798         # for testing LU-482 error handling in mount_facets() and test_0a()
799         if [ -f $TMP/test-lu482-trigger ]; then
800                 RC=2
801         else
802                 do_facet ${facet} "mkdir -p $mntpt; mount -t lustre $opts \
803                                    ${!dev} $mntpt"
804                 RC=${PIPESTATUS[0]}
805         fi
806         if [ $RC -ne 0 ]; then
807                 echo "Start of ${!dev} on ${facet} failed ${RC}"
808     else
809         set_default_debug_facet $facet
810
811                 label=$(devicelabel ${facet} ${!dev})
812         [ -z "$label" ] && echo no label for ${!dev} && exit 1
813         eval export ${facet}_svc=${label}
814         echo Started ${label}
815     fi
816     return $RC
817 }
818
819 # start facet device options
820 start() {
821     local facet=$1
822     shift
823     local device=$1
824     shift
825     eval export ${facet}_dev=${device}
826     eval export ${facet}_opt=\"$@\"
827
828     local varname=${facet}failover_dev
829     if [ -n "${!varname}" ] ; then
830         eval export ${facet}failover_dev=${!varname}
831     else
832         eval export ${facet}failover_dev=$device
833     fi
834
835     local mntpt=$(facet_mntpt $facet)
836     do_facet ${facet} mkdir -p $mntpt
837     eval export ${facet}_MOUNT=$mntpt
838     mount_facet ${facet}
839     RC=$?
840     return $RC
841 }
842
843 stop() {
844     local running
845     local facet=$1
846     shift
847     local HOST=`facet_active_host $facet`
848     [ -z $HOST ] && echo stop: no host for $facet && return 0
849
850     local mntpt=$(facet_mntpt $facet)
851     running=$(do_facet ${facet} "grep -c $mntpt' ' /proc/mounts") || true
852     if [ ${running} -ne 0 ]; then
853         echo "Stopping $mntpt (opts:$@) on $HOST"
854         do_facet ${facet} umount -d $@ $mntpt
855     fi
856
857     # umount should block, but we should wait for unrelated obd's
858     # like the MGS or MGC to also stop.
859     wait_exit_ST ${facet}
860 }
861
862 # save quota version (both administrative and operational quotas)
863 # add an additional parameter if mountpoint is ever different from $MOUNT
864 quota_save_version() {
865     local fsname=${2:-$FSNAME}
866     local spec=$1
867     local ver=$(tr -c -d "123" <<< $spec)
868     local type=$(tr -c -d "ug" <<< $spec)
869
870     [ -n "$ver" -a "$ver" != "3" ] && error "wrong quota version specifier"
871
872     [ -n "$type" ] && { $LFS quotacheck -$type $MOUNT || error "quotacheck has failed"; }
873
874     do_facet mgs "lctl conf_param ${fsname}-MDT*.mdd.quota_type=$spec"
875     local varsvc
876     local osts=$(get_facets OST)
877     for ost in ${osts//,/ }; do
878         varsvc=${ost}_svc
879         do_facet mgs "lctl conf_param ${!varsvc}.ost.quota_type=$spec"
880     done
881 }
882
883 # client could mount several lustre 
884 quota_type () {
885     local fsname=${1:-$FSNAME}
886     local rc=0
887     do_facet mgs lctl get_param mdd.${fsname}-MDT*.quota_type || rc=$?
888     do_nodes $(comma_list $(osts_nodes)) \
889         lctl get_param obdfilter.${fsname}-OST*.quota_type || rc=$?
890     return $rc 
891 }
892
893 restore_quota_type () {
894    local mntpt=${1:-$MOUNT}
895    local quota_type=$(quota_type $FSNAME | grep MDT | cut -d "=" -f2)
896    if [ ! "$old_QUOTA_TYPE" ] || [ "$quota_type" = "$old_QUOTA_TYPE" ]; then
897         return
898    fi
899    quota_save_version $old_QUOTA_TYPE
900 }
901
902 setup_quota(){
903     local mntpt=$1
904
905         if [ "$USE_OFD" = "yes" ]; then
906                 $LFS quotacheck $mntpt || error "quotacheck failed"
907                 return
908         fi
909
910     # We need save the original quota_type params, and restore them after testing
911
912     # Suppose that quota type the same on mds and ost
913     local quota_type=$(quota_type | grep MDT | cut -d "=" -f2)
914     [ ${PIPESTATUS[0]} -eq 0 ] || error "quota_type failed!"
915     echo "[HOST:$HOSTNAME] [old_quota_type:$quota_type] [new_quota_type:$QUOTA_TYPE]"
916     if [ "$quota_type" != "$QUOTA_TYPE" ]; then
917         export old_QUOTA_TYPE=$quota_type
918         quota_save_version $QUOTA_TYPE
919     else
920         qtype=$(tr -c -d "ug" <<< $QUOTA_TYPE)
921         $LFS quotacheck -$qtype $mntpt || error "quotacheck has failed for $type"
922     fi
923
924     local quota_usrs=$QUOTA_USERS
925
926     # get_filesystem_size
927     local disksz=$(lfs df $mntpt | grep "filesystem summary:"  | awk '{print $3}')
928     local blk_soft=$((disksz + 1024))
929     local blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over
930
931     local Inodes=$(lfs df -i $mntpt | grep "filesystem summary:"  | awk '{print $3}')
932     local i_soft=$Inodes
933     local i_hard=$((i_soft + i_soft / 20))
934
935     echo "Total disk size: $disksz  block-softlimit: $blk_soft block-hardlimit:
936         $blk_hard inode-softlimit: $i_soft inode-hardlimit: $i_hard"
937
938     local cmd
939     for usr in $quota_usrs; do
940         echo "Setting up quota on $HOSTNAME:$mntpt for $usr..."
941         for type in u g; do
942             cmd="$LFS setquota -$type $usr -b $blk_soft -B $blk_hard -i $i_soft -I $i_hard $mntpt"
943             echo "+ $cmd"
944             eval $cmd || error "$cmd FAILED!"
945         done
946         # display the quota status
947         echo "Quota settings for $usr : "
948         $LFS quota -v -u $usr $mntpt || true
949     done
950 }
951
952 zconf_mount() {
953     local client=$1
954     local mnt=$2
955     local OPTIONS=${3:-$MOUNTOPT}
956
957     local device=$MGSNID:/$FSNAME
958     if [ -z "$mnt" -o -z "$FSNAME" ]; then
959         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
960         exit 1
961     fi
962
963     echo "Starting client: $client: $OPTIONS $device $mnt"
964     do_node $client mkdir -p $mnt
965     do_node $client mount -t lustre $OPTIONS $device $mnt || return 1
966
967     set_default_debug_nodes $client
968
969     return 0
970 }
971
972 zconf_umount() {
973     local client=$1
974     local mnt=$2
975     local force
976     local busy 
977     local need_kill
978
979     [ "$3" ] && force=-f
980     local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
981     if [ $running -ne 0 ]; then
982         echo "Stopping client $client $mnt (opts:$force)"
983         do_node $client lsof -t $mnt || need_kill=no
984         if [ "x$force" != "x" -a "x$need_kill" != "xno" ]; then
985             pids=$(do_node $client lsof -t $mnt | sort -u);
986             if [ -n $pids ]; then
987                 do_node $client kill -9 $pids || true
988             fi
989         fi
990
991         busy=$(do_node $client "umount $force $mnt 2>&1" | grep -c "busy") || true
992         if [ $busy -ne 0 ] ; then
993             echo "$mnt is still busy, wait one second" && sleep 1
994             do_node $client umount $force $mnt
995         fi
996     fi
997 }
998
999 # nodes is comma list
1000 sanity_mount_check_nodes () {
1001     local nodes=$1
1002     shift
1003     local mnts="$@"
1004     local mnt
1005
1006     # FIXME: assume that all cluster nodes run the same os
1007     [ "$(uname)" = Linux ] || return 0
1008
1009     local rc=0
1010     for mnt in $mnts ; do
1011         do_nodes $nodes "running=\\\$(grep -c $mnt' ' /proc/mounts);
1012 mpts=\\\$(mount | grep -c $mnt' ');
1013 if [ \\\$running -ne \\\$mpts ]; then
1014     echo \\\$(hostname) env are INSANE!;
1015     exit 1;
1016 fi"
1017     [ $? -eq 0 ] || rc=1 
1018     done
1019     return $rc
1020 }
1021
1022 sanity_mount_check_servers () {
1023     [ "$CLIENTONLY" ] && 
1024         { echo "CLIENTONLY mode, skip mount_check_servers"; return 0; } || true
1025     echo Checking servers environments
1026
1027     # FIXME: modify get_facets to display all facets wo params
1028     local facets="$(get_facets OST),$(get_facets MDS),mgs"
1029     local node
1030     local mntpt
1031     local facet
1032     for facet in ${facets//,/ }; do
1033         node=$(facet_host ${facet})
1034         mntpt=$(facet_mntpt $facet)
1035         sanity_mount_check_nodes $node $mntpt ||
1036             { error "server $node environments are insane!"; return 1; }
1037     done
1038 }
1039
1040 sanity_mount_check_clients () {
1041     local clients=${1:-$CLIENTS}
1042     local mntpt=${2:-$MOUNT}
1043     local mntpt2=${3:-$MOUNT2}
1044
1045     [ -z $clients ] && clients=$(hostname)
1046     echo Checking clients $clients environments
1047
1048     sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
1049        error "clients environments are insane!"
1050 }
1051
1052 sanity_mount_check () {
1053     sanity_mount_check_servers || return 1
1054     sanity_mount_check_clients || return 2
1055 }
1056
1057 # mount clients if not mouted
1058 zconf_mount_clients() {
1059     local clients=$1
1060     local mnt=$2
1061     local OPTIONS=${3:-$MOUNTOPT}
1062
1063     local device=$MGSNID:/$FSNAME
1064     if [ -z "$mnt" -o -z "$FSNAME" ]; then
1065         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
1066         exit 1
1067     fi
1068
1069     echo "Starting client $clients: $OPTIONS $device $mnt"
1070
1071     do_nodes $clients "
1072 running=\\\$(mount | grep -c $mnt' ');
1073 rc=0;
1074 if [ \\\$running -eq 0 ] ; then
1075     mkdir -p $mnt;
1076     mount -t lustre $OPTIONS $device $mnt;
1077     rc=\\\$?;
1078 fi;
1079 exit \\\$rc" || return ${PIPESTATUS[0]}
1080
1081     echo "Started clients $clients: "
1082     do_nodes $clients "mount | grep $mnt' '"
1083
1084     set_default_debug_nodes $clients
1085
1086     return 0
1087 }
1088
1089 zconf_umount_clients() {
1090     local clients=$1
1091     local mnt=$2
1092     local force
1093
1094     [ "$3" ] && force=-f
1095
1096     echo "Stopping clients: $clients $mnt (opts:$force)"
1097     do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
1098 if [ \\\$running -ne 0 ] ; then
1099 echo Stopping client \\\$(hostname) $mnt opts:$force;
1100 lsof $mnt || need_kill=no;
1101 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
1102     pids=\\\$(lsof -t $mnt | sort -u);
1103     if [ -n \\\"\\\$pids\\\" ]; then
1104              kill -9 \\\$pids;
1105     fi
1106 fi;
1107 while umount $force $mnt 2>&1 | grep -q "busy"; do
1108     echo "$mnt is still busy, wait one second" && sleep 1;
1109 done;
1110 fi"
1111 }
1112
1113 shutdown_node () {
1114     local node=$1
1115     echo + $POWER_DOWN $node
1116     $POWER_DOWN $node
1117 }
1118
1119 shutdown_node_hard () {
1120     local host=$1
1121     local attempts=$SHUTDOWN_ATTEMPTS
1122
1123     for i in $(seq $attempts) ; do
1124         shutdown_node $host
1125         sleep 1
1126         wait_for_function --quiet "! ping -w 3 -c 1 $host" 5 1 && return 0
1127         echo "waiting for $host to fail attempts=$attempts"
1128         [ $i -lt $attempts ] || \
1129             { echo "$host still pingable after power down! attempts=$attempts" && return 1; } 
1130     done
1131 }
1132
1133 shutdown_client() {
1134     local client=$1
1135     local mnt=${2:-$MOUNT}
1136     local attempts=3
1137
1138     if [ "$FAILURE_MODE" = HARD ]; then
1139         shutdown_node_hard $client
1140     else
1141        zconf_umount_clients $client $mnt -f
1142     fi
1143 }
1144
1145 facets_on_host () {
1146     local host=$1
1147     local facets="$(get_facets OST),$(get_facets MDS)"
1148     local affected
1149
1150     combined_mgs_mds || facets="$facets,mgs"
1151
1152     for facet in ${facets//,/ }; do
1153         if [ $(facet_active_host $facet) == $host ]; then
1154            affected="$affected $facet"
1155         fi
1156     done
1157
1158     echo $(comma_list $affected)
1159 }
1160
1161 facet_up () {
1162     local facet=$1
1163     local host=${2:-$(facet_host $facet)}
1164
1165     local label=$(convert_facet2label $facet)
1166     do_node $host lctl dl | awk '{print $4}' | grep -q $label
1167 }
1168
1169 facets_up_on_host () {
1170     local host=$1
1171     local facets=$(facets_on_host $host)
1172     local affected_up
1173
1174     for facet in ${facets//,/ }; do
1175         if $(facet_up $facet $host); then
1176             affected_up="$affected_up $facet"
1177         fi
1178     done
1179
1180     echo $(comma_list $affected_up)
1181 }
1182
1183 shutdown_facet() {
1184     local facet=$1
1185
1186     if [ "$FAILURE_MODE" = HARD ]; then
1187         shutdown_node_hard $(facet_active_host $facet)
1188     else
1189         stop $facet
1190     fi
1191 }
1192
1193 reboot_node() {
1194     local node=$1
1195     echo + $POWER_UP $node
1196     $POWER_UP $node
1197 }
1198
1199 remount_facet() {
1200     local facet=$1
1201
1202     stop $facet
1203     mount_facet $facet
1204 }
1205
1206 reboot_facet() {
1207     local facet=$1
1208     if [ "$FAILURE_MODE" = HARD ]; then
1209         reboot_node $(facet_active_host $facet)
1210     else
1211         sleep 10
1212     fi
1213 }
1214
1215 boot_node() {
1216     local node=$1
1217     if [ "$FAILURE_MODE" = HARD ]; then
1218        reboot_node $node
1219        wait_for_host $node
1220     fi
1221 }
1222
1223 facets_hosts () {
1224     local facets=$1
1225     local hosts
1226
1227     for facet in ${facets//,/ }; do
1228         hosts=$(expand_list $hosts $(facet_host $facet) )
1229     done
1230
1231     echo $hosts
1232 }
1233
1234 _check_progs_installed () {
1235     local progs=$@
1236     local rc=0
1237
1238     for prog in $progs; do
1239         if ! [ "$(which $prog)"  -o  "${!prog}" ]; then
1240            echo $prog missing on $(hostname)
1241            rc=1
1242         fi
1243     done
1244     return $rc
1245 }
1246
1247 check_progs_installed () {
1248     local nodes=$1
1249     shift
1250
1251     do_rpc_nodes $nodes _check_progs_installed $@
1252 }
1253
1254 # recovery-scale functions
1255 node_var_name() {
1256     echo __$(echo $1 | tr '-' '_' | tr '.' '_')
1257 }
1258
1259 start_client_load() {
1260     local client=$1
1261     local load=$2
1262     local var=$(node_var_name $client)_load
1263     eval export ${var}=$load
1264
1265     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
1266 BREAK_ON_ERROR=$BREAK_ON_ERROR \
1267 END_RUN_FILE=$END_RUN_FILE \
1268 LOAD_PID_FILE=$LOAD_PID_FILE \
1269 TESTLOG_PREFIX=$TESTLOG_PREFIX \
1270 TESTNAME=$TESTNAME \
1271 DBENCH_LIB=$DBENCH_LIB \
1272 DBENCH_SRC=$DBENCH_SRC \
1273 run_${load}.sh" &
1274     local ppid=$!
1275     log "Started client load: ${load} on $client"
1276
1277     # get the children process IDs
1278     local pids=$(ps --ppid $ppid -o pid= | xargs)
1279     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $ppid $pids"
1280     return 0
1281 }
1282
1283 start_client_loads () {
1284     local -a clients=(${1//,/ })
1285     local numloads=${#CLIENT_LOADS[@]}
1286     local testnum
1287
1288     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
1289         testnum=$((nodenum % numloads))
1290         start_client_load ${clients[nodenum]} ${CLIENT_LOADS[testnum]}
1291     done
1292     # bug 22169: wait the background threads to start
1293     sleep 2
1294 }
1295
1296 # only for remote client
1297 check_client_load () {
1298     local client=$1
1299     local var=$(node_var_name $client)_load
1300     local TESTLOAD=run_${!var}.sh
1301
1302     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
1303
1304     # bug 18914: try to connect several times not only when
1305     # check ps, but  while check_catastrophe also
1306     local tries=3
1307     local RC=254
1308     while [ $RC = 254 -a $tries -gt 0 ]; do
1309         let tries=$tries-1
1310         # assume success
1311         RC=0
1312         if ! check_catastrophe $client; then
1313             RC=${PIPESTATUS[0]}
1314             if [ $RC -eq 254 ]; then
1315                 # FIXME: not sure how long we shuold sleep here
1316                 sleep 10
1317                 continue
1318             fi
1319             echo "check catastrophe failed: RC=$RC "
1320             return $RC
1321         fi
1322     done
1323     # We can continue try to connect if RC=254
1324     # Just print the warning about this
1325     if [ $RC = 254 ]; then
1326         echo "got a return status of $RC from do_node while checking catastrophe on $client"
1327     fi
1328
1329     # see if the load is still on the client
1330     tries=3
1331     RC=254
1332     while [ $RC = 254 -a $tries -gt 0 ]; do
1333         let tries=$tries-1
1334         # assume success
1335         RC=0
1336         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
1337             RC=${PIPESTATUS[0]}
1338             sleep 30
1339         fi
1340     done
1341     if [ $RC = 254 ]; then
1342         echo "got a return status of $RC from do_node while checking (catastrophe and 'ps') the client load on $client"
1343         # see if we can diagnose a bit why this is
1344     fi
1345
1346     return $RC
1347 }
1348 check_client_loads () {
1349    local clients=${1//,/ }
1350    local client=
1351    local rc=0
1352
1353    for client in $clients; do
1354       check_client_load $client
1355       rc=${PIPESTATUS[0]}
1356       if [ "$rc" != 0 ]; then
1357         log "Client load failed on node $client, rc=$rc"
1358         return $rc
1359       fi
1360    done
1361 }
1362
1363 restart_client_loads () {
1364     local clients=${1//,/ }
1365     local expectedfail=${2:-""}
1366     local client=
1367     local rc=0
1368
1369     for client in $clients; do
1370         check_client_load $client
1371         rc=${PIPESTATUS[0]}
1372         if [ "$rc" != 0 -a "$expectedfail" ]; then
1373             local var=$(node_var_name $client)_load
1374             start_client_load $client ${!var}
1375             echo "Restarted client load ${!var}: on $client. Checking ..."
1376             check_client_load $client
1377             rc=${PIPESTATUS[0]}
1378             if [ "$rc" != 0 ]; then
1379                 log "Client load failed to restart on node $client, rc=$rc"
1380                 # failure one client load means test fail
1381                 # we do not need to check other
1382                 return $rc
1383             fi
1384         else
1385             return $rc
1386         fi
1387     done
1388 }
1389
1390 # Start vmstat and save its process ID in a file.
1391 start_vmstat() {
1392     local nodes=$1
1393     local pid_file=$2
1394
1395     [ -z "$nodes" -o -z "$pid_file" ] && return 0
1396
1397     do_nodes $nodes \
1398         "vmstat 1 > $TESTLOG_PREFIX.$TESTNAME.vmstat.\\\$(hostname -s).log \
1399         2>/dev/null </dev/null & echo \\\$! > $pid_file"
1400 }
1401
1402 # Display the nodes on which client loads failed.
1403 print_end_run_file() {
1404     local file=$1
1405     local node
1406
1407     [ -s $file ] || return 0
1408
1409     echo "Found the END_RUN_FILE file: $file"
1410     cat $file
1411
1412     # A client load will stop if it finds the END_RUN_FILE file.
1413     # That does not mean the client load actually failed though.
1414     # The first node in END_RUN_FILE is the one we are interested in.
1415     read node < $file
1416
1417     if [ -n "$node" ]; then
1418         local var=$(node_var_name $node)_load
1419
1420         local prefix=$TESTLOG_PREFIX
1421         [ -n "$TESTNAME" ] && prefix=$prefix.$TESTNAME
1422         local stdout_log=$prefix.run_${!var}_stdout.$node.log
1423         local debug_log=$(echo $stdout_log | sed 's/\(.*\)stdout/\1debug/')
1424
1425         echo "Client load ${!var} failed on node $node:"
1426         echo "$stdout_log"
1427         echo "$debug_log"
1428     fi
1429 }
1430
1431 # Stop the process which had its PID saved in a file.
1432 stop_process() {
1433     local nodes=$1
1434     local pid_file=$2
1435
1436     [ -z "$nodes" -o -z "$pid_file" ] && return 0
1437
1438     do_nodes $nodes "test -f $pid_file &&
1439         { kill -s TERM \\\$(cat $pid_file); rm -f $pid_file; }" || true
1440 }
1441
1442 # Stop all client loads.
1443 stop_client_loads() {
1444     local nodes=${1:-$CLIENTS}
1445     local pid_file=$2
1446
1447     # stop the client loads
1448     stop_process $nodes $pid_file
1449
1450     # clean up the processes that started them
1451     [ -n "$CLIENT_LOAD_PIDS" ] && kill -9 $CLIENT_LOAD_PIDS 2>/dev/null || true
1452 }
1453 # End recovery-scale functions
1454
1455 # verify that lustre actually cleaned up properly
1456 cleanup_check() {
1457     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
1458         error "LBUG/LASSERT detected"
1459     BUSY=`dmesg | grep -i destruct || true`
1460     if [ "$BUSY" ]; then
1461         echo "$BUSY" 1>&2
1462         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
1463         exit 205
1464     fi
1465
1466     check_mem_leak || exit 204
1467
1468     [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl && \
1469         echo "$0: lustre didn't clean up..." 1>&2 && return 202 || true
1470
1471     if module_loaded lnet || module_loaded libcfs; then
1472         echo "$0: modules still loaded..." 1>&2
1473         /sbin/lsmod 1>&2
1474         return 203
1475     fi
1476     return 0
1477 }
1478
1479 wait_update () {
1480     local node=$1
1481     local TEST=$2
1482     local FINAL=$3
1483     local MAX=${4:-90}
1484
1485         local RESULT
1486         local WAIT=0
1487         local sleep=1
1488         local print=10
1489         while [ true ]; do
1490             RESULT=$(do_node $node "$TEST")
1491             if [ "$RESULT" == "$FINAL" ]; then
1492                 [ -z "$RESULT" -o $WAIT -le $sleep ] ||
1493                     echo "Updated after ${WAIT}s: wanted '$FINAL' got '$RESULT'"
1494                 return 0
1495             fi
1496             [ $WAIT -ge $MAX ] && break
1497             [ $((WAIT % print)) -eq 0 ] &&
1498                 echo "Waiting $((MAX - WAIT)) secs for update"
1499             WAIT=$((WAIT + sleep))
1500             sleep $sleep
1501         done
1502         echo "Update not seen after ${MAX}s: wanted '$FINAL' got '$RESULT'"
1503         return 3
1504 }
1505
1506 wait_update_facet () {
1507     local facet=$1
1508     wait_update  $(facet_active_host $facet) "$@"
1509 }
1510
1511 wait_delete_completed () {
1512     local TOTALPREV=`lctl get_param -n osc.*.kbytesavail | \
1513                      awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1514
1515     local WAIT=0
1516     local MAX_WAIT=20
1517     while [ "$WAIT" -ne "$MAX_WAIT" ]; do
1518         sleep 1
1519         TOTAL=`lctl get_param -n osc.*.kbytesavail | \
1520                awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1521         [ "$TOTAL" -eq "$TOTALPREV" ] && return 0
1522         echo "Waiting delete completed ... prev: $TOTALPREV current: $TOTAL "
1523         TOTALPREV=$TOTAL
1524         WAIT=$(( WAIT + 1))
1525     done
1526     echo "Delete is not completed in $MAX_WAIT sec"
1527     return 1
1528 }
1529
1530 wait_for_host() {
1531     local hostlist=$1
1532
1533     # we can use "for" here because we are waiting the slowest
1534     for host in ${hostlist//,/ }; do
1535         check_network "$host" 900
1536     done
1537     while ! do_nodes $hostlist hostname  > /dev/null; do sleep 5; done
1538 }
1539
1540 wait_for_facet() {
1541     local facetlist=$1
1542     local hostlist
1543
1544     for facet in ${facetlist//,/ }; do
1545         hostlist=$(expand_list $hostlist $(facet_active_host $facet))
1546     done
1547     wait_for_host $hostlist
1548 }
1549
1550 _wait_recovery_complete () {
1551     local param=$1
1552
1553     # Use default policy if $2 is not passed by caller.
1554     local MAX=${2:-$(max_recovery_time)}
1555
1556     local WAIT=0
1557     local STATUS=
1558
1559     while [ $WAIT -lt $MAX ]; do
1560         STATUS=$(lctl get_param -n $param | grep status)
1561         echo $param $STATUS
1562         [[ $STATUS = "status: COMPLETE" || $STATUS = "status: INACTIVE" ]] && return 0
1563         sleep 5
1564         WAIT=$((WAIT + 5))
1565         echo "Waiting $((MAX - WAIT)) secs for $param recovery done. $STATUS"
1566     done
1567     echo "$param recovery not done in $MAX sec. $STATUS"
1568     return 1
1569 }
1570
1571 wait_recovery_complete () {
1572     local facet=$1
1573
1574     # with an assumption that at_max is the same on all nodes
1575     local MAX=${2:-$(max_recovery_time)}
1576
1577     local facets=$facet
1578     if [ "$FAILURE_MODE" = HARD ]; then
1579         facets=$(facets_on_host $(facet_active_host $facet))
1580     fi
1581     echo affected facets: $facets
1582
1583     # we can use "for" here because we are waiting the slowest
1584     for facet in ${facets//,/ }; do
1585         local var_svc=${facet}_svc
1586         local param="*.${!var_svc}.recovery_status"
1587
1588         local host=$(facet_active_host $facet)
1589         do_rpc_nodes $host _wait_recovery_complete $param $MAX
1590     done
1591 }
1592
1593 wait_mds_ost_sync () {
1594     # just because recovery is done doesn't mean we've finished
1595     # orphan cleanup. Wait for llogs to get synchronized.
1596     echo "Waiting for orphan cleanup..."
1597     # MAX value includes time needed for MDS-OST reconnection
1598     local MAX=$(( TIMEOUT * 2 ))
1599     local WAIT=0
1600     while [ $WAIT -lt $MAX ]; do
1601         local -a sync=($(do_nodes $(comma_list $(osts_nodes)) \
1602             "$LCTL get_param -n obdfilter.*.mds_sync"))
1603         local con=1
1604         local i
1605         for ((i=0; i<${#sync[@]}; i++)); do
1606             [ ${sync[$i]} -eq 0 ] && continue
1607             # there is a not finished MDS-OST synchronization
1608             con=0
1609             break;
1610         done
1611         sleep 2 # increase waiting time and cover statfs cache
1612         [ ${con} -eq 1 ] && return 0
1613         echo "Waiting $WAIT secs for $facet mds-ost sync done."
1614         WAIT=$((WAIT + 2))
1615     done
1616     echo "$facet recovery not done in $MAX sec. $STATUS"
1617     return 1
1618 }
1619
1620 wait_destroy_complete () {
1621     echo "Waiting for destroy to be done..."
1622     # MAX value shouldn't be big as this mean server responsiveness
1623     # never increase this just to make test pass but investigate
1624     # why it takes so long time
1625     local MAX=5
1626     local WAIT=0
1627     while [ $WAIT -lt $MAX ]; do
1628         local -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))
1629         local con=1
1630         for ((i=0; i<${#RPCs[@]}; i++)); do
1631             [ ${RPCs[$i]} -eq 0 ] && continue
1632             # there are still some destroy RPCs in flight
1633             con=0
1634             break;
1635         done
1636         sleep 1
1637         [ ${con} -eq 1 ] && return 0 # done waiting
1638         echo "Waiting $WAIT secs for destroys to be done."
1639         WAIT=$((WAIT + 1))
1640     done
1641     echo "Destroys weren't done in $MAX sec."
1642     return 1
1643 }
1644
1645 wait_exit_ST () {
1646     local facet=$1
1647
1648     local WAIT=0
1649     local INTERVAL=1
1650     local running
1651     # conf-sanity 31 takes a long time cleanup
1652     while [ $WAIT -lt 300 ]; do
1653         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
1654         [ -z "${running}" ] && return 0
1655         echo "waited $WAIT for${running}"
1656         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
1657         sleep $INTERVAL
1658         WAIT=$((WAIT + INTERVAL))
1659     done
1660     echo "service didn't stop after $WAIT seconds.  Still running:"
1661     echo ${running}
1662     return 1
1663 }
1664
1665 wait_remote_prog () {
1666    local prog=$1
1667    local WAIT=0
1668    local INTERVAL=5
1669    local rc=0
1670
1671    [ "$PDSH" = "no_dsh" ] && return 0
1672
1673    while [ $WAIT -lt $2 ]; do
1674         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
1675         [ -z "${running}" ] && return 0 || true
1676         echo "waited $WAIT for: "
1677         echo "$running"
1678         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
1679         sleep $INTERVAL
1680         WAIT=$((WAIT + INTERVAL))
1681     done
1682     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
1683     [ -z "$pids" ] && return 0
1684     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
1685     # FIXME: not portable
1686     for pid in $pids; do
1687         cat /proc/${pid}/status || true
1688         cat /proc/${pid}/wchan || true
1689         echo "Killing $pid"
1690         kill -9 $pid || true
1691         sleep 1
1692         ps -P $pid && rc=1
1693     done
1694
1695     return $rc
1696 }
1697
1698 clients_up() {
1699     # not every config has many clients
1700     sleep 1
1701     if [ ! -z "$CLIENTS" ]; then
1702         $PDSH $CLIENTS "stat -f $MOUNT" > /dev/null
1703     else
1704         stat -f $MOUNT > /dev/null
1705     fi
1706 }
1707
1708 client_up() {
1709     local client=$1
1710     # usually checked on particular client or locally
1711     sleep 1
1712     if [ ! -z "$client" ]; then
1713         $PDSH $client "stat -f $MOUNT" > /dev/null
1714     else
1715         stat -f $MOUNT > /dev/null
1716     fi
1717 }
1718
1719 client_evicted() {
1720     ! client_up $1
1721 }
1722
1723 client_reconnect() {
1724     uname -n >> $MOUNT/recon
1725     if [ -z "$CLIENTS" ]; then
1726         df $MOUNT; uname -n >> $MOUNT/recon
1727     else
1728         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
1729     fi
1730     echo Connected clients:
1731     cat $MOUNT/recon
1732     ls -l $MOUNT/recon > /dev/null
1733     rm $MOUNT/recon
1734 }
1735
1736 affected_facets () {
1737     local facet=$1
1738
1739     local host=$(facet_active_host $facet)
1740     local affected=$facet
1741
1742     if [ "$FAILURE_MODE" = HARD ]; then
1743         affected=$(facets_up_on_host $host)
1744     fi
1745     echo $affected
1746 }
1747
1748 facet_failover() {
1749     local facet=$1
1750     local sleep_time=$2
1751     local host=$(facet_active_host $facet)
1752
1753     echo "Failing $facet on node $host"
1754
1755     # Make sure the client data is synced to disk. LU-924
1756     #
1757     # We don't write client data synchrnously (to avoid flooding sync writes
1758     # when there are many clients connecting), so if the server reboots before
1759     # the client data reachs disk, the client data will be lost and the client
1760     # will be evicted after recovery, which is not what we expected.
1761     do_facet $facet "sync; sync; sync"
1762
1763     local affected=$(affected_facets $facet)
1764
1765     shutdown_facet $facet
1766
1767     echo affected facets: $affected
1768
1769     [ -n "$sleep_time" ] && sleep $sleep_time
1770
1771     reboot_facet $facet
1772
1773     change_active $affected
1774
1775     wait_for_facet $affected
1776     # start mgs first if it is affected
1777     if ! combined_mgs_mds && list_member $affected mgs; then
1778         mount_facet mgs || error "Restart of mgs failed"
1779     fi
1780     # FIXME; has to be changed to mount all facets concurrently
1781     affected=$(exclude_items_from_list $affected mgs)
1782     mount_facets $affected
1783 }
1784
1785 obd_name() {
1786     local facet=$1
1787 }
1788
1789 replay_barrier() {
1790     local facet=$1
1791     do_facet $facet "sync; sync; sync"
1792     df $MOUNT
1793
1794     # make sure there will be no seq change
1795     local clients=${CLIENTS:-$HOSTNAME}
1796     do_nodes $clients "f=${MOUNT}/fsa-\\\$(hostname); mcreate \\\$f; rm \\\$f"
1797
1798     local svc=${facet}_svc
1799     do_facet $facet $LCTL --device %${!svc} notransno
1800     do_facet $facet $LCTL --device %${!svc} readonly
1801     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1802     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1803 }
1804
1805 replay_barrier_nodf() {
1806     local facet=$1    echo running=${running}
1807     do_facet $facet "sync; sync; sync"
1808     local svc=${facet}_svc
1809     echo Replay barrier on ${!svc}
1810     do_facet $facet $LCTL --device %${!svc} notransno
1811     do_facet $facet $LCTL --device %${!svc} readonly
1812     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1813     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1814 }
1815
1816 replay_barrier_nosync() {
1817     local facet=$1    echo running=${running}
1818     local svc=${facet}_svc
1819     echo Replay barrier on ${!svc}
1820     do_facet $facet $LCTL --device %${!svc} notransno
1821     do_facet $facet $LCTL --device %${!svc} readonly
1822     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1823     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1824 }
1825
1826 mds_evict_client() {
1827     UUID=`lctl get_param -n mdc.${mds1_svc}-mdc-*.uuid`
1828     do_facet mds1 "lctl set_param -n mdt.${mds1_svc}.evict_client $UUID"
1829 }
1830
1831 ost_evict_client() {
1832     UUID=`lctl get_param -n devices| grep ${ost1_svc}-osc- | egrep -v 'MDT' | awk '{print $5}'`
1833     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
1834 }
1835
1836 fail() {
1837     facet_failover $* || error "failover: $?"
1838     clients_up || error "post-failover df: $?"
1839 }
1840
1841 fail_nodf() {
1842         local facet=$1
1843         facet_failover $facet
1844 }
1845
1846 fail_abort() {
1847     local facet=$1
1848     stop $facet
1849     change_active $facet
1850     wait_for_facet $facet
1851     mount_facet $facet -o abort_recovery
1852     clients_up || echo "first df failed: $?"
1853     clients_up || error "post-failover df: $?"
1854 }
1855
1856 do_lmc() {
1857     echo There is no lmc.  This is mountconf, baby.
1858     exit 1
1859 }
1860
1861 host_nids_address() {
1862     local nodes=$1
1863     local kind=$2
1864
1865     if [ -n "$kind" ]; then
1866         nids=$(do_nodes $nodes "$LCTL list_nids | grep $kind | cut -f 1 -d '@'")
1867     else
1868         nids=$(do_nodes $nodes "$LCTL list_nids all | cut -f 1 -d '@'")
1869     fi
1870     echo $nids
1871 }
1872
1873 h2name_or_ip() {
1874     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1875         echo $1"@$2"
1876     fi
1877 }
1878
1879 h2ptl() {
1880    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1881        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
1882        if [ -z "$ID" ]; then
1883            echo "Could not get a ptl id for $1..."
1884            exit 1
1885        fi
1886        echo $ID"@ptl"
1887    fi
1888 }
1889 declare -fx h2ptl
1890
1891 h2tcp() {
1892     h2name_or_ip "$1" "tcp"
1893 }
1894 declare -fx h2tcp
1895
1896 h2elan() {
1897     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1898         if type __h2elan >/dev/null 2>&1; then
1899             ID=$(__h2elan $1)
1900         else
1901             ID=`echo $1 | sed 's/[^0-9]*//g'`
1902         fi
1903         echo $ID"@elan"
1904     fi
1905 }
1906 declare -fx h2elan
1907
1908 h2o2ib() {
1909     h2name_or_ip "$1" "o2ib"
1910 }
1911 declare -fx h2o2ib
1912
1913 # This enables variables in cfg/"setup".sh files to support the pdsh HOSTLIST
1914 # expressions format. As a bonus we can then just pass in those variables
1915 # to pdsh. What this function does is take a HOSTLIST type string and
1916 # expand it into a space deliminated list for us.
1917 hostlist_expand() {
1918     local hostlist=$1
1919     local offset=$2
1920     local myList
1921     local item
1922     local list
1923
1924     [ -z "$hostlist" ] && return
1925
1926     # Translate the case of [..],..,[..] to [..] .. [..]
1927     list="${hostlist/],/] }"
1928     front=${list%%[*}
1929     [[ "$front" == *,* ]] && {
1930         new="${list%,*} "
1931         old="${list%,*},"
1932         list=${list/${old}/${new}}
1933     }
1934
1935     for item in $list; do
1936         # Test if we have any []'s at all
1937         if [ "$item" != "${item/\[/}" ]; then {
1938             # Expand the [*] into list
1939             name=${item%%[*}
1940             back=${item#*]}
1941
1942             if [ "$name" != "$item" ]; then
1943                 group=${item#$name[*}
1944                 group=${group%%]*}
1945
1946                 for range in ${group//,/ }; do
1947                     begin=${range%-*}
1948                     end=${range#*-}
1949
1950                     # Number of leading zeros
1951                     padlen=${#begin}
1952                     padlen2=${#end}
1953                     end=$(echo $end | sed 's/0*//')
1954                     [[ -z "$end" ]] && end=0
1955                     [[ $padlen2 -gt $padlen ]] && {
1956                         [[ $padlen2 -eq ${#end} ]] && padlen2=0
1957                         padlen=$padlen2
1958                     }
1959                     begin=$(echo $begin | sed 's/0*//')
1960                     [ -z $begin ] && begin=0
1961
1962                     for num in $(seq -f "%0${padlen}g" $begin $end); do
1963                         value="${name#*,}${num}${back}"
1964                         [ "$value" != "${value/\[/}" ] && {
1965                             value=$(hostlist_expand "$value")
1966                         }
1967                         myList="$myList $value"
1968                     done
1969                 done
1970             fi
1971         } else {
1972             myList="$myList $item"
1973         } fi
1974     done
1975     myList=${myList//,/ }
1976     myList=${myList:1} # Remove first character which is a space
1977
1978     # Filter any duplicates without sorting
1979     list="$myList "
1980     myList="${list%% *}"
1981
1982     while [[ "$list" != ${myList##* } ]]; do
1983         list=${list//${list%% *} /}
1984         myList="$myList ${list%% *}"
1985     done
1986     myList="${myList%* }";
1987
1988     # We can select an object at a offset in the list
1989     [ $# -eq 2 ] && {
1990         cnt=0
1991         for item in $myList; do
1992             let cnt=cnt+1
1993             [ $cnt -eq $offset ] && {
1994                 myList=$item
1995             }
1996         done
1997         [ $(get_node_count $myList) -ne 1 ] && myList=""
1998     }
1999     echo $myList
2000 }
2001
2002 facet_host() {
2003     local facet=$1
2004
2005     [ "$facet" == client ] && echo -n $HOSTNAME && return
2006     varname=${facet}_HOST
2007     if [ -z "${!varname}" ]; then
2008         if [ "${facet:0:3}" == "ost" ]; then
2009             eval ${facet}_HOST=${ost_HOST}
2010         fi
2011     fi
2012     echo -n ${!varname}
2013 }
2014
2015 facet_failover_host() {
2016         local facet=$1
2017         local var
2018
2019         var=${facet}failover_HOST
2020         if [ -n "${!var}" ]; then
2021                 echo ${!var}
2022                 return
2023         fi
2024
2025         if [[ $facet == ost* ]]; then
2026                 var=ostfailover_HOST
2027                 if [ -n "${!var}" ]; then
2028                         echo ${!var}
2029                         return
2030                 fi
2031         fi
2032 }
2033
2034 facet_active() {
2035     local facet=$1
2036     local activevar=${facet}active
2037
2038     if [ -f $TMP/${facet}active ] ; then
2039         source $TMP/${facet}active
2040     fi
2041
2042     active=${!activevar}
2043     if [ -z "$active" ] ; then
2044         echo -n ${facet}
2045     else
2046         echo -n ${active}
2047     fi
2048 }
2049
2050 facet_active_host() {
2051     local facet=$1
2052     local active=`facet_active $facet`
2053     if [ "$facet" == client ]; then
2054         echo $HOSTNAME
2055     else
2056         echo `facet_host $active`
2057     fi
2058 }
2059
2060 change_active() {
2061     local facetlist=$1
2062     local facet
2063
2064     facetlist=$(exclude_items_from_list $facetlist mgs)
2065
2066     for facet in ${facetlist//,/ }; do
2067     local failover=${facet}failover
2068     local host=`facet_host $failover`
2069     [ -z "$host" ] && return
2070
2071     local curactive=`facet_active $facet`
2072     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
2073         eval export ${facet}active=$facet
2074     else
2075         eval export ${facet}active=$failover
2076     fi
2077     # save the active host for this facet
2078     local activevar=${facet}active
2079     echo "$activevar=${!activevar}" > $TMP/$activevar
2080     [[ $facet = mds1 ]] && combined_mgs_mds && \
2081         echo "mgsactive=${!activevar}" > $TMP/mgsactive
2082     local TO=`facet_active_host $facet`
2083     echo "Failover $facet to $TO"
2084     done
2085 }
2086
2087 do_node() {
2088     local verbose=false
2089     # do not stripe off hostname if verbose, bug 19215
2090     if [ x$1 = x--verbose ]; then
2091         shift
2092         verbose=true
2093     fi
2094
2095     local HOST=$1
2096     shift
2097     local myPDSH=$PDSH
2098     if [ "$HOST" = "$HOSTNAME" ]; then
2099         myPDSH="no_dsh"
2100     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
2101         echo "cannot run remote command on $HOST with $myPDSH"
2102         return 128
2103     fi
2104     if $VERBOSE; then
2105         echo "CMD: $HOST $@" >&2
2106         $myPDSH $HOST "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
2107     fi
2108
2109     if [ "$myPDSH" = "rsh" ]; then
2110 # we need this because rsh does not return exit code of an executed command
2111         local command_status="$TMP/cs"
2112         rsh $HOST ":> $command_status"
2113         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
2114                     cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
2115                     echo command failed >$command_status"
2116         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
2117         return 0
2118     fi
2119
2120     if $verbose ; then
2121         # print HOSTNAME for myPDSH="no_dsh"
2122         if [[ $myPDSH = no_dsh ]]; then
2123             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
2124         else
2125             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
2126         fi
2127     else
2128         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
2129     fi
2130     return ${PIPESTATUS[0]}
2131 }
2132
2133 do_nodev() {
2134     do_node --verbose "$@"
2135 }
2136
2137 single_local_node () {
2138    [ "$1" = "$HOSTNAME" ]
2139 }
2140
2141 # Outputs environment variable assignments that should be passed to remote nodes
2142 get_env_vars() {
2143         local var
2144         local value
2145
2146         for var in ${!MODOPTS_*}; do
2147                 value=${!var}
2148                 echo -n " ${var}=\"$value\""
2149         done
2150
2151         echo -n " USE_OFD=$USE_OFD"
2152 }
2153
2154 do_nodes() {
2155     local verbose=false
2156     # do not stripe off hostname if verbose, bug 19215
2157     if [ x$1 = x--verbose ]; then
2158         shift
2159         verbose=true
2160     fi
2161
2162     local rnodes=$1
2163     shift
2164
2165     if single_local_node $rnodes; then
2166         if $verbose; then
2167            do_nodev $rnodes "$@"
2168         else
2169            do_node $rnodes "$@"
2170         fi
2171         return $?
2172     fi
2173
2174     # This is part from do_node
2175     local myPDSH=$PDSH
2176
2177     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
2178         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
2179
2180     export FANOUT=$(get_node_count "${rnodes//,/ }")
2181     if $VERBOSE; then
2182         echo "CMD: $rnodes $@" >&2
2183         $myPDSH $rnodes "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
2184     fi
2185
2186     # do not replace anything from pdsh output if -N is used
2187     # -N     Disable hostname: prefix on lines of output.
2188     if $verbose || [[ $myPDSH = *-N* ]]; then
2189         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")"
2190     else
2191         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")" | sed -re "s/^[^:]*: //g"
2192     fi
2193     return ${PIPESTATUS[0]}
2194 }
2195
2196 do_facet() {
2197     local facet=$1
2198     shift
2199     local HOST=`facet_active_host $facet`
2200     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
2201     do_node $HOST "$@"
2202 }
2203
2204 do_nodesv() {
2205     do_nodes --verbose "$@"
2206 }
2207
2208 add() {
2209     local facet=$1
2210     shift
2211     # make sure its not already running
2212     stop ${facet} -f
2213     rm -f $TMP/${facet}active
2214     [[ $facet = mds1 ]] && combined_mgs_mds && rm -f $TMP/mgsactive
2215     do_facet ${facet} $MKFS $*
2216 }
2217
2218 ostdevname() {
2219     num=$1
2220     DEVNAME=OSTDEV$num
2221
2222         local fstype=$(facet_fstype ost$num)
2223
2224         case $fstype in
2225                 ldiskfs )
2226                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
2227                         eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
2228                 zfs )
2229                         #dataset name is independent of vdev device names
2230                         eval DEVPTR=${FSNAME}-ost${num}/ost${num};;
2231                 * )
2232                         error "unknown fstype!";;
2233         esac
2234
2235     echo -n $DEVPTR
2236 }
2237
2238 ostvdevname() {
2239         num=$1
2240         DEVNAME=OSTDEV$num
2241
2242         local fstype=$(facet_fstype ost$num)
2243
2244         case $fstype in
2245                 ldiskfs )
2246                         # vdevs are not supported by ldiskfs
2247                         eval VDEVPTR="";;
2248                 zfs )
2249                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
2250                         eval VDEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
2251                 * )
2252                         error "unknown fstype!";;
2253         esac
2254
2255         echo -n $VDEVPTR
2256 }
2257
2258 mdsdevname() {
2259     num=$1
2260     DEVNAME=MDSDEV$num
2261
2262         local fstype=$(facet_fstype mds$num)
2263
2264         case $fstype in
2265                 ldiskfs )
2266                         #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
2267                         eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
2268                 zfs )
2269                         #dataset name is independent of vdev device names
2270                         eval DEVPTR=${FSNAME}-mdt${num}/mdt${num};;
2271                 * )
2272                         error "unknown fstype!";;
2273         esac
2274
2275         echo -n $DEVPTR
2276 }
2277
2278 mdsvdevname() {
2279         num=$1
2280         DEVNAME=MDSDEV$num
2281
2282         local fstype=$(facet_fstype mds$num)
2283
2284         case $fstype in
2285                 ldiskfs )
2286                         # vdevs are not supported by ldiskfs
2287                         eval VDEVPTR="";;
2288                 zfs )
2289                         #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
2290                         eval VDEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
2291                 * )
2292                         error "unknown fstype!";;
2293         esac
2294
2295         echo -n $VDEVPTR
2296 }
2297
2298 mgsdevname() {
2299         DEVNAME=MGSDEV
2300
2301         local fstype=$(facet_fstype mds$num)
2302
2303         case $fstype in
2304                 ldiskfs )
2305                         #if $MGSDEV isn't defined, default is $MDSDEV1
2306                         eval DEVPTR=${!DEVNAME:=${MDSDEV1}};;
2307                 zfs )
2308                         #dataset name is independent of vdev device names
2309                         eval DEVPTR=${FSNAME}-mgs/mgs;;
2310                 * )
2311                         error "unknown fstype!";;
2312         esac
2313
2314     echo -n $DEVPTR
2315 }
2316
2317 mgsvdevname() {
2318         DEVNAME=MGSDEV
2319
2320         local fstype=$(facet_fstype mds$num)
2321
2322         case $fstype in
2323                 ldiskfs )
2324                         # vdevs are not supported by ldiskfs
2325                         eval VDEVPTR="";;
2326                 zfs )
2327                         #if $MGSDEV isn't defined, default is $MGSDEV1
2328                         eval VDEVPTR=${!DEVNAME:=${MDSDEV1}};;
2329                 * )
2330                         error "unknown fstype!";;
2331         esac
2332
2333         echo -n $VDEVPTR
2334 }
2335
2336 facet_mntpt () {
2337     local facet=$1
2338     [[ $facet = mgs ]] && combined_mgs_mds && facet="mds1"
2339
2340     local var=${facet}_MOUNT
2341     eval mntpt=${!var:-${MOUNT%/*}/$facet}
2342
2343     echo -n $mntpt
2344 }
2345
2346 ########
2347 ## MountConf setup
2348
2349 stopall() {
2350     # make sure we are using the primary server, so test-framework will
2351     # be able to clean up properly.
2352     activemds=`facet_active mds1`
2353     if [ $activemds != "mds1" ]; then
2354         fail mds1
2355     fi
2356
2357     local clients=$CLIENTS
2358     [ -z $clients ] && clients=$(hostname)
2359
2360     zconf_umount_clients $clients $MOUNT "$*" || true
2361     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
2362
2363     [ "$CLIENTONLY" ] && return
2364     # The add fn does rm ${facet}active file, this would be enough
2365     # if we use do_facet <facet> only after the facet added, but
2366     # currently we use do_facet mds in local.sh
2367     for num in `seq $MDSCOUNT`; do
2368         stop mds$num -f
2369         rm -f ${TMP}/mds${num}active
2370     done
2371     combined_mgs_mds && rm -f $TMP/mgsactive
2372
2373     for num in `seq $OSTCOUNT`; do
2374         stop ost$num -f
2375         rm -f $TMP/ost${num}active
2376     done
2377
2378     if ! combined_mgs_mds ; then
2379         stop mgs
2380     fi
2381
2382     return 0
2383 }
2384
2385 cleanup_echo_devs () {
2386     local devs=$($LCTL dl | grep echo | awk '{print $4}')
2387
2388     for dev in $devs; do
2389         $LCTL --device $dev cleanup
2390         $LCTL --device $dev detach
2391     done
2392 }
2393
2394 cleanupall() {
2395     nfs_client_mode && return
2396
2397     stopall $*
2398     cleanup_echo_devs
2399
2400     unload_modules
2401     cleanup_gss
2402 }
2403
2404 combined_mgs_mds () {
2405     [[ $MDSDEV1 = $MGSDEV ]] && [[ $mds1_HOST = $mgs_HOST ]]
2406 }
2407
2408 lower() {
2409         echo -n "$1" | tr '[:upper:]' '[:lower:]'
2410 }
2411
2412 upper() {
2413         echo -n "$1" | tr '[:lower:]' '[:upper:]'
2414 }
2415
2416 mkfs_opts() {
2417         local facet=$1
2418         local type=$(facet_type $facet)
2419         local index=$(($(facet_number $facet) - 1))
2420         local fstype=$(facet_fstype $facet)
2421         local opts
2422         local fs_mkfs_opts
2423         local var
2424
2425         if [ $type == MGS ] && combined_mgs_mds; then
2426                 return 1
2427         fi
2428
2429         if [ $type == MGS ] || ( [ $type == MDS ] && combined_mgs_mds ); then
2430                 opts="--mgs"
2431         else
2432                 opts="--mgsnode=$MGSNID"
2433         fi
2434
2435         if [ $type != MGS ]; then
2436                 opts+=" --fsname=$FSNAME --$(lower ${type/MDS/MDT}) --index=$index"
2437         fi
2438
2439         var=${facet}failover_HOST
2440         if [ -n "${!var}" ] && [ ${!var} != $(facet_host $facet) ]; then
2441                 opts+=" --failnode=$(h2$NETTYPE ${!var})"
2442         fi
2443
2444         opts+=${TIMEOUT:+" --param=sys.timeout=$TIMEOUT"}
2445         opts+=${LDLM_TIMEOUT:+" --param=sys.ldlm_timeout=$LDLM_TIMEOUT"}
2446
2447         if [ $type == MDS ]; then
2448                 opts+=${SECLEVEL:+" --param=mdt.sec_level"}
2449                 opts+=${MDSCAPA:+" --param-mdt.capa=$MDSCAPA"}
2450                 opts+=${STRIPE_BYTES:+" --param=lov.stripesize=$STRIPE_BYTES"}
2451                 opts+=${STRIPES_PER_OBJ:+" --param=lov.stripecount=$STRIPES_PER_OBJ"}
2452                 opts+=${L_GETIDENTITY:+" --param=mdt.identity_upcall=$L_GETIDENTITY"}
2453
2454                 if [ $fstype == ldiskfs ]; then
2455                         opts+=${IAMDIR:+" --iam-dir"}
2456
2457                         fs_mkfs_opts+=${MDSJOURNALSIZE:+" -J size=$MDSJOURNALSIZE"}
2458                         fs_mkfs_opts+=${MDSISIZE:+" -i $MDSISIZE"}
2459                 fi
2460         fi
2461
2462         if [ $type == OST ]; then
2463                 opts+=${SECLEVEL:+" --param=ost.sec_level"}
2464                 opts+=${OSSCAPA:+" --param=ost.capa=$OSSCAPA"}
2465
2466                 if [ $fstype == ldiskfs ]; then
2467                         fs_mkfs_opts+=${OSTJOURNALSIZE:+" -J size=$OSTJOURNALSIZE"}
2468                 fi
2469         fi
2470
2471         opts+=" --backfstype=$fstype"
2472
2473         var=${type}SIZE
2474         if [ -n "${!var}" ]; then
2475                 opts+=" --device-size=${!var}"
2476         fi
2477
2478         var=$(upper $fstype)_MKFS_OPTS
2479         fs_mkfs_opts+=${!var:+" ${!var}"}
2480
2481         var=${type}_FS_MKFS_OPTS
2482         fs_mkfs_opts+=${!var:+" ${!var}"}
2483
2484         if [ -n "${fs_mkfs_opts## }" ]; then
2485                 opts+=" --mkfsoptions=\\\"${fs_mkfs_opts## }\\\""
2486         fi
2487
2488         var=${type}OPT
2489         opts+=${!var:+" ${!var}"}
2490
2491         echo -n "$opts"
2492 }
2493
2494 formatall() {
2495         local quiet
2496
2497         if ! $VERBOSE; then
2498                 quiet=yes
2499         fi
2500
2501         stopall
2502         # We need ldiskfs here, may as well load them all
2503         load_modules
2504         [ "$CLIENTONLY" ] && return
2505         echo Formatting mgs, mds, osts
2506         if ! combined_mgs_mds ; then
2507                 echo "Format mgs: $(mgsdevname)"
2508                 add mgs $(mkfs_opts mgs) --reformat $(mgsdevname) \
2509                         $(mgsvdevname) ${quiet:+>/dev/null} || exit 10
2510                 fi
2511
2512                 for num in `seq $MDSCOUNT`; do
2513                         echo "Format mds$num: $(mdsdevname $num)"
2514                         add mds$num $(mkfs_opts mds$num) --reformat \
2515                         $(mdsdevname $num) $(mdsvdevname $num) \
2516                         ${quiet:+>/dev/null} || exit 10
2517                 done
2518
2519                 for num in `seq $OSTCOUNT`; do
2520                         echo "Format ost$num: $(ostdevname $num)"
2521                         add ost$num $(mkfs_opts ost$num) --reformat \
2522                         $(ostdevname $num) $(ostvdevname ${num}) \
2523                         ${quiet:+>/dev/null} || exit 10
2524                 done
2525 }
2526
2527 mount_client() {
2528     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
2529 }
2530
2531 umount_client() {
2532     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
2533 }
2534
2535 # return value:
2536 # 0: success, the old identity set already.
2537 # 1: success, the old identity does not set.
2538 # 2: fail.
2539 switch_identity() {
2540     local num=$1
2541     local switch=$2
2542     local j=`expr $num - 1`
2543     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
2544
2545     if [ -z "$MDT" ]; then
2546         return 2
2547     fi
2548
2549     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
2550
2551     if $switch; then
2552         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
2553     else
2554         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
2555     fi
2556
2557     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush=-1"
2558
2559     if [ $old = "NONE" ]; then
2560         return 1
2561     else
2562         return 0
2563     fi
2564 }
2565
2566 remount_client()
2567 {
2568         zconf_umount `hostname` $1 || error "umount failed"
2569         zconf_mount `hostname` $1 || error "mount failed"
2570 }
2571
2572 writeconf_facet () {
2573     local facet=$1
2574     local dev=$2
2575
2576     do_facet $facet "$TUNEFS --writeconf $dev"
2577 }
2578
2579 writeconf_all () {
2580     for num in `seq $MDSCOUNT`; do
2581         DEVNAME=$(mdsdevname $num)
2582         writeconf_facet mds$num $DEVNAME
2583     done
2584
2585     for num in `seq $OSTCOUNT`; do
2586         DEVNAME=$(ostdevname $num)
2587         writeconf_facet ost$num $DEVNAME
2588     done
2589 }
2590
2591 setupall() {
2592     nfs_client_mode && return
2593
2594     sanity_mount_check ||
2595         error "environments are insane!"
2596
2597     load_modules
2598
2599     if [ -z "$CLIENTONLY" ]; then
2600         echo Setup mgs, mdt, osts
2601         echo $WRITECONF | grep -q "writeconf" && \
2602             writeconf_all
2603         if ! combined_mgs_mds ; then
2604                         start mgs $(mgsdevname) $MGS_MOUNT_OPTS
2605         fi
2606
2607         for num in `seq $MDSCOUNT`; do
2608             DEVNAME=$(mdsdevname $num)
2609             start mds$num $DEVNAME $MDS_MOUNT_OPTS
2610
2611             # We started mds, now we should set failover variables properly.
2612             # Set mds${num}failover_HOST if it is not set (the default failnode).
2613             local varname=mds${num}failover_HOST
2614             if [ -z "${!varname}" ]; then
2615                 eval mds${num}failover_HOST=$(facet_host mds$num)
2616             fi
2617
2618             if [ $IDENTITY_UPCALL != "default" ]; then
2619                 switch_identity $num $IDENTITY_UPCALL
2620             fi
2621         done
2622         for num in `seq $OSTCOUNT`; do
2623             DEVNAME=$(ostdevname $num)
2624             start ost$num $DEVNAME $OST_MOUNT_OPTS
2625
2626             # We started ost$num, now we should set ost${num}failover variable properly.
2627             # Set ost${num}failover_HOST if it is not set (the default failnode).
2628             varname=ost${num}failover_HOST
2629             if [ -z "${!varname}" ]; then
2630                 eval ost${num}failover_HOST=$(facet_host ost${num})
2631             fi
2632
2633         done
2634     fi
2635
2636     init_gss
2637
2638     # wait a while to allow sptlrpc configuration be propogated to targets,
2639     # only needed when mounting new target devices.
2640     if $GSS; then
2641         sleep 10
2642     fi
2643
2644     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
2645     mount_client $MOUNT
2646     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
2647     clients_up
2648
2649     if [ "$MOUNT_2" ]; then
2650         mount_client $MOUNT2
2651         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
2652     fi
2653
2654     init_param_vars
2655
2656     # by remounting mdt before ost, initial connect from mdt to ost might
2657     # timeout because ost is not ready yet. wait some time to its fully
2658     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
2659     # by a context negotiation rpc with $TIMEOUT.
2660     # FIXME better by monitoring import status.
2661     if $GSS; then
2662         set_flavor_all $SEC
2663         sleep $((TIMEOUT + 5))
2664     else
2665         sleep 5
2666     fi
2667 }
2668
2669 mounted_lustre_filesystems() {
2670         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
2671 }
2672
2673 init_facet_vars () {
2674     [ "$CLIENTONLY" ] && return 0
2675     local facet=$1
2676     shift
2677     local device=$1
2678
2679     shift
2680
2681     eval export ${facet}_dev=${device}
2682     eval export ${facet}_opt=\"$@\"
2683
2684     local dev=${facet}_dev
2685         local label=$(devicelabel ${facet} ${!dev})
2686     [ -z "$label" ] && echo no label for ${!dev} && exit 1
2687
2688     eval export ${facet}_svc=${label}
2689
2690     local varname=${facet}failover_HOST
2691     if [ -z "${!varname}" ]; then
2692        eval $varname=$(facet_host $facet) 
2693     fi
2694
2695     # ${facet}failover_dev is set in cfg file
2696     varname=${facet}failover_dev
2697     if [ -n "${!varname}" ] ; then
2698         eval export ${facet}failover_dev=${!varname}
2699     else
2700         eval export ${facet}failover_dev=$device
2701     fi
2702
2703     # get mount point of already mounted device
2704     # is facet_dev is already mounted then use the real
2705     #  mount point of this facet; otherwise use $(facet_mntpt $facet)
2706     # i.e. ${facet}_MOUNT if specified by user or default
2707     local mntpt=$(do_facet ${facet} cat /proc/mounts | \
2708             awk '"'${!dev}'" == $1 && $3 == "lustre" { print $2 }')
2709     if [ -z $mntpt ]; then
2710         mntpt=$(facet_mntpt $facet)
2711     fi
2712     eval export ${facet}_MOUNT=$mntpt
2713 }
2714
2715 init_facets_vars () {
2716     local DEVNAME
2717
2718     if ! remote_mds_nodsh; then 
2719         for num in `seq $MDSCOUNT`; do
2720             DEVNAME=`mdsdevname $num`
2721             init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
2722         done
2723     fi
2724
2725         combined_mgs_mds || init_facet_vars mgs $(mgsdevname) $MGS_MOUNT_OPTS
2726
2727     remote_ost_nodsh && return
2728
2729     for num in `seq $OSTCOUNT`; do
2730         DEVNAME=`ostdevname $num`
2731         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
2732     done
2733 }
2734
2735 osc_ensure_active () {
2736     local facet=$1
2737     local timeout=$2
2738     local period=0
2739
2740     while [ $period -lt $timeout ]; do
2741         count=$(do_facet $facet "lctl dl | grep ' IN osc ' 2>/dev/null | wc -l")
2742         if [ $count -eq 0 ]; then
2743             break
2744         fi
2745
2746         echo "There are $count OST are inactive, wait $period seconds, and try again"
2747         sleep 3
2748         period=$((period+3))
2749     done
2750
2751     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
2752 }
2753
2754 init_param_vars () {
2755     remote_mds_nodsh ||
2756         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
2757
2758     log "Using TIMEOUT=$TIMEOUT"
2759
2760     osc_ensure_active $SINGLEMDS $TIMEOUT
2761     osc_ensure_active client $TIMEOUT
2762
2763         if [ $QUOTA_AUTO -ne 0 ]; then
2764         if [ "$ENABLE_QUOTA" ]; then
2765             echo "enable quota as required"
2766             setup_quota $MOUNT || return 2
2767         else
2768             echo "disable quota as required"
2769             $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
2770         fi
2771     fi
2772
2773     return 0
2774 }
2775
2776 nfs_client_mode () {
2777     if [ "$NFSCLIENT" ]; then
2778         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
2779         local clients=$CLIENTS
2780         [ -z $clients ] && clients=$(hostname)
2781
2782         # FIXME: remove hostname when 19215 fixed
2783         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
2784         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
2785         if [[ ${#nfsexport[@]} -eq 0 ]]; then
2786                 error_exit NFSCLIENT=$NFSCLIENT mode, but no NFS export found!
2787         fi
2788         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
2789         return
2790     fi
2791     return 1
2792 }
2793
2794 check_config_client () {
2795     local mntpt=$1
2796
2797     local mounted=$(mount | grep " $mntpt ")
2798     if [ "$CLIENTONLY" ]; then
2799         # bug 18021
2800         # CLIENTONLY should not depend on *_HOST settings
2801         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
2802         # in theory someone could create a new,
2803         # client-only config file that assumed lustre was already
2804         # configured and didn't set the MGSNID. If MGSNID is not set,
2805         # then we should use the mgs nid currently being used 
2806         # as the default value. bug 18021
2807         [[ x$MGSNID = x ]] &&
2808             MGSNID=${mgc//MGC/}
2809
2810         if [[ x$mgc != xMGC$MGSNID ]]; then
2811             if [ "$mgs_HOST" ]; then
2812                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
2813 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
2814 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
2815             fi
2816         fi
2817         return 0
2818     fi
2819
2820     local myMGS_host=$mgs_HOST   
2821     if [ "$NETTYPE" = "ptl" ]; then
2822         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
2823     fi
2824
2825     echo Checking config lustre mounted on $mntpt
2826     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
2827     mgshost=$(echo $mgshost | awk -F: '{print $1}')
2828
2829 #    if [ "$mgshost" != "$myMGS_host" ]; then
2830 #            log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
2831 #                   Please use correct config or set mds_HOST correctly!"
2832 #    fi
2833
2834 }
2835
2836 check_config_clients () {
2837     local clients=${CLIENTS:-$HOSTNAME}
2838     local mntpt=$1
2839
2840     nfs_client_mode && return
2841
2842     do_rpc_nodes $clients check_config_client $mntpt
2843
2844     sanity_mount_check ||
2845         error "environments are insane!"
2846 }
2847
2848 check_timeout () {
2849     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
2850     local cltimeout=$(lctl get_param -n timeout)
2851     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
2852         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
2853         return 1
2854     fi
2855 }
2856
2857 is_mounted () {
2858     local mntpt=$1
2859     [ -z $mntpt ] && return 1
2860     local mounted=$(mounted_lustre_filesystems)
2861
2862     echo $mounted' ' | grep -w -q $mntpt' '
2863 }
2864
2865 is_empty_dir() {
2866     [ $(find $1 -maxdepth 1 -print | wc -l) = 1 ] && return 0
2867     return 1
2868 }
2869
2870 # empty lustre filesystem may have empty directories lost+found and .lustre
2871 is_empty_fs() {
2872     [ $(find $1 -maxdepth 1 -name lost+found -o -name .lustre -prune -o \
2873        -print | wc -l) = 1 ] || return 1
2874     [ ! -d $1/lost+found ] || is_empty_dir $1/lost+found && return 0
2875     [ ! -d $1/.lustre ] || is_empty_dir $1/.lustre && return 0
2876     return 1
2877 }
2878
2879 check_and_setup_lustre() {
2880     nfs_client_mode && return
2881
2882     local MOUNTED=$(mounted_lustre_filesystems)
2883
2884     local do_check=true
2885     # 1.
2886     # both MOUNT and MOUNT2 are not mounted
2887     if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
2888         [ "$REFORMAT" ] && formatall
2889         # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
2890         setupall
2891         is_mounted $MOUNT || error "NAME=$NAME not mounted"
2892         export I_MOUNTED=yes
2893         do_check=false
2894     # 2.
2895     # MOUNT2 is mounted
2896     elif is_mounted $MOUNT2; then
2897             # 3.
2898             # MOUNT2 is mounted, while MOUNT_2 is not set
2899             if ! [ "$MOUNT_2" ]; then
2900                 cleanup_mount $MOUNT2
2901                 export I_UMOUNTED2=yes
2902
2903             # 4.
2904             # MOUNT2 is mounted, MOUNT_2 is set
2905             else
2906                 # FIXME: what to do if check_config failed?
2907                 # i.e. if:
2908                 # 1) remote client has mounted other Lustre fs ?
2909                 # 2) it has insane env ?
2910                 # let's try umount MOUNT2 on all clients and mount it again:
2911                 if ! check_config_clients $MOUNT2; then
2912                     cleanup_mount $MOUNT2
2913                     restore_mount $MOUNT2
2914                     export I_MOUNTED2=yes
2915                 fi
2916             fi 
2917
2918     # 5.
2919     # MOUNT is mounted MOUNT2 is not mounted
2920     elif [ "$MOUNT_2" ]; then
2921         restore_mount $MOUNT2
2922         export I_MOUNTED2=yes
2923     fi
2924
2925     if $do_check; then
2926         # FIXME: what to do if check_config failed?
2927         # i.e. if:
2928         # 1) remote client has mounted other Lustre fs?
2929         # 2) lustre is mounted on remote_clients atall ?
2930         check_config_clients $MOUNT
2931         init_facets_vars
2932         init_param_vars
2933
2934         set_default_debug_nodes $(comma_list $(nodes_list))
2935     fi
2936
2937         init_gss
2938         if $GSS; then
2939                 set_flavor_all $SEC
2940         fi
2941
2942         if [ "$ONLY" == "setup" ]; then
2943                 exit 0
2944         fi
2945 }
2946
2947 restore_mount () {
2948    local clients=${CLIENTS:-$HOSTNAME}
2949    local mntpt=$1
2950
2951    zconf_mount_clients $clients $mntpt
2952 }
2953
2954 cleanup_mount () {
2955     local clients=${CLIENTS:-$HOSTNAME}
2956     local mntpt=$1
2957
2958     zconf_umount_clients $clients $mntpt    
2959 }
2960
2961 cleanup_and_setup_lustre() {
2962     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
2963         lctl set_param debug=0 || true
2964         cleanupall
2965         if [ "$ONLY" == "cleanup" ]; then
2966             exit 0
2967         fi
2968     fi
2969     check_and_setup_lustre
2970 }
2971
2972 # Get all of the server target devices from a given server node and type.
2973 get_mnt_devs() {
2974     local node=$1
2975     local type=$2
2976     local obd_type
2977     local devs
2978     local dev
2979
2980     case $type in
2981     mdt) obd_type="osd" ;;
2982     ost) obd_type="obdfilter" ;; # needs to be fixed when OST also uses an OSD
2983     *) echo "invalid server type" && return 1 ;;
2984     esac
2985
2986     devs=$(do_node $node "lctl get_param -n $obd_type*.*.mntdev")
2987     for dev in $devs; do
2988         case $dev in
2989         *loop*) do_node $node "losetup $dev" | \
2990                 sed -e "s/.*(//" -e "s/).*//" ;;
2991         *) echo $dev ;;
2992         esac
2993     done
2994 }
2995
2996 # Get all of the server target devices.
2997 get_svr_devs() {
2998     local i
2999
3000     # MDT device
3001     MDTDEV=$(get_mnt_devs $(mdts_nodes) mdt)
3002
3003     # OST devices
3004     i=0
3005     for node in $(osts_nodes); do
3006         OSTDEVS[i]=$(get_mnt_devs $node ost)
3007         i=$((i + 1))
3008     done
3009 }
3010
3011 # Run e2fsck on MDT or OST device.
3012 run_e2fsck() {
3013     local node=$1
3014     local target_dev=$2
3015     local extra_opts=$3
3016
3017     df > /dev/null      # update statfs data on disk
3018     local cmd="$E2FSCK -d -v -t -t -f -n $extra_opts $target_dev"
3019     echo $cmd
3020     local rc=0
3021     do_node $node $cmd || rc=$?
3022     [ $rc -le $FSCK_MAX_ERR ] || \
3023         error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
3024     return 0
3025 }
3026
3027 # verify a directory is shared among nodes.
3028 check_shared_dir() {
3029     local dir=$1
3030
3031     [ -z "$dir" ] && return 1
3032     do_rpc_nodes $(comma_list $(nodes_list)) check_logdir $dir
3033     check_write_access $dir || return 1
3034     return 0
3035 }
3036
3037 # Run e2fsck on MDT and OST(s) to generate databases used for lfsck.
3038 generate_db() {
3039     local i
3040     local ostidx
3041     local dev
3042
3043     check_shared_dir $SHARED_DIRECTORY ||
3044         error "$SHARED_DIRECTORY isn't a shared directory"
3045
3046     export MDSDB=$SHARED_DIRECTORY/mdsdb
3047     export OSTDB=$SHARED_DIRECTORY/ostdb
3048
3049     [ $MDSCOUNT -eq 1 ] || error "CMD is not supported"
3050
3051     run_e2fsck $(mdts_nodes) $MDTDEV "--mdsdb $MDSDB"
3052
3053     i=0
3054     ostidx=0
3055     OSTDB_LIST=""
3056     for node in $(osts_nodes); do
3057         for dev in ${OSTDEVS[i]}; do
3058             run_e2fsck $node $dev "--mdsdb $MDSDB --ostdb $OSTDB-$ostidx"
3059             OSTDB_LIST="$OSTDB_LIST $OSTDB-$ostidx"
3060             ostidx=$((ostidx + 1))
3061         done
3062         i=$((i + 1))
3063     done
3064 }
3065
3066 run_lfsck() {
3067     local cmd="$LFSCK_BIN -c -l --mdsdb $MDSDB --ostdb $OSTDB_LIST $MOUNT"
3068     echo $cmd
3069     local rc=0
3070     eval $cmd || rc=$?
3071     [ $rc -le $FSCK_MAX_ERR ] || \
3072         error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
3073     echo "lfsck finished with rc=$rc"
3074
3075     rm -rvf $MDSDB* $OSTDB* || true
3076     return 0
3077 }
3078
3079 check_and_cleanup_lustre() {
3080     if [ "$LFSCK_ALWAYS" = "yes" -a "$TESTSUITE" != "lfsck" ]; then
3081         get_svr_devs
3082         generate_db
3083         run_lfsck
3084     fi
3085
3086     if is_mounted $MOUNT; then
3087         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]* ||
3088             error "remove sub-test dirs failed"
3089         [ "$ENABLE_QUOTA" ] && restore_quota_type || true
3090     fi
3091
3092     if [ "$I_UMOUNTED2" = "yes" ]; then
3093         restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
3094     fi
3095
3096     if [ "$I_MOUNTED2" = "yes" ]; then
3097         cleanup_mount $MOUNT2
3098     fi
3099
3100     if [ "$I_MOUNTED" = "yes" ]; then
3101         cleanupall -f || error "cleanup failed"
3102         unset I_MOUNTED
3103     fi
3104 }
3105
3106 #######
3107 # General functions
3108
3109 wait_for_function () {
3110     local quiet=""
3111
3112     # suppress fn both stderr and stdout
3113     if [ "$1" = "--quiet" ]; then
3114         shift
3115         quiet=" > /dev/null 2>&1"
3116
3117     fi
3118
3119     local fn=$1
3120     local max=${2:-900}
3121     local sleep=${3:-5}
3122
3123     local wait=0
3124
3125     while true; do
3126
3127         eval $fn $quiet && return 0
3128
3129         wait=$((wait + sleep))
3130         [ $wait -lt $max ] || return 1
3131         echo waiting $fn, $((max - wait)) secs left ...
3132         sleep $sleep
3133     done
3134 }
3135
3136 check_network() {
3137     local host=$1
3138     local max=$2
3139     local sleep=${3:-5}
3140
3141     echo `date +"%H:%M:%S (%s)"` waiting for $host network $max secs ...
3142     if ! wait_for_function --quiet "ping -c 1 -w 3 $host" $max $sleep ; then
3143         echo "Network not available!"
3144         exit 1
3145     fi
3146
3147     echo `date +"%H:%M:%S (%s)"` network interface is UP
3148 }
3149
3150 no_dsh() {
3151     shift
3152     eval $@
3153 }
3154
3155 comma_list() {
3156     # the sed converts spaces to commas, but leaves the last space
3157     # alone, so the line doesn't end with a comma.
3158     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
3159 }
3160
3161 list_member () {
3162     local list=$1
3163     local item=$2
3164     echo $list | grep -qw $item
3165 }
3166
3167 # list, excluded are the comma separated lists
3168 exclude_items_from_list () {
3169     local list=$1
3170     local excluded=$2
3171     local item
3172
3173     list=${list//,/ }
3174     for item in ${excluded//,/ }; do
3175         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
3176     done
3177     echo $(comma_list $list)
3178 }
3179
3180 # list, expand  are the comma separated lists
3181 expand_list () {
3182     local list=${1//,/ }
3183     local expand=${2//,/ }
3184     local expanded=
3185
3186     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
3187     echo $(comma_list $expanded)
3188 }
3189
3190 testslist_filter () {
3191     local script=$LUSTRE/tests/${TESTSUITE}.sh
3192
3193     [ -f $script ] || return 0
3194
3195     local start_at=$START_AT
3196     local stop_at=$STOP_AT
3197
3198     local var=${TESTSUITE//-/_}_START_AT
3199     [ x"${!var}" != x ] && start_at=${!var}
3200     var=${TESTSUITE//-/_}_STOP_AT
3201     [ x"${!var}" != x ] && stop_at=${!var}
3202
3203     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
3204         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
3205             /^'${start_at}'$/ {flag = 0}
3206             {if (flag == 1) print $0}
3207             /^'${stop_at}'$/ { flag = 1 }'
3208 }
3209
3210 absolute_path() {
3211     (cd `dirname $1`; echo $PWD/`basename $1`)
3212 }
3213
3214 get_facets () {
3215     local types=${1:-"OST MDS MGS"}
3216
3217     local list=""
3218
3219     for entry in $types; do
3220         local name=$(echo $entry | tr "[:upper:]" "[:lower:]")
3221         local type=$(echo $entry | tr "[:lower:]" "[:upper:]")
3222
3223         case $type in
3224                 MGS ) list="$list $name";;
3225             MDS|OST ) local count=${type}COUNT
3226                        for ((i=1; i<=${!count}; i++)) do
3227                           list="$list ${name}$i"
3228                       done;;
3229                   * ) error "Invalid facet type"
3230                  exit 1;;
3231         esac
3232     done
3233     echo $(comma_list $list)
3234 }
3235
3236 ##################################
3237 # Adaptive Timeouts funcs
3238
3239 at_is_enabled() {
3240     # only check mds, we assume at_max is the same on all nodes
3241     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
3242     if [ $at_max -eq 0 ]; then
3243         return 1
3244     else
3245         return 0
3246     fi
3247 }
3248
3249 at_get() {
3250     local facet=$1
3251     local at=$2
3252
3253     # suppose that all ost-s have the same $at value set
3254     [ $facet != "ost" ] || facet=ost1
3255
3256     do_facet $facet "lctl get_param -n $at"
3257 }
3258
3259 at_max_get() {
3260     at_get $1 at_max
3261 }
3262
3263 at_max_set() {
3264     local at_max=$1
3265     shift
3266
3267     local facet
3268     local hosts
3269     for facet in $@; do
3270         if [ $facet == "ost" ]; then
3271             facet=$(get_facets OST)
3272         elif [ $facet == "mds" ]; then
3273             facet=$(get_facets MDS)
3274         fi
3275         hosts=$(expand_list $hosts $(facets_hosts $facet))
3276     done
3277
3278     do_nodes $hosts lctl set_param at_max=$at_max
3279 }
3280
3281 ##################################
3282 # OBD_FAIL funcs
3283
3284 drop_request() {
3285 # OBD_FAIL_MDS_ALL_REQUEST_NET
3286     RC=0
3287     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
3288     do_facet client "$1" || RC=$?
3289     do_facet $SINGLEMDS lctl set_param fail_loc=0
3290     return $RC
3291 }
3292
3293 drop_reply() {
3294 # OBD_FAIL_MDS_ALL_REPLY_NET
3295     RC=0
3296     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
3297     do_facet client "$@" || RC=$?
3298     do_facet $SINGLEMDS lctl set_param fail_loc=0
3299     return $RC
3300 }
3301
3302 drop_reint_reply() {
3303 # OBD_FAIL_MDS_REINT_NET_REP
3304     RC=0
3305     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
3306     do_facet client "$@" || RC=$?
3307     do_facet $SINGLEMDS lctl set_param fail_loc=0
3308     return $RC
3309 }
3310
3311 pause_bulk() {
3312 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
3313     RC=0
3314     do_facet ost1 lctl set_param fail_loc=0x214
3315     do_facet client "$1" || RC=$?
3316     do_facet client "sync"
3317     do_facet ost1 lctl set_param fail_loc=0
3318     return $RC
3319 }
3320
3321 drop_ldlm_cancel() {
3322 #define OBD_FAIL_LDLM_CANCEL             0x304
3323         local RC=0
3324         local list=$(comma_list $(mdts_nodes) $(osts_nodes))
3325         do_nodes $list lctl set_param fail_loc=0x304
3326
3327         do_facet client "$@" || RC=$?
3328
3329         do_nodes $list lctl set_param fail_loc=0
3330         return $RC
3331 }
3332
3333 drop_bl_callback() {
3334 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
3335     RC=0
3336     do_facet client lctl set_param fail_loc=0x305
3337     do_facet client "$@" || RC=$?
3338     do_facet client lctl set_param fail_loc=0
3339     return $RC
3340 }
3341
3342 drop_ldlm_reply() {
3343 #define OBD_FAIL_LDLM_REPLY              0x30c
3344     RC=0
3345     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
3346     do_facet client "$@" || RC=$?
3347     do_facet $SINGLEMDS lctl set_param fail_loc=0
3348     return $RC
3349 }
3350
3351 clear_failloc() {
3352     facet=$1
3353     pause=$2
3354     sleep $pause
3355     echo "clearing fail_loc on $facet"
3356     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
3357 }
3358
3359 set_nodes_failloc () {
3360     do_nodes $(comma_list $1)  lctl set_param fail_loc=$2
3361 }
3362
3363 cancel_lru_locks() {
3364     $LCTL mark "cancel_lru_locks $1 start"
3365     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
3366         $LCTL set_param -n $d=clear
3367     done
3368     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
3369     $LCTL mark "cancel_lru_locks $1 stop"
3370 }
3371
3372 default_lru_size()
3373 {
3374         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
3375         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
3376         echo "$DEFAULT_LRU_SIZE"
3377 }
3378
3379 lru_resize_enable()
3380 {
3381     lctl set_param ldlm.namespaces.*$1*.lru_size=0
3382 }
3383
3384 lru_resize_disable()
3385 {
3386     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
3387 }
3388
3389 pgcache_empty() {
3390     local FILE
3391     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
3392         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
3393             echo there is still data in page cache $FILE ?
3394             lctl get_param -n $FILE
3395             return 1
3396         fi
3397     done
3398     return 0
3399 }
3400
3401 debugsave() {
3402     DEBUGSAVE="$(lctl get_param -n debug)"
3403 }
3404
3405 debugrestore() {
3406     [ -n "$DEBUGSAVE" ] && \
3407         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
3408     DEBUGSAVE=""
3409 }
3410
3411 debug_size_save() {
3412     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
3413 }
3414
3415 debug_size_restore() {
3416     [ -n "$DEBUG_SIZE_SAVED" ] && \
3417         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
3418     DEBUG_SIZE_SAVED=""
3419 }
3420
3421 start_full_debug_logging() {
3422     debugsave
3423     debug_size_save
3424
3425     local FULLDEBUG=-1
3426     local DEBUG_SIZE=150
3427
3428     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
3429     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
3430 }
3431
3432 stop_full_debug_logging() {
3433     debug_size_restore
3434     debugrestore
3435 }
3436
3437 ##################################
3438 # Test interface
3439 ##################################
3440
3441 error_noexit() {
3442     local TYPE=${TYPE:-"FAIL"}
3443
3444     local dump=true
3445     # do not dump logs if $1=false
3446     if [ "x$1" = "xfalse" ]; then
3447         shift
3448         dump=false
3449     fi
3450
3451     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
3452
3453     mkdir -p $LOGDIR
3454     # We need to dump the logs on all nodes
3455     if $dump; then
3456         gather_logs $(comma_list $(nodes_list))
3457     fi
3458
3459     debugrestore
3460     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
3461     echo "$@" > $LOGDIR/err
3462 }
3463
3464 exit_status () {
3465     local status=0
3466     local log=$TESTSUITELOG
3467
3468     [ -f "$log" ] && grep -q FAIL: $log && status=1
3469     exit $status
3470 }
3471
3472 error() {
3473     error_noexit "$@"
3474     exit 1
3475 }
3476
3477 error_exit() {
3478     error "$@"
3479 }
3480
3481 # use only if we are ignoring failures for this test, bugno required.
3482 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
3483 # e.g. error_ignore 5494 "your message"
3484 error_ignore() {
3485     local TYPE="IGNORE (bz$1)"
3486     shift
3487     error_noexit "$@"
3488 }
3489
3490 skip_env () {
3491     $FAIL_ON_SKIP_ENV && error false $@ || skip $@
3492 }
3493
3494 skip () {
3495     echo
3496     log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
3497     [ "$ALWAYS_SKIPPED" ] && \
3498         skip_logged ${TESTNAME} "$@" || true
3499     [ "$TESTSUITELOG" ] && \
3500         echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
3501 }
3502
3503 build_test_filter() {
3504     EXCEPT="$EXCEPT $(testslist_filter)"
3505
3506     [ "$ONLY" ] && log "only running test `echo $ONLY`"
3507     for O in $ONLY; do
3508         eval ONLY_${O}=true
3509     done
3510     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
3511         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
3512     [ "$EXCEPT_SLOW" ] && \
3513         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
3514     for E in $EXCEPT; do
3515         eval EXCEPT_${E}=true
3516     done
3517     for E in $ALWAYS_EXCEPT; do
3518         eval EXCEPT_ALWAYS_${E}=true
3519     done
3520     for E in $EXCEPT_SLOW; do
3521         eval EXCEPT_SLOW_${E}=true
3522     done
3523     for G in $GRANT_CHECK_LIST; do
3524         eval GCHECK_ONLY_${G}=true
3525         done
3526 }
3527
3528 basetest() {
3529     if [[ $1 = [a-z]* ]]; then
3530         echo $1
3531     else
3532         echo ${1%%[a-z]*}
3533     fi
3534 }
3535
3536 # print a newline if the last test was skipped
3537 export LAST_SKIPPED=
3538 export ALWAYS_SKIPPED=
3539 #
3540 # Main entry into test-framework. This is called with the name and
3541 # description of a test. The name is used to find the function to run
3542 # the test using "test_$name".
3543 #
3544 # This supports a variety of methods of specifying specific test to
3545 # run or not run.  These need to be documented...
3546 #
3547 run_test() {
3548     assert_DIR
3549
3550     export base=`basetest $1`
3551     if [ ! -z "$ONLY" ]; then
3552         testname=ONLY_$1
3553         if [ ${!testname}x != x ]; then
3554             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
3555             run_one_logged $1 "$2"
3556             return $?
3557         fi
3558         testname=ONLY_$base
3559         if [ ${!testname}x != x ]; then
3560             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
3561             run_one_logged $1 "$2"
3562             return $?
3563         fi
3564         LAST_SKIPPED="y"
3565         echo -n "."
3566         return 0
3567     fi
3568     testname=EXCEPT_$1
3569     if [ ${!testname}x != x ]; then
3570         LAST_SKIPPED="y"
3571         TESTNAME=test_$1 skip "skipping excluded test $1"
3572         return 0
3573     fi
3574     testname=EXCEPT_$base
3575     if [ ${!testname}x != x ]; then
3576         LAST_SKIPPED="y"
3577         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
3578         return 0
3579     fi
3580     testname=EXCEPT_ALWAYS_$1
3581     if [ ${!testname}x != x ]; then
3582         LAST_SKIPPED="y"
3583         ALWAYS_SKIPPED="y"
3584         TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1"
3585         return 0
3586     fi
3587     testname=EXCEPT_ALWAYS_$base
3588     if [ ${!testname}x != x ]; then
3589         LAST_SKIPPED="y"
3590         ALWAYS_SKIPPED="y"
3591         TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1 (base $base)"
3592         return 0
3593     fi
3594     testname=EXCEPT_SLOW_$1
3595     if [ ${!testname}x != x ]; then
3596         LAST_SKIPPED="y"
3597         TESTNAME=test_$1 skip "skipping SLOW test $1"
3598         return 0
3599     fi
3600     testname=EXCEPT_SLOW_$base
3601     if [ ${!testname}x != x ]; then
3602         LAST_SKIPPED="y"
3603         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
3604         return 0
3605     fi
3606
3607     LAST_SKIPPED=
3608     ALWAYS_SKIPPED=
3609     run_one_logged $1 "$2"
3610
3611     return $?
3612 }
3613
3614 equals_msg() {
3615     banner "$*"
3616 }
3617
3618 log() {
3619     echo "$*"
3620     module_loaded lnet || load_modules
3621
3622     local MSG="$*"
3623     # Get rid of '
3624     MSG=${MSG//\'/\\\'}
3625     MSG=${MSG//\(/\\\(}
3626     MSG=${MSG//\)/\\\)}
3627     MSG=${MSG//\;/\\\;}
3628     MSG=${MSG//\|/\\\|}
3629     MSG=${MSG//\>/\\\>}
3630     MSG=${MSG//\</\\\<}
3631     MSG=${MSG//\//\\\/}
3632     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
3633 }
3634
3635 trace() {
3636         log "STARTING: $*"
3637         strace -o $TMP/$1.strace -ttt $*
3638         RC=$?
3639         log "FINISHED: $*: rc $RC"
3640         return 1
3641 }
3642
3643 complete () {
3644     equals_msg $1 test complete, duration $2 sec
3645     [ -f "$TESTSUITELOG" ] && egrep .FAIL $TESTSUITELOG || true
3646     echo duration $2 >>$TESTSUITELOG
3647 }
3648
3649 pass() {
3650     # Set TEST_STATUS here; will be used for logging the result
3651     if [ -f $LOGDIR/err ]; then
3652         TEST_STATUS="FAIL"
3653     else
3654         TEST_STATUS="PASS"
3655     fi
3656     echo "$TEST_STATUS $@" 2>&1 | tee -a $TESTSUITELOG
3657 }
3658
3659 check_mds() {
3660     local FFREE=$(do_node $SINGLEMDS \
3661         lctl get_param -n osd*.*MDT*.filesfree | calc_sum)
3662     local FTOTAL=$(do_node $SINGLEMDS \
3663         lctl get_param -n osd*.*MDT*.filestotal | calc_sum)
3664
3665     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
3666 }
3667
3668 reset_fail_loc () {
3669     echo -n "Resetting fail_loc on all nodes..."
3670     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
3671     echo done.
3672 }
3673
3674
3675 #
3676 # Log a message (on all nodes) padded with "=" before and after. 
3677 # Also appends a timestamp and prepends the testsuite name.
3678
3679
3680 EQUALS="===================================================================================================="
3681 banner() {
3682     msg="== ${TESTSUITE} $*"
3683     last=${msg: -1:1}
3684     [[ $last != "=" && $last != " " ]] && msg="$msg "
3685     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
3686     # always include at least == after the message
3687     log "$msg== $(date +"%H:%M:%S (%s)")"
3688 }
3689
3690 #
3691 # Run a single test function and cleanup after it.  
3692 #
3693 # This function should be run in a subshell so the test func can
3694 # exit() without stopping the whole script.
3695 #
3696 run_one() {
3697     local testnum=$1
3698     local message=$2
3699     tfile=f${testnum}
3700     export tdir=d0.${TESTSUITE}/d${base}
3701     export TESTNAME=test_$testnum
3702     local SAVE_UMASK=`umask`
3703     umask 0022
3704
3705     banner "test $testnum: $message"
3706     test_${testnum} || error "test_$testnum failed with $?"
3707     cd $SAVE_PWD
3708     reset_fail_loc
3709     check_grant ${testnum} || error "check_grant $testnum failed with $?"
3710     check_catastrophe || error "LBUG/LASSERT detected"
3711     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
3712     unset TESTNAME
3713     unset tdir
3714     umask $SAVE_UMASK
3715     return 0
3716 }
3717
3718 #
3719 # Wrapper around run_one to ensure:
3720 #  - test runs in subshell
3721 #  - output of test is saved to separate log file for error reporting
3722 #  - test result is saved to data file
3723 #
3724 run_one_logged() {
3725     local BEFORE=`date +%s`
3726     local TEST_ERROR
3727     local name=${TESTSUITE}.test_${1}.test_log.$(hostname -s).log
3728     local test_log=$LOGDIR/$name
3729     rm -rf $LOGDIR/err
3730     local SAVE_UMASK=`umask`
3731     umask 0022
3732
3733     echo
3734     log_sub_test_begin test_${1}
3735     (run_one $1 "$2") 2>&1 | tee -i $test_log
3736     local RC=${PIPESTATUS[0]}
3737
3738     [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] && \
3739         echo "test_$1 returned $RC" | tee $LOGDIR/err
3740
3741     duration=$((`date +%s` - $BEFORE))
3742     pass "$1" "(${duration}s)"
3743     [ -f $LOGDIR/err ] && TEST_ERROR=$(cat $LOGDIR/err)
3744     log_sub_test_end $TEST_STATUS $duration "$RC" "$TEST_ERROR"
3745
3746     if [ -f $LOGDIR/err ]; then
3747         $FAIL_ON_ERROR && exit $RC
3748     fi
3749
3750     umask $SAVE_UMASK
3751
3752     return $RC
3753 }
3754
3755 #
3756 # Print information of skipped tests to result.yml
3757 #
3758 skip_logged(){
3759     log_sub_test_begin $1
3760     log_sub_test_end "SKIP" "0" "0" "\"$2\""
3761 }
3762
3763 canonical_path() {
3764     (cd `dirname $1`; echo $PWD/`basename $1`)
3765 }
3766
3767
3768 check_grant() {
3769     export base=`basetest $1`
3770     [ "$CHECK_GRANT" == "no" ] && return 0
3771
3772         testname=GCHECK_ONLY_${base}
3773         [ ${!testname}x == x ] && return 0
3774
3775     echo -n "checking grant......"
3776
3777         local clients=$CLIENTS
3778         [ -z $clients ] && clients=$(hostname)
3779
3780     # sync all the data and make sure no pending data on server
3781     do_nodes $clients sync
3782
3783     # get client grant
3784     client_grant=`do_nodes $clients \
3785                     "$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes" | \
3786                     awk '{total += $1} END{print total}'`
3787
3788     # get server grant
3789     server_grant=`do_nodes $(comma_list $(osts_nodes)) \
3790                     "$LCTL get_param -n obdfilter.${FSNAME}-OST*.tot_granted" |
3791                     awk '{total += $1} END{print total}'`
3792
3793     # check whether client grant == server grant
3794     if [ $client_grant -ne $server_grant ]; then
3795         echo "failed: client:${client_grant} server: ${server_grant}."
3796         do_nodes $(comma_list $(osts_nodes)) \
3797                    "$LCTL get_param obdfilter.${FSNAME}-OST*.tot*"
3798         do_nodes $clients "$LCTL get_param osc.${FSNAME}-*.cur_*_bytes"
3799         return 1
3800     else
3801         echo "pass: client:${client_grant} server: ${server_grant}"
3802     fi
3803
3804 }
3805
3806 ########################
3807 # helper functions
3808
3809 osc_to_ost()
3810 {
3811     osc=$1
3812     ost=`echo $1 | awk -F_ '{print $3}'`
3813     if [ -z $ost ]; then
3814         ost=`echo $1 | sed 's/-osc.*//'`
3815     fi
3816     echo $ost
3817 }
3818
3819 ostuuid_from_index()
3820 {
3821     $LFS osts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
3822 }
3823
3824 ostname_from_index() {
3825     local uuid=$(ostuuid_from_index $1)
3826     echo ${uuid/_UUID/}
3827 }
3828
3829 index_from_ostuuid()
3830 {
3831     $LFS osts $2 | sed -ne "/${1}/s/\(.*\): .* .*$/\1/p"
3832 }
3833
3834 mdtuuid_from_index()
3835 {
3836     $LFS mdts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
3837 }
3838
3839 remote_node () {
3840     local node=$1
3841     [ "$node" != "$(hostname)" ]
3842 }
3843
3844 remote_mds ()
3845 {
3846     local node
3847     for node in $(mdts_nodes); do
3848         remote_node $node && return 0
3849     done
3850     return 1
3851 }
3852
3853 remote_mds_nodsh()
3854 {
3855     [ "$CLIENTONLY" ] && return 0 || true
3856     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
3857 }
3858
3859 require_dsh_mds()
3860 {
3861         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
3862             MSKIPPED=1 && return 1
3863         return 0
3864 }
3865
3866 remote_ost ()
3867 {
3868     local node
3869     for node in $(osts_nodes) ; do
3870         remote_node $node && return 0
3871     done
3872     return 1
3873 }
3874
3875 remote_ost_nodsh()
3876 {
3877     [ "$CLIENTONLY" ] && return 0 || true 
3878     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
3879 }
3880
3881 require_dsh_ost()
3882 {
3883         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
3884             OSKIPPED=1 && return 1
3885         return 0
3886 }
3887
3888 remote_mgs_nodsh()
3889 {
3890     local MGS 
3891     MGS=$(facet_host mgs)
3892     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
3893 }
3894
3895 local_mode ()
3896 {
3897     remote_mds_nodsh || remote_ost_nodsh || \
3898         $(single_local_node $(comma_list $(nodes_list)))
3899 }
3900
3901 mdts_nodes () {
3902     local MDSNODES
3903     local NODES_sort
3904     for num in `seq $MDSCOUNT`; do
3905         MDSNODES="$MDSNODES $(facet_host mds$num)"
3906     done
3907     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
3908
3909     echo $NODES_sort
3910 }
3911
3912 remote_servers () {
3913     remote_ost && remote_mds
3914 }
3915
3916 facets_nodes () {
3917     local facets=$1
3918     local nodes
3919     local NODES_sort
3920
3921     for facet in ${facets//,/ }; do
3922         if [ "$FAILURE_MODE" = HARD ]; then
3923             nodes="$nodes $(facet_active_host $facet)"
3924         else
3925             nodes="$nodes $(facet_host $facet)"
3926         fi
3927     done
3928     NODES_sort=$(for i in $nodes; do echo $i; done | sort -u)
3929
3930     echo $NODES_sort
3931 }
3932
3933 osts_nodes () {
3934     local facets=$(get_facets OST)
3935     local nodes=$(facets_nodes $facets)
3936
3937     echo $nodes
3938 }
3939
3940 nodes_list () {
3941     # FIXME. We need a list of clients
3942     local myNODES=$HOSTNAME
3943     local myNODES_sort
3944
3945     # CLIENTS (if specified) contains the local client
3946     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
3947
3948     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
3949         myNODES="$myNODES $(facets_nodes $(get_facets))"
3950     fi
3951
3952     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
3953
3954     echo $myNODES_sort
3955 }
3956
3957 remote_nodes_list () {
3958     local rnodes=$(nodes_list)
3959     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
3960     echo $rnodes
3961 }
3962
3963 init_clients_lists () {
3964     # Sanity check: exclude the local client from RCLIENTS
3965     local clients=$(hostlist_expand "$RCLIENTS")
3966     local rclients=$(exclude_items_from_list "$clients" $HOSTNAME)
3967
3968     # Sanity check: exclude the dup entries
3969     RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)
3970
3971     clients="$SINGLECLIENT $HOSTNAME $RCLIENTS"
3972
3973     # Sanity check: exclude the dup entries from CLIENTS
3974     # for those configs which has SINGLCLIENT set to local client
3975     clients=$(for i in $clients; do echo $i; done | sort -u)
3976
3977     CLIENTS=$(comma_list $clients)
3978     local -a remoteclients=($RCLIENTS)
3979     for ((i=0; $i<${#remoteclients[@]}; i++)); do
3980             varname=CLIENT$((i + 2))
3981             eval $varname=${remoteclients[i]}
3982     done
3983
3984     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
3985 }
3986
3987 get_random_entry () {
3988     local rnodes=$1
3989
3990     rnodes=${rnodes//,/ }
3991
3992     local -a nodes=($rnodes)
3993     local num=${#nodes[@]} 
3994     local i=$((RANDOM * num * 2 / 65536))
3995
3996     echo ${nodes[i]}
3997 }
3998
3999 client_only () {
4000     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
4001 }
4002
4003 is_patchless ()
4004 {
4005     lctl get_param version | grep -q patchless
4006 }
4007
4008 check_versions () {
4009     [ "$(lustre_version_code client)" = "$(lustre_version_code $SINGLEMDS)" -a \
4010       "$(lustre_version_code client)" = "$(lustre_version_code ost1)" ]
4011 }
4012
4013 get_node_count() {
4014     local nodes="$@"
4015     echo $nodes | wc -w || true
4016 }
4017
4018 mixed_ost_devs () {
4019     local nodes=$(osts_nodes)
4020     local osscount=$(get_node_count "$nodes")
4021     [ ! "$OSTCOUNT" = "$osscount" ]
4022 }
4023
4024 mixed_mdt_devs () {
4025     local nodes=$(mdts_nodes)
4026     local mdtcount=$(get_node_count "$nodes")
4027     [ ! "$MDSCOUNT" = "$mdtcount" ]
4028 }
4029
4030 generate_machine_file() {
4031     local nodes=${1//,/ }
4032     local machinefile=$2
4033     rm -f $machinefile
4034     for node in $nodes; do
4035         echo $node >>$machinefile || \
4036             { echo "can not generate machinefile $machinefile" && return 1; }
4037     done
4038 }
4039
4040 get_stripe () {
4041     local file=$1/stripe
4042     touch $file
4043     $LFS getstripe -v $file || error
4044     rm -f $file
4045 }
4046
4047 setstripe_nfsserver () {
4048     local dir=$1
4049
4050     local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
4051                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -1)
4052
4053     [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
4054
4055     do_nodev $nfsserver lfs setstripe "$@"
4056 }
4057
4058 check_runas_id_ret() {
4059     local myRC=0
4060     local myRUNAS_UID=$1
4061     local myRUNAS_GID=$2
4062     shift 2
4063     local myRUNAS=$@
4064     if [ -z "$myRUNAS" ]; then
4065         error_exit "myRUNAS command must be specified for check_runas_id"
4066     fi
4067     if $GSS_KRB5; then
4068         $myRUNAS krb5_login.sh || \
4069             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
4070     fi
4071     mkdir $DIR/d0_runas_test
4072     chmod 0755 $DIR
4073     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
4074     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
4075     rm -rf $DIR/d0_runas_test
4076     return $myRC
4077 }
4078
4079 check_runas_id() {
4080     local myRUNAS_UID=$1
4081     local myRUNAS_GID=$2
4082     shift 2
4083     local myRUNAS=$@
4084     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
4085         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
4086         Please set RUNAS_ID to some UID which exists on MDS and client or
4087         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
4088 }
4089
4090 # obtain the UID/GID for MPI_USER
4091 get_mpiuser_id() {
4092     local mpi_user=$1
4093
4094     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
4095 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
4096
4097     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
4098 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
4099 }
4100
4101 # obtain and cache Kerberos ticket-granting ticket
4102 refresh_krb5_tgt() {
4103     local myRUNAS_UID=$1
4104     local myRUNAS_GID=$2
4105     shift 2
4106     local myRUNAS=$@
4107     if [ -z "$myRUNAS" ]; then
4108         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
4109     fi
4110
4111     CLIENTS=${CLIENTS:-$HOSTNAME}
4112     do_nodes $CLIENTS "set -x
4113 if ! $myRUNAS krb5_login.sh; then
4114     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
4115     exit 1
4116 fi"
4117 }
4118
4119 # Run multiop in the background, but wait for it to print
4120 # "PAUSING" to its stdout before returning from this function.
4121 multiop_bg_pause() {
4122     MULTIOP_PROG=${MULTIOP_PROG:-$MULTIOP}
4123     FILE=$1
4124     ARGS=$2
4125
4126     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
4127     mkfifo $TMPPIPE
4128
4129     echo "$MULTIOP_PROG $FILE v$ARGS"
4130     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
4131
4132     echo "TMPPIPE=${TMPPIPE}"
4133     read -t 60 multiop_output < $TMPPIPE
4134     if [ $? -ne 0 ]; then
4135         rm -f $TMPPIPE
4136         return 1
4137     fi
4138     rm -f $TMPPIPE
4139     if [ "$multiop_output" != "PAUSING" ]; then
4140         echo "Incorrect multiop output: $multiop_output"
4141         kill -9 $PID
4142         return 1
4143     fi
4144
4145     return 0
4146 }
4147
4148 do_and_time () {
4149     local cmd=$1
4150     local rc
4151
4152     SECONDS=0
4153     eval '$cmd'
4154     
4155     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
4156
4157     echo $SECONDS
4158     return $rc
4159 }
4160
4161 inodes_available () {
4162     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
4163     echo $IFree
4164 }
4165
4166 mdsrate_inodes_available () {
4167     local min_inodes=$(inodes_available)
4168     echo $((min_inodes * 99 / 100))
4169 }
4170
4171 # reset llite stat counters
4172 clear_llite_stats(){
4173         lctl set_param -n llite.*.stats 0
4174 }
4175
4176 # sum llite stat items
4177 calc_llite_stats() {
4178         local res=$(lctl get_param -n llite.*.stats |
4179                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
4180         echo $res
4181 }
4182
4183 # reset osc stat counters
4184 clear_osc_stats(){
4185         lctl set_param -n osc.*.osc_stats 0
4186 }
4187
4188 # sum osc stat items
4189 calc_osc_stats() {
4190         local res=$(lctl get_param -n osc.*.osc_stats |
4191                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
4192         echo $res
4193 }
4194
4195 calc_sum () {
4196         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
4197 }
4198
4199 calc_osc_kbytes () {
4200         df $MOUNT > /dev/null
4201         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
4202 }
4203
4204 # save_lustre_params(node, parameter_mask)
4205 # generate a stream of formatted strings (<node> <param name>=<param value>)
4206 save_lustre_params() {
4207         local s
4208         do_nodesv $1 "lctl get_param $2 | while read s; do echo \\\$s; done"
4209 }
4210
4211 # restore lustre parameters from input stream, produces by save_lustre_params
4212 restore_lustre_params() {
4213         local node
4214         local name
4215         local val
4216         while IFS=" =" read node name val; do
4217                 do_node ${node//:/} "lctl set_param -n $name $val"
4218         done
4219 }
4220
4221 check_catastrophe() {
4222     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
4223     local C=$CATASTROPHE
4224     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
4225
4226     if [ $rnodes ]; then
4227         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
4228 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
4229 exit \\\$rc;"
4230     fi 
4231 }
4232
4233 # CMD: determine mds index where directory inode presents
4234 get_mds_dir () {
4235     local dir=$1
4236     local file=$dir/f0.get_mds_dir_tmpfile
4237
4238     mkdir -p $dir
4239     rm -f $file
4240     sleep 1
4241     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
4242     local -a oldused=($iused)
4243
4244     openfile -f O_CREAT:O_LOV_DELAY_CREATE -m 0644 $file > /dev/null
4245     sleep 1
4246     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
4247     local -a newused=($iused)
4248
4249     local num=0
4250     for ((i=0; i<${#newused[@]}; i++)); do
4251          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
4252              echo $(( i + 1 ))
4253              rm -f $file
4254              return 0
4255          fi
4256     done
4257     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
4258 }
4259
4260 mdsrate_cleanup () {
4261     if [ -d $4 ]; then
4262         mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
4263         rmdir $4
4264     fi
4265 }
4266
4267 delayed_recovery_enabled () {
4268     local var=${SINGLEMDS}_svc
4269     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
4270 }
4271
4272 ########################
4273
4274 convert_facet2label() { 
4275     local facet=$1
4276
4277     if [ x$facet = xost ]; then
4278        facet=ost1
4279     fi
4280
4281     local varsvc=${facet}_svc
4282
4283     if [ -n ${!varsvc} ]; then
4284         echo ${!varsvc}
4285     else  
4286         error "No lablel for $facet!"
4287     fi
4288 }
4289
4290 get_clientosc_proc_path() {
4291     echo "${1}-osc-[^M]*"
4292 }
4293
4294 get_lustre_version () {
4295     local facet=${1:-"$SINGLEMDS"}    
4296     do_facet $facet $LCTL get_param -n version | awk '/^lustre:/ {print $2}'
4297 }
4298
4299 lustre_version_code() {
4300     local facet=${1:-"$SINGLEMDS"}
4301     version_code $(get_lustre_version $1)
4302 }
4303
4304 # If the 2.0 MDS was mounted on 1.8 device, then the OSC and LOV names
4305 # used by MDT would not be changed.
4306 # mdt lov: fsname-mdtlov
4307 # mdt osc: fsname-OSTXXXX-osc
4308 mds_on_old_device() {
4309     local mds=${1:-"$SINGLEMDS"}
4310
4311     if [ $(lustre_version_code $mds) -gt $(version_code 1.9.0) ]; then
4312         do_facet $mds "lctl list_param osc.$FSNAME-OST*-osc \
4313             > /dev/null 2>&1" && return 0
4314     fi
4315     return 1
4316 }
4317
4318 get_mdtosc_proc_path() {
4319     local mds_facet=$1
4320     local ost_label=${2:-"*OST*"}
4321
4322     [ "$mds_facet" = "mds" ] && mds_facet=$SINGLEMDS
4323     local mdt_label=$(convert_facet2label $mds_facet)
4324     local mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')
4325
4326     if [ $(lustre_version_code $mds_facet) -le $(version_code 1.8.0) ] ||
4327        mds_on_old_device $mds_facet; then
4328         echo "${ost_label}-osc"
4329     else
4330         echo "${ost_label}-osc-${mdt_index}"
4331     fi
4332 }
4333
4334 get_osc_import_name() {
4335     local facet=$1
4336     local ost=$2
4337     local label=$(convert_facet2label $ost)
4338
4339     if [ "${facet:0:3}" = "mds" ]; then
4340         get_mdtosc_proc_path $facet $label
4341         return 0
4342     fi
4343
4344     get_clientosc_proc_path $label
4345     return 0
4346 }
4347
4348 _wait_import_state () {
4349     local expected=$1
4350     local CONN_PROC=$2
4351     local maxtime=${3:-$(max_recovery_time)}
4352     local CONN_STATE
4353     local i=0
4354
4355     CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
4356     while [ "${CONN_STATE}" != "${expected}" ]; do
4357         if [ "${expected}" == "DISCONN" ]; then
4358             # for disconn we can check after proc entry is removed
4359             [ "x${CONN_STATE}" == "x" ] && return 0
4360             #  with AT enabled, we can have connect request timeout near of
4361             # reconnect timeout and test can't see real disconnect
4362             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
4363         fi
4364         [ $i -ge $maxtime ] && \
4365             error "can't put import for $CONN_PROC into ${expected} state after $i sec, have ${CONN_STATE}" && \
4366             return 1
4367         sleep 1
4368         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
4369         i=$(($i + 1))
4370     done
4371
4372     log "$CONN_PROC in ${CONN_STATE} state after $i sec"
4373     return 0
4374 }
4375
4376 wait_import_state() {
4377     local state=$1
4378     local params=$2
4379     local maxtime=${3:-$(max_recovery_time)}
4380     local param
4381
4382     for param in ${params//,/ }; do
4383         _wait_import_state $state $param $maxtime || return
4384     done
4385 }
4386
4387 # One client request could be timed out because server was not ready
4388 # when request was sent by client.
4389 # The request timeout calculation details :
4390 # ptl_send_rpc ()
4391 #      /* We give the server rq_timeout secs to process the req, and
4392 #      add the network latency for our local timeout. */
4393 #      request->rq_deadline = request->rq_sent + request->rq_timeout +
4394 #           ptlrpc_at_get_net_latency(request) ;
4395 #
4396 # ptlrpc_connect_import ()
4397 #      request->rq_timeout = INITIAL_CONNECT_TIMEOUT
4398 #
4399 # init_imp_at () ->
4400 #   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0
4401 # ptlrpc_at_get_net_latency(request) ->
4402 #       at_get (max (iat_net_latency=0, at_min)) = at_min
4403 #
4404 # i.e.:
4405 # request->rq_timeout + ptlrpc_at_get_net_latency(request) =
4406 # INITIAL_CONNECT_TIMEOUT + at_min
4407 #
4408 # We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT
4409 # because we can not get this value in runtime,
4410 # the value depends on configure options, and it is not stored in /proc.
4411 # obd_support.h:
4412 # #define CONNECTION_SWITCH_MIN 5U
4413 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
4414
4415 request_timeout () {
4416     local facet=$1
4417
4418     # request->rq_timeout = INITIAL_CONNECT_TIMEOUT
4419     local init_connect_timeout=$TIMEOUT
4420     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
4421
4422     local at_min=$(at_get $facet at_min)
4423
4424     echo $(( init_connect_timeout + at_min ))
4425 }
4426
4427 wait_osc_import_state() {
4428     local facet=$1
4429     local ost_facet=$2
4430     local expected=$3
4431     local ost=$(get_osc_import_name $facet $ost_facet)
4432
4433     local param="osc.${ost}.ost_server_uuid"
4434
4435     # 1. wait the deadline of client 1st request (it could be skipped)
4436     # 2. wait the deadline of client 2nd request
4437     local maxtime=$(( 2 * $(request_timeout $facet)))
4438
4439     if ! do_rpc_nodes $(facet_host $facet) \
4440                 _wait_import_state $expected $param $maxtime; then
4441         error "import is not in ${expected} state"
4442         return 1
4443     fi
4444
4445     return 0
4446 }
4447
4448 get_clientmdc_proc_path() {
4449     echo "${1}-mdc-*"
4450 }
4451
4452 do_rpc_nodes () {
4453     local list=$1
4454     shift
4455
4456     # Add paths to lustre tests for 32 and 64 bit systems.
4457     local RPATH="PATH=$RLUSTRE/tests:/usr/lib/lustre/tests:/usr/lib64/lustre/tests:$PATH"
4458     do_nodesv $list "${RPATH} NAME=${NAME} sh rpc.sh $@ "
4459 }
4460
4461 wait_clients_import_state () {
4462     local list=$1
4463     local facet=$2
4464     local expected=$3
4465
4466     local facets=$facet
4467
4468     if [ "$FAILURE_MODE" = HARD ]; then
4469         facets=$(facets_on_host $(facet_active_host $facet))
4470     fi
4471
4472     for facet in ${facets//,/ }; do
4473     local label=$(convert_facet2label $facet)
4474     local proc_path
4475     case $facet in
4476         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
4477         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
4478         *) error "unknown facet!" ;;
4479     esac
4480     local params=$(expand_list $params $proc_path)
4481     done
4482
4483     if ! do_rpc_nodes $list wait_import_state $expected $params; then
4484         error "import is not in ${expected} state"
4485         return 1
4486     fi
4487 }
4488
4489 oos_full() {
4490         local -a AVAILA
4491         local -a GRANTA
4492         local OSCFULL=1
4493         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
4494                   $LCTL get_param obdfilter.*.kbytesavail))
4495         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
4496                   $LCTL get_param -n obdfilter.*.tot_granted))
4497         for ((i=0; i<${#AVAILA[@]}; i++)); do
4498                 local -a AVAIL1=(${AVAILA[$i]//=/ })
4499                 GRANT=$((${GRANTA[$i]}/1024))
4500                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} grnt=$GRANT diff=$((AVAIL1[1] - GRANT))
4501                 [ $((AVAIL1[1] - GRANT)) -lt 400 ] && OSCFULL=0 && echo " FULL" || echo
4502         done
4503         return $OSCFULL
4504 }
4505
4506 pool_list () {
4507    do_facet mgs lctl pool_list $1
4508 }
4509
4510 create_pool() {
4511     local fsname=${1%%.*}
4512     local poolname=${1##$fsname.}
4513
4514     do_facet mgs lctl pool_new $1
4515     local RC=$?
4516     # get param should return err unless pool is created
4517     [[ $RC -ne 0 ]] && return $RC
4518
4519     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
4520         2>/dev/null || echo foo" "" || RC=1
4521     if [[ $RC -eq 0 ]]; then
4522         add_pool_to_list $1
4523     else
4524         error "pool_new failed $1"
4525     fi
4526     return $RC
4527 }
4528
4529 add_pool_to_list () {
4530     local fsname=${1%%.*}
4531     local poolname=${1##$fsname.}
4532
4533     local listvar=${fsname}_CREATED_POOLS
4534     eval export ${listvar}=$(expand_list ${!listvar} $poolname)
4535 }
4536
4537 remove_pool_from_list () {
4538     local fsname=${1%%.*}
4539     local poolname=${1##$fsname.}
4540
4541     local listvar=${fsname}_CREATED_POOLS
4542     eval export ${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
4543 }
4544
4545 destroy_pool_int() {
4546     local ost
4547     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
4548         awk '$1 !~ /^Pool:/ {print $1}')
4549     for ost in $OSTS; do
4550         do_facet mgs lctl pool_remove $1 $ost
4551     done
4552     do_facet mgs lctl pool_destroy $1
4553 }
4554
4555 # <fsname>.<poolname> or <poolname>
4556 destroy_pool() {
4557     local fsname=${1%%.*}
4558     local poolname=${1##$fsname.}
4559
4560     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
4561
4562     local RC
4563
4564     pool_list $fsname.$poolname || return $?
4565
4566     destroy_pool_int $fsname.$poolname
4567     RC=$?
4568     [[ $RC -ne 0 ]] && return $RC
4569
4570     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
4571       2>/dev/null || echo foo" "foo" || RC=1
4572
4573     if [[ $RC -eq 0 ]]; then
4574         remove_pool_from_list $fsname.$poolname
4575     else
4576         error "destroy pool failed $1"
4577     fi
4578     return $RC
4579 }
4580
4581 destroy_pools () {
4582     local fsname=${1:-$FSNAME}
4583     local poolname
4584     local listvar=${fsname}_CREATED_POOLS
4585
4586     pool_list $fsname
4587
4588     [ x${!listvar} = x ] && return 0
4589
4590     echo destroy the created pools: ${!listvar}
4591     for poolname in ${!listvar//,/ }; do
4592         destroy_pool $fsname.$poolname
4593     done
4594 }
4595
4596 cleanup_pools () {
4597     local fsname=${1:-$FSNAME}
4598     trap 0
4599     destroy_pools $fsname
4600 }
4601
4602 gather_logs () {
4603     local list=$1
4604
4605     local ts=$(date +%s)
4606     local docp=true
4607
4608     if [[ ! -f "$YAML_LOG" ]]; then
4609         # init_logging is not performed before gather_logs,
4610         # so the $LOGDIR needs to be checked here
4611         check_shared_dir $LOGDIR && touch $LOGDIR/shared
4612     fi
4613
4614     [ -f $LOGDIR/shared ] && docp=false
4615
4616     # dump lustre logs, dmesg
4617
4618     prefix="$TESTLOG_PREFIX.$TESTNAME"
4619     suffix="$ts.log"
4620     echo "Dumping lctl log to ${prefix}.*.${suffix}"
4621
4622     if [ "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
4623         echo "Dumping logs only on local client."
4624         $LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}
4625         dmesg > ${prefix}.dmesg.$(hostname -s).${suffix}
4626         return
4627     fi
4628
4629     do_nodesv $list \
4630         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname -s).${suffix};
4631          dmesg > ${prefix}.dmesg.\\\$(hostname -s).${suffix}"
4632     if [ ! -f $LOGDIR/shared ]; then
4633         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
4634     fi
4635 }
4636
4637 do_ls () {
4638     local mntpt_root=$1
4639     local num_mntpts=$2
4640     local dir=$3
4641     local i
4642     local cmd
4643     local pids
4644     local rc=0
4645
4646     for i in $(seq 0 $num_mntpts); do
4647         cmd="ls -laf ${mntpt_root}$i/$dir"
4648         echo + $cmd;
4649         $cmd > /dev/null &
4650         pids="$pids $!"
4651     done
4652     echo pids=$pids
4653     for pid in $pids; do
4654         wait $pid || rc=$?
4655     done
4656
4657     return $rc
4658 }
4659
4660 # target_start_and_reset_recovery_timer()
4661 #        service_time = at_est2timeout(service_time);
4662 #        service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC +
4663 #                             INITIAL_CONNECT_TIMEOUT);
4664 # CONNECTION_SWITCH_MAX : min(25U, max(CONNECTION_SWITCH_MIN,obd_timeout))
4665 #define CONNECTION_SWITCH_INC 1
4666 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
4667 #define CONNECTION_SWITCH_MIN 5U
4668
4669 max_recovery_time () {
4670     local init_connect_timeout=$(( TIMEOUT / 20 ))
4671     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
4672
4673     local service_time=$(( $(at_max_get client) + $(( 2 * $(( 25 + 1  + init_connect_timeout)) )) ))
4674
4675     echo $service_time 
4676 }
4677
4678 get_clients_mount_count () {
4679     local clients=${CLIENTS:-`hostname`}
4680
4681     # we need to take into account the clients mounts and
4682     # exclude mds/ost mounts if any;
4683     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
4684 }
4685
4686 # gss functions
4687 PROC_CLI="srpc_info"
4688
4689 combination()
4690 {
4691     local M=$1
4692     local N=$2
4693     local R=1
4694
4695     if [ $M -lt $N ]; then
4696         R=0
4697     else
4698         N=$((N + 1))
4699         while [ $N -lt $M ]; do
4700             R=$((R * N))
4701             N=$((N + 1))
4702         done
4703     fi
4704
4705     echo $R
4706     return 0
4707 }
4708
4709 calc_connection_cnt() {
4710     local dir=$1
4711
4712     # MDT->MDT = 2 * C(M, 2)
4713     # MDT->OST = M * O
4714     # CLI->OST = C * O
4715     # CLI->MDT = C * M
4716     comb_m2=$(combination $MDSCOUNT 2)
4717
4718     local num_clients=$(get_clients_mount_count)
4719
4720     local cnt_mdt2mdt=$((comb_m2 * 2))
4721     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
4722     local cnt_cli2ost=$((num_clients * OSTCOUNT))
4723     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
4724     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
4725     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
4726     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
4727
4728     local var=cnt_$dir
4729     local res=${!var}
4730
4731     echo $res
4732 }
4733
4734 set_rule()
4735 {
4736     local tgt=$1
4737     local net=$2
4738     local dir=$3
4739     local flavor=$4
4740     local cmd="$tgt.srpc.flavor"
4741
4742     if [ $net == "any" ]; then
4743         net="default"
4744     fi
4745     cmd="$cmd.$net"
4746
4747     if [ $dir != "any" ]; then
4748         cmd="$cmd.$dir"
4749     fi
4750
4751     cmd="$cmd=$flavor"
4752     log "Setting sptlrpc rule: $cmd"
4753     do_facet mgs "$LCTL conf_param $cmd"
4754 }
4755
4756 count_flvr()
4757 {
4758     local output=$1
4759     local flavor=$2
4760     local count=0
4761
4762     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
4763     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
4764
4765     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
4766
4767     if [ "x$bulkspec" != "x" ]; then
4768         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
4769
4770         if [ "x$algs" != "x" ]; then
4771             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
4772         else
4773             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
4774             if [ $bulk == "bulkn" ]; then
4775                 bulk_count=`echo "$output" | grep "bulk flavor" \
4776                             | grep "null/null" | wc -l`
4777             elif [ $bulk == "bulki" ]; then
4778                 bulk_count=`echo "$output" | grep "bulk flavor" \
4779                             | grep "/null" | grep -v "null/" | wc -l`
4780             else
4781                 bulk_count=`echo "$output" | grep "bulk flavor" \
4782                             | grep -v "/null" | grep -v "null/" | wc -l`
4783             fi
4784         fi
4785
4786         [ $bulk_count -lt $count ] && count=$bulk_count
4787     fi
4788
4789     echo $count
4790 }
4791
4792 flvr_cnt_cli2mdt()
4793 {
4794     local flavor=$1
4795     local cnt
4796
4797     local clients=${CLIENTS:-`hostname`}
4798
4799     for c in ${clients//,/ }; do
4800         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
4801         tmpcnt=`count_flvr "$output" $flavor`
4802         cnt=$((cnt + tmpcnt))
4803     done
4804     echo $cnt
4805 }
4806
4807 flvr_cnt_cli2ost()
4808 {
4809     local flavor=$1
4810     local cnt
4811
4812     local clients=${CLIENTS:-`hostname`}
4813
4814     for c in ${clients//,/ }; do
4815         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
4816         tmpcnt=`count_flvr "$output" $flavor`
4817         cnt=$((cnt + tmpcnt))
4818     done
4819     echo $cnt
4820 }
4821
4822 flvr_cnt_mdt2mdt()
4823 {
4824     local flavor=$1
4825     local cnt=0
4826
4827     if [ $MDSCOUNT -le 1 ]; then
4828         echo 0
4829         return
4830     fi
4831
4832     for num in `seq $MDSCOUNT`; do
4833         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
4834         tmpcnt=`count_flvr "$output" $flavor`
4835         cnt=$((cnt + tmpcnt))
4836     done
4837     echo $cnt;
4838 }
4839
4840 flvr_cnt_mdt2ost()
4841 {
4842     local flavor=$1
4843     local cnt=0
4844     local mdtosc
4845
4846     for num in `seq $MDSCOUNT`; do
4847         mdtosc=$(get_mdtosc_proc_path mds$num)
4848         mdtosc=${mdtosc/-MDT*/-MDT\*}
4849         output=$(do_facet mds$num lctl get_param -n \
4850             osc.$mdtosc.$PROC_CLI 2>/dev/null)
4851         tmpcnt=`count_flvr "$output" $flavor`
4852         cnt=$((cnt + tmpcnt))
4853     done
4854     echo $cnt;
4855 }
4856
4857 flvr_cnt_mgc2mgs()
4858 {
4859     local flavor=$1
4860
4861     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
4862     count_flvr "$output" $flavor
4863 }
4864
4865 do_check_flavor()
4866 {
4867     local dir=$1        # from to
4868     local flavor=$2     # flavor expected
4869     local res=0
4870
4871     if [ $dir == "cli2mdt" ]; then
4872         res=`flvr_cnt_cli2mdt $flavor`
4873     elif [ $dir == "cli2ost" ]; then
4874         res=`flvr_cnt_cli2ost $flavor`
4875     elif [ $dir == "mdt2mdt" ]; then
4876         res=`flvr_cnt_mdt2mdt $flavor`
4877     elif [ $dir == "mdt2ost" ]; then
4878         res=`flvr_cnt_mdt2ost $flavor`
4879     elif [ $dir == "all2ost" ]; then
4880         res1=`flvr_cnt_mdt2ost $flavor`
4881         res2=`flvr_cnt_cli2ost $flavor`
4882         res=$((res1 + res2))
4883     elif [ $dir == "all2mdt" ]; then
4884         res1=`flvr_cnt_mdt2mdt $flavor`
4885         res2=`flvr_cnt_cli2mdt $flavor`
4886         res=$((res1 + res2))
4887     elif [ $dir == "all2all" ]; then
4888         res1=`flvr_cnt_mdt2ost $flavor`
4889         res2=`flvr_cnt_cli2ost $flavor`
4890         res3=`flvr_cnt_mdt2mdt $flavor`
4891         res4=`flvr_cnt_cli2mdt $flavor`
4892         res=$((res1 + res2 + res3 + res4))
4893     fi
4894
4895     echo $res
4896 }
4897
4898 wait_flavor()
4899 {
4900     local dir=$1        # from to
4901     local flavor=$2     # flavor expected
4902     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
4903
4904     local res=0
4905
4906     for ((i=0;i<20;i++)); do
4907         echo -n "checking $dir..."
4908         res=$(do_check_flavor $dir $flavor)
4909         echo "found $res/$expect $flavor connections"
4910         [ $res -ge $expect ] && return 0
4911         sleep 4
4912     done
4913
4914     echo "Error checking $flavor of $dir: expect $expect, actual $res"
4915     return 1
4916 }
4917
4918 restore_to_default_flavor()
4919 {
4920     local proc="mgs.MGS.live.$FSNAME"
4921
4922     echo "restoring to default flavor..."
4923
4924     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
4925
4926     # remove all existing rules if any
4927     if [ $nrule -ne 0 ]; then
4928         echo "$nrule existing rules"
4929         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
4930             echo "remove rule: $rule"
4931             spec=`echo $rule | awk -F = '{print $1}'`
4932             do_facet mgs "$LCTL conf_param -d $spec"
4933         done
4934     fi
4935
4936     # verify no rules left
4937     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
4938     [ $nrule -ne 0 ] && error "still $nrule rules left"
4939
4940     # wait for default flavor to be applied
4941     # currently default flavor for all connections are 'null'
4942     wait_flavor all2all null
4943     echo "now at default flavor settings"
4944 }
4945
4946 set_flavor_all()
4947 {
4948     local flavor=${1:-null}
4949
4950     echo "setting all flavor to $flavor"
4951
4952     # FIXME need parameter to this fn
4953     # and remove global vars
4954     local cnt_all2all=$(calc_connection_cnt all2all)
4955
4956     local res=$(do_check_flavor all2all $flavor)
4957     if [ $res -eq $cnt_all2all ]; then
4958         echo "already have total $res $flavor connections"
4959         return
4960     fi
4961
4962     echo "found $res $flavor out of total $cnt_all2all connections"
4963     restore_to_default_flavor
4964
4965     [[ $flavor = null ]] && return 0
4966
4967     set_rule $FSNAME any any $flavor
4968     wait_flavor all2all $flavor
4969 }
4970
4971
4972 check_logdir() {
4973     local dir=$1
4974     # Checking for shared logdir
4975     if [ ! -d $dir ]; then
4976         # Not found. Create local logdir
4977         mkdir -p $dir
4978     else
4979         touch $dir/check_file.$(hostname -s)
4980     fi
4981     return 0
4982 }
4983
4984 check_write_access() {
4985     local dir=$1
4986     local node
4987     local file
4988
4989     for node in $(nodes_list); do
4990         file=$dir/check_file.$(short_hostname $node)
4991         if [[ ! -f "$file" ]]; then
4992             # Logdir not accessible/writable from this node.
4993             return 1
4994         fi
4995         rm -f $file || return 1
4996     done
4997     return 0
4998 }
4999
5000 init_logging() {
5001     if [[ -n $YAML_LOG ]]; then
5002         return
5003     fi
5004     local SAVE_UMASK=`umask`
5005     umask 0000
5006
5007     export YAML_LOG=${LOGDIR}/results.yml
5008     mkdir -p $LOGDIR
5009     init_clients_lists
5010
5011     if [ ! -f $YAML_LOG ]; then       # If the yaml log already exists then we will just append to it
5012       if check_shared_dir $LOGDIR; then
5013           touch $LOGDIR/shared
5014           echo "Logging to shared log directory: $LOGDIR"
5015       else
5016           echo "Logging to local directory: $LOGDIR"
5017       fi
5018
5019       yml_nodes_file $LOGDIR >> $YAML_LOG
5020       yml_results_file >> $YAML_LOG
5021     fi
5022
5023     umask $SAVE_UMASK
5024 }
5025
5026 log_test() {
5027     yml_log_test $1 >> $YAML_LOG
5028 }
5029
5030 log_test_status() {
5031      yml_log_test_status $@ >> $YAML_LOG
5032 }
5033
5034 log_sub_test_begin() {
5035     yml_log_sub_test_begin "$@" >> $YAML_LOG
5036 }
5037
5038 log_sub_test_end() {
5039     yml_log_sub_test_end "$@" >> $YAML_LOG
5040 }
5041
5042 run_llverdev()
5043 {
5044         local dev=$1
5045         local llverdev_opts=$2
5046         local devname=$(basename $1)
5047         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
5048         # loop devices aren't in /proc/partitions
5049         [ "x$size" == "x" ] && local size=$(ls -l $dev | awk '{print $5}')
5050
5051         size=$(($size / 1024 / 1024)) # Gb
5052
5053         local partial_arg=""
5054         # Run in partial (fast) mode if the size
5055         # of a partition > 1 GB
5056         [ $size -gt 1 ] && partial_arg="-p"
5057
5058         llverdev --force $partial_arg $llverdev_opts $dev
5059 }
5060
5061 run_llverfs()
5062 {
5063         local dir=$1
5064         local llverfs_opts=$2
5065         local partial_arg=""
5066         local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB
5067
5068         # Run in partial (fast) mode if the size
5069         # of a partition > 1 GB
5070         [ $size -gt 1 ] && partial_arg="-p"
5071
5072         llverfs $partial_arg $llverfs_opts $dir
5073 }
5074
5075 remove_mdt_files() {
5076         local facet=$1
5077         local mdtdev=$2
5078         shift 2
5079         local files="$@"
5080         local mntpt=$(facet_mntpt $facet)
5081         local opts=$MDS_MOUNT_OPTS
5082
5083         echo "removing files from $mdtdev on $facet: $files"
5084         if [ $(facet_fstype $facet) == ldiskfs ] &&
5085            ! do_facet $facet test -b ${!dev}; then
5086                 opts=$(csa_add "$opts" -o loop)
5087         fi
5088         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
5089                 return $?
5090         rc=0;
5091         for f in $files; do
5092                 rm $mntpt/ROOT/$f || { rc=$?; break; }
5093         done
5094         umount -f $mntpt || return $?
5095         return $rc
5096 }
5097
5098 duplicate_mdt_files() {
5099         local facet=$1
5100         local mdtdev=$2
5101         shift 2
5102         local files="$@"
5103         local mntpt=$(facet_mntpt $facet)
5104         local opts=$MDS_MOUNT_OPTS
5105
5106         echo "duplicating files on $mdtdev on $facet: $files"
5107         mkdir -p $mntpt || return $?
5108         if [ $(facet_fstype $facet) == ldiskfs ] &&
5109            ! do_facet $facet test -b ${!dev}; then
5110                 opts=$(csa_add "$opts" -o loop)
5111         fi
5112         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
5113                 return $?
5114
5115     do_umount() {
5116         trap 0
5117         popd > /dev/null
5118         rm $tmp
5119         umount -f $mntpt
5120     }
5121     trap do_umount EXIT
5122
5123     tmp=$(mktemp $TMP/setfattr.XXXXXXXXXX)
5124     pushd $mntpt/ROOT > /dev/null || return $?
5125     rc=0
5126     for f in $files; do
5127         touch $f.bad || return $?
5128         getfattr -n trusted.lov $f | sed "s#$f#&.bad#" > $tmp
5129         rc=${PIPESTATUS[0]}
5130         [ $rc -eq 0 ] || return $rc
5131         setfattr --restore $tmp || return $?
5132     done
5133     do_umount
5134 }
5135
5136 run_sgpdd () {
5137     local devs=${1//,/ }
5138     shift
5139     local params=$@
5140     local rslt=$TMP/sgpdd_survey
5141
5142     # sgpdd-survey cleanups ${rslt}.* files
5143
5144     local cmd="rslt=$rslt $params scsidevs=\"$devs\" $SGPDDSURVEY"
5145     echo + $cmd
5146     eval $cmd
5147     cat ${rslt}.detail
5148 }
5149
5150 # returns the canonical name for an ldiskfs device
5151 ldiskfs_canon() {
5152         local dev="$1"
5153         local facet="$2"
5154
5155         do_facet $facet "dv=\\\$(lctl get_param -n $dev);
5156 if foo=\\\$(lvdisplay -c \\\$dv 2>/dev/null); then
5157     echo dm-\\\${foo##*:};
5158 else
5159     echo \\\$(basename \\\$dv);
5160 fi;"
5161 }
5162
5163 is_sanity_benchmark() {
5164     local benchmarks="dbench bonnie iozone fsx"
5165     local suite=$1
5166     for b in $benchmarks; do
5167         if [ "$b" == "$suite" ]; then
5168             return 0
5169         fi
5170     done
5171     return 1
5172 }
5173
5174 min_ost_size () {
5175     $LCTL get_param -n osc.*.kbytesavail | sort -n | head -n1
5176 }
5177
5178 # Get the block size of the filesystem.
5179 get_block_size() {
5180     local facet=$1
5181     local device=$2
5182     local size
5183
5184     size=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
5185            awk '/^Block size:/ {print $3}')
5186     echo $size
5187 }
5188
5189 # Check whether the "large_xattr" feature is enabled or not.
5190 large_xattr_enabled() {
5191     local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
5192
5193     do_facet $SINGLEMDS "$DUMPE2FS -h $mds_dev 2>&1 | grep -q large_xattr"
5194     return ${PIPESTATUS[0]}
5195 }
5196
5197 # Get the maximum xattr size supported by the filesystem.
5198 max_xattr_size() {
5199     local size
5200
5201     if large_xattr_enabled; then
5202         # include/linux/limits.h: #define XATTR_SIZE_MAX 65536
5203         size=65536
5204     else
5205         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
5206         local block_size=$(get_block_size $SINGLEMDS $mds_dev)
5207
5208         # maximum xattr size = size of block - size of header -
5209         #                      size of 1 entry - 4 null bytes
5210         size=$((block_size - 32 - 32 - 4))
5211     fi
5212
5213     echo $size
5214 }
5215
5216 # Dump the value of the named xattr from a file.
5217 get_xattr_value() {
5218     local xattr_name=$1
5219     local file=$2
5220
5221     echo "$(getfattr -n $xattr_name --absolute-names --only-values $file)"
5222 }
5223
5224 # Generate a string with size of $size bytes.
5225 generate_string() {
5226     local size=${1:-1024} # in bytes
5227
5228     echo "$(head -c $size < /dev/zero | tr '\0' y)"
5229 }