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