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