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