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