Whamcloud - gitweb
b=22402 new OBDFILTER_SURVEY test suite
[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=$PATH:$LUSTRE/tests
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
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 ${fsname}-MDT*.mdd.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 ${!varsvc}.ost.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 shudown_node_hard () {
863     local host=$1
864     local attempts=3
865
866     for i in $(seq $attempts) ; do
867         $POWER_DOWN $host
868         sleep 1
869         ping -w 3 -c 1 $host > /dev/null 2>&1 || return 0
870         echo "waiting for $host to fail attempts=$attempts"
871         [ $i -lt $attempts ] || \
872             { echo "$host still pingable after power down! attempts=$attempts" && return 1; } 
873     done
874 }
875
876 shutdown_client() {
877     local client=$1
878     local mnt=${2:-$MOUNT}
879     local attempts=3
880
881     if [ "$FAILURE_MODE" = HARD ]; then
882         shudown_node_hard $client 
883     else
884        zconf_umount_clients $client $mnt -f
885     fi
886 }
887
888 shutdown_facet() {
889     local facet=$1
890     if [ "$FAILURE_MODE" = HARD ]; then
891         shudown_node_hard $(facet_active_host $facet)
892     elif [ "$FAILURE_MODE" = SOFT ]; then
893         stop $facet
894     fi
895 }
896
897 remount_facet() {
898     local facet=$1
899
900     stop $facet
901     mount_facet $facet
902 }
903
904 reboot_facet() {
905     facet=$1
906     if [ "$FAILURE_MODE" = HARD ]; then
907         $POWER_UP `facet_active_host $facet`
908     else
909         sleep 10
910     fi
911 }
912
913 boot_node() {
914     local node=$1
915     if [ "$FAILURE_MODE" = HARD ]; then
916        $POWER_UP $node
917        wait_for_host $node
918     fi
919 }
920
921 # recovery-scale functions
922 check_progs_installed () {
923     local clients=$1
924     shift
925     local progs=$@
926
927     do_nodes $clients "PATH=:$PATH; status=true;
928 for prog in $progs; do
929     if ! [ \\\"\\\$(which \\\$prog)\\\"  -o  \\\"\\\${!prog}\\\" ]; then
930        echo \\\$prog missing on \\\$(hostname);
931        status=false;
932     fi
933 done;
934 eval \\\$status"
935 }
936
937 client_var_name() {
938     echo __$(echo $1 | tr '-' 'X')
939 }
940
941 start_client_load() {
942     local client=$1
943     local load=$2
944     local var=$(client_var_name $client)_load
945     eval export ${var}=$load
946
947     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
948                               BREAK_ON_ERROR=$BREAK_ON_ERROR \
949                               END_RUN_FILE=$END_RUN_FILE \
950                               LOAD_PID_FILE=$LOAD_PID_FILE \
951                               TESTSUITELOG=$TESTSUITELOG \
952                               run_${load}.sh" &
953     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $!"
954     log "Started client load: ${load} on $client"
955
956     return 0
957 }
958
959 start_client_loads () {
960     local -a clients=(${1//,/ })
961     local numloads=${#CLIENT_LOADS[@]}
962     local testnum
963
964     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
965         testnum=$((nodenum % numloads))
966         start_client_load ${clients[nodenum]} ${CLIENT_LOADS[testnum]}
967     done
968     # bug 22169: wait the background threads to start
969     sleep 2
970 }
971
972 # only for remote client 
973 check_client_load () {
974     local client=$1
975     local var=$(client_var_name $client)_load
976     local TESTLOAD=run_${!var}.sh
977
978     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
979     
980     # bug 18914: try to connect several times not only when
981     # check ps, but  while check_catastrophe also
982     local tries=3
983     local RC=254
984     while [ $RC = 254 -a $tries -gt 0 ]; do
985         let tries=$tries-1
986         # assume success
987         RC=0
988         if ! check_catastrophe $client; then
989             RC=${PIPESTATUS[0]}
990             if [ $RC -eq 254 ]; then
991                 # FIXME: not sure how long we shuold sleep here
992                 sleep 10
993                 continue
994             fi
995             echo "check catastrophe failed: RC=$RC "
996             return $RC
997         fi
998     done
999     # We can continue try to connect if RC=254
1000     # Just print the warning about this
1001     if [ $RC = 254 ]; then
1002         echo "got a return status of $RC from do_node while checking catastrophe on $client"
1003     fi
1004
1005     # see if the load is still on the client
1006     tries=3
1007     RC=254
1008     while [ $RC = 254 -a $tries -gt 0 ]; do
1009         let tries=$tries-1
1010         # assume success
1011         RC=0
1012         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
1013             RC=${PIPESTATUS[0]}
1014             sleep 30
1015         fi
1016     done
1017     if [ $RC = 254 ]; then
1018         echo "got a return status of $RC from do_node while checking (catastrophe and 'ps') the client load on $client"
1019         # see if we can diagnose a bit why this is
1020     fi
1021
1022     return $RC
1023 }
1024 check_client_loads () {
1025    local clients=${1//,/ }
1026    local client=
1027    local rc=0
1028
1029    for client in $clients; do
1030       check_client_load $client
1031       rc=${PIPESTATUS[0]}
1032       if [ "$rc" != 0 ]; then
1033         log "Client load failed on node $client, rc=$rc"
1034         return $rc
1035       fi
1036    done
1037 }
1038
1039 restart_client_loads () {
1040     local clients=${1//,/ }
1041     local expectedfail=${2:-""}
1042     local client=
1043     local rc=0
1044
1045     for client in $clients; do
1046         check_client_load $client
1047         rc=${PIPESTATUS[0]}
1048         if [ "$rc" != 0 -a "$expectedfail" ]; then
1049             local var=$(client_var_name $client)_load
1050             start_client_load $client ${!var}
1051             echo "Restarted client load ${!var}: on $client. Checking ..."
1052             check_client_load $client
1053             rc=${PIPESTATUS[0]}
1054             if [ "$rc" != 0 ]; then
1055                 log "Client load failed to restart on node $client, rc=$rc"
1056                 # failure one client load means test fail
1057                 # we do not need to check other 
1058                 return $rc
1059             fi
1060         else
1061             return $rc
1062         fi
1063     done
1064 }
1065 # End recovery-scale functions
1066
1067 # verify that lustre actually cleaned up properly
1068 cleanup_check() {
1069     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
1070         error "LBUG/LASSERT detected"
1071     BUSY=`dmesg | grep -i destruct || true`
1072     if [ "$BUSY" ]; then
1073         echo "$BUSY" 1>&2
1074         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
1075         exit 205
1076     fi
1077
1078     check_mem_leak || exit 204
1079
1080     [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl && \
1081         echo "$0: lustre didn't clean up..." 1>&2 && return 202 || true
1082
1083     if module_loaded lnet || module_loaded libcfs; then
1084         echo "$0: modules still loaded..." 1>&2
1085         /sbin/lsmod 1>&2
1086         return 203
1087     fi
1088     return 0
1089 }
1090
1091 wait_update () {
1092     local node=$1
1093     local TEST=$2
1094     local FINAL=$3
1095     local MAX=${4:-90}
1096
1097         local RESULT
1098         local WAIT=0
1099         local sleep=5
1100         while [ true ]; do
1101             RESULT=$(do_node $node "$TEST")
1102             if [ "$RESULT" == "$FINAL" ]; then
1103                 echo "Updated after $WAIT sec: wanted '$FINAL' got '$RESULT'"
1104                 return 0
1105             fi
1106             [ $WAIT -ge $MAX ] && break
1107             echo "Waiting $((MAX - WAIT)) secs for update"
1108             WAIT=$((WAIT + sleep))
1109             sleep $sleep
1110         done
1111         echo "Update not seen after $MAX sec: wanted '$FINAL' got '$RESULT'"
1112         return 3
1113 }
1114
1115 wait_update_facet () {
1116     local facet=$1
1117     wait_update  $(facet_active_host $facet) "$@"
1118 }
1119
1120 wait_delete_completed () {
1121     local TOTALPREV=`lctl get_param -n osc.*.kbytesavail | \
1122                      awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1123
1124     local WAIT=0
1125     local MAX_WAIT=20
1126     while [ "$WAIT" -ne "$MAX_WAIT" ]; do
1127         sleep 1
1128         TOTAL=`lctl get_param -n osc.*.kbytesavail | \
1129                awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1130         [ "$TOTAL" -eq "$TOTALPREV" ] && return 0
1131         echo "Waiting delete completed ... prev: $TOTALPREV current: $TOTAL "
1132         TOTALPREV=$TOTAL
1133         WAIT=$(( WAIT + 1))
1134     done
1135     echo "Delete is not completed in $MAX_WAIT sec"
1136     return 1
1137 }
1138
1139 wait_for_host() {
1140     local host=$1
1141     check_network "$host" 900
1142     while ! do_node $host hostname  > /dev/null; do sleep 5; done
1143 }
1144
1145 wait_for() {
1146     local facet=$1
1147     local host=`facet_active_host $facet`
1148     wait_for_host $host
1149 }
1150
1151 wait_recovery_complete () {
1152     local facet=$1
1153
1154     # Use default policy if $2 is not passed by caller.
1155     local MAX=${2:-$(max_recovery_time)}
1156
1157     local var_svc=${facet}_svc
1158     local procfile="*.${!var_svc}.recovery_status"
1159     local WAIT=0
1160     local STATUS=
1161
1162     while [ $WAIT -lt $MAX ]; do
1163         STATUS=$(do_facet $facet lctl get_param -n $procfile | grep status)
1164         [[ $STATUS = "status: COMPLETE" ]] && return 0
1165         sleep 5
1166         WAIT=$((WAIT + 5))
1167         echo "Waiting $((MAX - WAIT)) secs for $facet recovery done. $STATUS"
1168     done
1169     echo "$facet recovery not done in $MAX sec. $STATUS"
1170     return 1
1171 }
1172
1173 wait_mds_ost_sync () {
1174     # just because recovery is done doesn't mean we've finished
1175     # orphan cleanup. Wait for llogs to get synchronized.
1176     echo "Waiting for orphan cleanup..."
1177     # MAX value includes time needed for MDS-OST reconnection
1178     local MAX=$(( TIMEOUT * 2 ))
1179     local WAIT=0
1180     while [ $WAIT -lt $MAX ]; do
1181         local -a sync=($(do_nodes $(comma_list $(osts_nodes)) \
1182             "$LCTL get_param -n obdfilter.*.mds_sync"))
1183         local con=1
1184         local i
1185         for ((i=0; i<${#sync[@]}; i++)); do
1186             [ ${sync[$i]} -eq 0 ] && continue
1187             # there is a not finished MDS-OST synchronization
1188             con=0
1189             break;
1190         done
1191         sleep 2 # increase waiting time and cover statfs cache
1192         [ ${con} -eq 1 ] && return 0
1193         echo "Waiting $WAIT secs for $facet mds-ost sync done."
1194         WAIT=$((WAIT + 2))
1195     done
1196     echo "$facet recovery not done in $MAX sec. $STATUS"
1197     return 1
1198 }
1199
1200 wait_destroy_complete () {
1201     echo "Waiting for destroy to be done..."
1202     # MAX value shouldn't be big as this mean server responsiveness
1203     # never increase this just to make test pass but investigate
1204     # why it takes so long time
1205     local MAX=5
1206     local WAIT=0
1207     while [ $WAIT -lt $MAX ]; do
1208         local -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))
1209         local con=1
1210         for ((i=0; i<${#RPCs[@]}; i++)); do
1211             [ ${RPCs[$i]} -eq 0 ] && continue
1212             # there are still some destroy RPCs in flight
1213             con=0
1214             break;
1215         done
1216         sleep 1
1217         [ ${con} -eq 1 ] && return 0 # done waiting
1218         echo "Waiting $WAIT secs for destroys to be done."
1219         WAIT=$((WAIT + 1))
1220     done
1221     echo "Destroys weren't done in $MAX sec."
1222     return 1
1223 }
1224
1225 wait_exit_ST () {
1226     local facet=$1
1227
1228     local WAIT=0
1229     local INTERVAL=1
1230     local running
1231     # conf-sanity 31 takes a long time cleanup
1232     while [ $WAIT -lt 300 ]; do
1233         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
1234         [ -z "${running}" ] && return 0
1235         echo "waited $WAIT for${running}"
1236         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
1237         sleep $INTERVAL
1238         WAIT=$((WAIT + INTERVAL))
1239     done
1240     echo "service didn't stop after $WAIT seconds.  Still running:"
1241     echo ${running}
1242     return 1
1243 }
1244
1245 wait_remote_prog () {
1246    local prog=$1
1247    local WAIT=0
1248    local INTERVAL=5
1249    local rc=0
1250
1251    [ "$PDSH" = "no_dsh" ] && return 0
1252
1253    while [ $WAIT -lt $2 ]; do
1254         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
1255         [ -z "${running}" ] && return 0 || true
1256         echo "waited $WAIT for: "
1257         echo "$running"
1258         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
1259         sleep $INTERVAL
1260         WAIT=$((WAIT + INTERVAL))
1261     done
1262     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
1263     [ -z "$pids" ] && return 0
1264     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
1265     # FIXME: not portable
1266     for pid in $pids; do
1267         cat /proc/${pid}/status || true
1268         cat /proc/${pid}/wchan || true
1269         echo "Killing $pid"
1270         kill -9 $pid || true
1271         sleep 1
1272         ps -P $pid && rc=1
1273     done
1274
1275     return $rc
1276 }
1277
1278 clients_up() {
1279     # not every config has many clients
1280     sleep 1
1281     if [ ! -z "$CLIENTS" ]; then
1282         $PDSH $CLIENTS "stat -f $MOUNT" > /dev/null
1283     else
1284         stat -f $MOUNT > /dev/null
1285     fi
1286 }
1287
1288 client_up() {
1289     local client=$1
1290     # usually checked on particular client or locally
1291     sleep 1
1292     if [ ! -z "$client" ]; then
1293         $PDSH $client "stat -f $MOUNT" > /dev/null
1294     else
1295         stat -f $MOUNT > /dev/null
1296     fi
1297 }
1298
1299 client_evicted() {
1300     ! client_up $1
1301 }
1302
1303 client_reconnect() {
1304     uname -n >> $MOUNT/recon
1305     if [ -z "$CLIENTS" ]; then
1306         df $MOUNT; uname -n >> $MOUNT/recon
1307     else
1308         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
1309     fi
1310     echo Connected clients:
1311     cat $MOUNT/recon
1312     ls -l $MOUNT/recon > /dev/null
1313     rm $MOUNT/recon
1314 }
1315
1316 facet_failover() {
1317     local facet=$1
1318     local sleep_time=$2
1319     echo "Failing $facet on node `facet_active_host $facet`"
1320     shutdown_facet $facet
1321     [ -n "$sleep_time" ] && sleep $sleep_time
1322     reboot_facet $facet
1323     change_active $facet
1324     local TO=`facet_active_host $facet`
1325     echo "Failover $facet to $TO"
1326     wait_for $facet
1327     mount_facet $facet || error "Restart of $facet failed"
1328 }
1329
1330 obd_name() {
1331     local facet=$1
1332 }
1333
1334 replay_barrier() {
1335     local facet=$1
1336     do_facet $facet sync
1337     df $MOUNT
1338     local svc=${facet}_svc
1339     do_facet $facet $LCTL --device %${!svc} notransno
1340     do_facet $facet $LCTL --device %${!svc} readonly
1341     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1342     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1343 }
1344
1345 replay_barrier_nodf() {
1346     local facet=$1    echo running=${running}
1347     do_facet $facet sync
1348     local svc=${facet}_svc
1349     echo Replay barrier on ${!svc}
1350     do_facet $facet $LCTL --device %${!svc} notransno
1351     do_facet $facet $LCTL --device %${!svc} readonly
1352     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1353     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1354 }
1355
1356 replay_barrier_nosync() {
1357     local facet=$1    echo running=${running}
1358     local svc=${facet}_svc
1359     echo Replay barrier on ${!svc}
1360     do_facet $facet $LCTL --device %${!svc} notransno
1361     do_facet $facet $LCTL --device %${!svc} readonly
1362     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1363     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1364 }
1365
1366 mds_evict_client() {
1367     UUID=`lctl get_param -n mdc.${mds1_svc}-mdc-*.uuid`
1368     do_facet mds1 "lctl set_param -n mdt.${mds1_svc}.evict_client $UUID"
1369 }
1370
1371 ost_evict_client() {
1372     UUID=`lctl get_param -n devices| grep ${ost1_svc}-osc- | egrep -v 'MDT' | awk '{print $5}'`
1373     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
1374 }
1375
1376 fail() {
1377     facet_failover $* || error "failover: $?"
1378     clients_up || error "post-failover df: $?"
1379 }
1380
1381 fail_nodf() {
1382         local facet=$1
1383         facet_failover $facet
1384 }
1385
1386 fail_abort() {
1387     local facet=$1
1388     stop $facet
1389     change_active $facet
1390     mount_facet $facet -o abort_recovery
1391     clients_up || echo "first df failed: $?"
1392     clients_up || error "post-failover df: $?"
1393 }
1394
1395 do_lmc() {
1396     echo There is no lmc.  This is mountconf, baby.
1397     exit 1
1398 }
1399
1400 h2name_or_ip() {
1401     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1402         echo $1"@$2"
1403     fi
1404 }
1405
1406 h2ptl() {
1407    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1408        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
1409        if [ -z "$ID" ]; then
1410            echo "Could not get a ptl id for $1..."
1411            exit 1
1412        fi
1413        echo $ID"@ptl"
1414    fi
1415 }
1416 declare -fx h2ptl
1417
1418 h2tcp() {
1419     h2name_or_ip "$1" "tcp"
1420 }
1421 declare -fx h2tcp
1422
1423 h2elan() {
1424     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1425         if type __h2elan >/dev/null 2>&1; then
1426             ID=$(__h2elan $1)
1427         else
1428             ID=`echo $1 | sed 's/[^0-9]*//g'`
1429         fi
1430         echo $ID"@elan"
1431     fi
1432 }
1433 declare -fx h2elan
1434
1435 h2openib() {
1436     h2name_or_ip "$1" "openib"
1437 }
1438 declare -fx h2openib
1439
1440 h2o2ib() {
1441     h2name_or_ip "$1" "o2ib"
1442 }
1443 declare -fx h2o2ib
1444
1445 facet_host() {
1446     local facet=$1
1447
1448     [ "$facet" == client ] && echo -n $HOSTNAME && return
1449     varname=${facet}_HOST
1450     if [ -z "${!varname}" ]; then
1451         if [ "${facet:0:3}" == "ost" ]; then
1452             eval ${facet}_HOST=${ost_HOST}
1453         fi
1454     fi
1455     echo -n ${!varname}
1456 }
1457
1458 facet_active() {
1459     local facet=$1
1460     local activevar=${facet}active
1461
1462     if [ -f $TMP/${facet}active ] ; then
1463         source $TMP/${facet}active
1464     fi
1465
1466     active=${!activevar}
1467     if [ -z "$active" ] ; then
1468         echo -n ${facet}
1469     else
1470         echo -n ${active}
1471     fi
1472 }
1473
1474 facet_active_host() {
1475     local facet=$1
1476     local active=`facet_active $facet`
1477     if [ "$facet" == client ]; then
1478         echo $HOSTNAME
1479     else
1480         echo `facet_host $active`
1481     fi
1482 }
1483
1484 change_active() {
1485     local facet=$1
1486     local failover=${facet}failover
1487     host=`facet_host $failover`
1488     [ -z "$host" ] && return
1489     local curactive=`facet_active $facet`
1490     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
1491         eval export ${facet}active=$facet
1492     else
1493         eval export ${facet}active=$failover
1494     fi
1495     # save the active host for this facet
1496     local activevar=${facet}active
1497     echo "$activevar=${!activevar}" > $TMP/$activevar
1498 }
1499
1500 do_node() {
1501     local verbose=false
1502     # do not stripe off hostname if verbose, bug 19215
1503     if [ x$1 = x--verbose ]; then
1504         shift
1505         verbose=true
1506     fi
1507
1508     local HOST=$1
1509     shift
1510     local myPDSH=$PDSH
1511     if [ "$HOST" = "$HOSTNAME" ]; then
1512         myPDSH="no_dsh"
1513     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
1514         echo "cannot run remote command on $HOST with $myPDSH"
1515         return 128
1516     fi
1517     if $VERBOSE; then
1518         echo "CMD: $HOST $@" >&2
1519         $myPDSH $HOST $LCTL mark "$@" > /dev/null 2>&1 || :
1520     fi
1521
1522     if [ "$myPDSH" = "rsh" ]; then
1523 # we need this because rsh does not return exit code of an executed command
1524         local command_status="$TMP/cs"
1525         rsh $HOST ":> $command_status"
1526         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
1527                     cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
1528                     echo command failed >$command_status"
1529         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
1530         return 0
1531     fi
1532
1533     if $verbose ; then
1534         # print HOSTNAME for myPDSH="no_dsh"
1535         if [[ $myPDSH = no_dsh ]]; then
1536             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
1537         else
1538             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
1539         fi
1540     else
1541         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
1542     fi
1543     return ${PIPESTATUS[0]}
1544 }
1545
1546 do_nodev() {
1547     do_node --verbose "$@"
1548 }
1549
1550 single_local_node () {
1551    [ "$1" = "$HOSTNAME" ]
1552 }
1553
1554 # Outputs environment variable assignments that should be passed to remote nodes
1555 get_env_vars() {
1556     local var
1557     local value
1558
1559     for var in ${!MODOPTS_*}; do
1560         value=${!var}
1561         echo "${var}=\"$value\""
1562     done
1563 }
1564
1565 do_nodes() {
1566     local verbose=false
1567     # do not stripe off hostname if verbose, bug 19215
1568     if [ x$1 = x--verbose ]; then
1569         shift
1570         verbose=true
1571     fi
1572
1573     local rnodes=$1
1574     shift
1575
1576     if single_local_node $rnodes; then
1577         if $verbose; then
1578            do_nodev $rnodes "$@"
1579         else
1580            do_node $rnodes "$@"
1581         fi
1582         return $?
1583     fi
1584
1585     # This is part from do_node
1586     local myPDSH=$PDSH
1587
1588     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
1589         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
1590
1591     if $VERBOSE; then
1592         echo "CMD: $rnodes $@" >&2
1593         $myPDSH $rnodes $LCTL mark "$@" > /dev/null 2>&1 || :
1594     fi
1595
1596     if $verbose ; then
1597         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")"
1598     else
1599         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")" | sed -re "s/\w+:\s//g"
1600     fi
1601     return ${PIPESTATUS[0]}
1602 }
1603
1604 do_facet() {
1605     local facet=$1
1606     shift
1607     local HOST=`facet_active_host $facet`
1608     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
1609     do_node $HOST "$@"
1610 }
1611
1612 do_nodesv() {
1613     do_nodes --verbose "$@"
1614 }
1615
1616 add() {
1617     local facet=$1
1618     shift
1619     # make sure its not already running
1620     stop ${facet} -f
1621     rm -f $TMP/${facet}active
1622     do_facet ${facet} $MKFS $*
1623 }
1624
1625 ostdevname() {
1626     num=$1
1627     DEVNAME=OSTDEV$num
1628     #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
1629     eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}}
1630     echo -n $DEVPTR
1631 }
1632
1633 mdsdevname() {
1634     num=$1
1635     DEVNAME=MDSDEV$num
1636     #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
1637     eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}}
1638     echo -n $DEVPTR
1639 }
1640
1641 ########
1642 ## MountConf setup
1643
1644 stopall() {
1645     # make sure we are using the primary server, so test-framework will
1646     # be able to clean up properly.
1647     activemds=`facet_active mds1`
1648     if [ $activemds != "mds1" ]; then
1649         fail mds1
1650     fi
1651
1652     local clients=$CLIENTS
1653     [ -z $clients ] && clients=$(hostname)
1654
1655     zconf_umount_clients $clients $MOUNT "$*" || true
1656     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
1657
1658     [ "$CLIENTONLY" ] && return
1659     # The add fn does rm ${facet}active file, this would be enough
1660     # if we use do_facet <facet> only after the facet added, but
1661     # currently we use do_facet mds in local.sh
1662     for num in `seq $MDSCOUNT`; do
1663         stop mds$num -f
1664         rm -f ${TMP}/mds${num}active
1665     done
1666
1667     for num in `seq $OSTCOUNT`; do
1668         stop ost$num -f
1669         rm -f $TMP/ost${num}active
1670     done
1671
1672     if ! combined_mgs_mds ; then
1673         stop mgs
1674     fi
1675
1676     return 0
1677 }
1678
1679 cleanup_echo_devs () {
1680     local devs=$($LCTL dl | grep echo | awk '{print $4}')
1681
1682     for dev in $devs; do
1683         $LCTL --device $dev cleanup
1684         $LCTL --device $dev detach
1685     done
1686 }
1687
1688 cleanupall() {
1689     nfs_client_mode && return
1690
1691     stopall $*
1692     cleanup_echo_devs
1693
1694     unload_modules
1695     cleanup_gss
1696 }
1697
1698 mdsmkfsopts()
1699 {
1700     local nr=$1
1701     test $nr = 1 && echo -n $MDS_MKFS_OPTS || echo -n $MDSn_MKFS_OPTS
1702 }
1703
1704 combined_mgs_mds () {
1705     [[ $MDSDEV1 = $MGSDEV ]] && [[ $mds1_HOST = $mgs_HOST ]]
1706 }
1707
1708 formatall() {
1709     if [ "$IAMDIR" == "yes" ]; then
1710         MDS_MKFS_OPTS="$MDS_MKFS_OPTS --iam-dir"
1711         MDSn_MKFS_OPTS="$MDSn_MKFS_OPTS --iam-dir"
1712     fi
1713
1714     [ "$FSTYPE" ] && FSTYPE_OPT="--backfstype $FSTYPE"
1715
1716     stopall
1717     # We need ldiskfs here, may as well load them all
1718     load_modules
1719     [ "$CLIENTONLY" ] && return
1720     echo Formatting mgs, mds, osts
1721     if ! combined_mgs_mds ; then
1722         add mgs $mgs_MKFS_OPTS $FSTYPE_OPT --reformat $MGSDEV || exit 10
1723     fi
1724
1725     for num in `seq $MDSCOUNT`; do
1726         echo "Format mds$num: $(mdsdevname $num)"
1727         if $VERBOSE; then
1728             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` || exit 9
1729         else
1730             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` > /dev/null || exit 9
1731         fi
1732     done
1733
1734     for num in `seq $OSTCOUNT`; do
1735         echo "Format ost$num: $(ostdevname $num)"
1736         if $VERBOSE; then
1737             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` || exit 10
1738         else
1739             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` > /dev/null || exit 10
1740         fi
1741     done
1742 }
1743
1744 mount_client() {
1745     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
1746 }
1747
1748 umount_client() {
1749     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
1750 }
1751
1752 # return value:
1753 # 0: success, the old identity set already.
1754 # 1: success, the old identity does not set.
1755 # 2: fail.
1756 switch_identity() {
1757     local num=$1
1758     local switch=$2
1759     local j=`expr $num - 1`
1760     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
1761
1762     if [ -z "$MDT" ]; then
1763         return 2
1764     fi
1765
1766     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
1767
1768     if $switch; then
1769         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
1770     else
1771         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
1772     fi
1773
1774     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush=-1"
1775
1776     if [ $old = "NONE" ]; then
1777         return 1
1778     else
1779         return 0
1780     fi
1781 }
1782
1783 remount_client()
1784 {
1785         zconf_umount `hostname` $1 || error "umount failed"
1786         zconf_mount `hostname` $1 || error "mount failed"
1787 }
1788
1789 writeconf_facet () {
1790     local facet=$1
1791     local dev=$2
1792
1793     do_facet $facet "$TUNEFS --writeconf $dev"
1794 }
1795
1796 writeconf_all () {
1797     for num in `seq $MDSCOUNT`; do
1798         DEVNAME=$(mdsdevname $num)
1799         writeconf_facet mds$num $DEVNAME
1800     done
1801
1802     for num in `seq $OSTCOUNT`; do
1803         DEVNAME=$(ostdevname $num)
1804         writeconf_facet ost$num $DEVNAME
1805     done
1806 }
1807
1808 setupall() {
1809     nfs_client_mode && return
1810
1811     sanity_mount_check ||
1812         error "environments are insane!"
1813
1814     load_modules
1815
1816     if [ -z "$CLIENTONLY" ]; then
1817         echo Setup mgs, mdt, osts
1818         echo $WRITECONF | grep -q "writeconf" && \
1819             writeconf_all
1820         if ! combined_mgs_mds ; then
1821             start mgs $MGSDEV $mgs_MOUNT_OPTS
1822         fi
1823
1824         for num in `seq $MDSCOUNT`; do
1825             DEVNAME=$(mdsdevname $num)
1826             start mds$num $DEVNAME $MDS_MOUNT_OPTS
1827
1828             # We started mds, now we should set failover variables properly.
1829             # Set mds${num}failover_HOST if it is not set (the default failnode).
1830             local varname=mds${num}failover_HOST
1831             if [ -z "${!varname}" ]; then
1832                 eval mds${num}failover_HOST=$(facet_host mds$num)
1833             fi
1834
1835             if [ $IDENTITY_UPCALL != "default" ]; then
1836                 switch_identity $num $IDENTITY_UPCALL
1837             fi
1838         done
1839         for num in `seq $OSTCOUNT`; do
1840             DEVNAME=$(ostdevname $num)
1841             start ost$num $DEVNAME $OST_MOUNT_OPTS
1842
1843             # We started ost$num, now we should set ost${num}failover variable properly.
1844             # Set ost${num}failover_HOST if it is not set (the default failnode).
1845             varname=ost${num}failover_HOST
1846             if [ -z "${!varname}" ]; then
1847                 eval ost${num}failover_HOST=$(facet_host ost${num})
1848             fi
1849
1850         done
1851     fi
1852
1853     init_gss
1854
1855     # wait a while to allow sptlrpc configuration be propogated to targets,
1856     # only needed when mounting new target devices.
1857     if $GSS; then
1858         sleep 10
1859     fi
1860
1861     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
1862     mount_client $MOUNT
1863     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
1864
1865     if [ "$MOUNT_2" ]; then
1866         mount_client $MOUNT2
1867         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
1868     fi
1869
1870     init_param_vars
1871
1872     # by remounting mdt before ost, initial connect from mdt to ost might
1873     # timeout because ost is not ready yet. wait some time to its fully
1874     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
1875     # by a context negotiation rpc with $TIMEOUT.
1876     # FIXME better by monitoring import status.
1877     if $GSS; then
1878         set_flavor_all $SEC
1879         sleep $((TIMEOUT + 5))
1880     else
1881         sleep 5
1882     fi
1883 }
1884
1885 mounted_lustre_filesystems() {
1886         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
1887 }
1888
1889 init_facet_vars () {
1890     [ "$CLIENTONLY" ] && return 0
1891     local facet=$1
1892     shift
1893     local device=$1
1894
1895     shift
1896
1897     eval export ${facet}_dev=${device}
1898     eval export ${facet}_opt=\"$@\"
1899
1900     local dev=${facet}_dev
1901     local label=$(do_facet ${facet} "$E2LABEL ${!dev}")
1902     [ -z "$label" ] && echo no label for ${!dev} && exit 1
1903
1904     eval export ${facet}_svc=${label}
1905
1906     local varname=${facet}failover_HOST
1907     if [ -z "${!varname}" ]; then
1908        eval $varname=$(facet_host $facet) 
1909     fi
1910
1911     # ${facet}failover_dev is set in cfg file
1912     varname=${facet}failover_dev
1913     if [ -n "${!varname}" ] ; then
1914         eval export ${facet}failover_dev=${!varname}
1915     else
1916         eval export ${facet}failover_dev=$device
1917     fi
1918 }
1919
1920 init_facets_vars () {
1921     local DEVNAME
1922
1923     if ! remote_mds_nodsh; then 
1924         for num in `seq $MDSCOUNT`; do
1925             DEVNAME=`mdsdevname $num`
1926             init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
1927         done
1928     fi
1929
1930     remote_ost_nodsh && return
1931
1932     for num in `seq $OSTCOUNT`; do
1933         DEVNAME=`ostdevname $num`
1934         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
1935     done
1936 }
1937
1938 osc_ensure_active () {
1939     local facet=$1
1940     local type=$2
1941     local timeout=$3
1942     local period=0
1943
1944     while [ $period -lt $timeout ]; do
1945         count=$(do_facet $facet "lctl dl | grep '${FSNAME}-OST.*-osc-${type}' | grep ' IN ' 2>/dev/null | wc -l")
1946         if [ $count -eq 0 ]; then
1947             break
1948         fi
1949
1950         echo "There are $count OST are inactive, wait $period seconds, and try again"
1951         sleep 3
1952         period=$((period+3))
1953     done
1954
1955     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
1956 }
1957
1958 init_param_vars () {
1959     if ! remote_ost_nodsh && ! remote_mds_nodsh; then
1960         export MDSVER=$(do_facet $SINGLEMDS "lctl get_param version" | cut -d. -f1,2)
1961         export OSTVER=$(do_facet ost1 "lctl get_param version" | cut -d. -f1,2)
1962         export CLIVER=$(lctl get_param version | cut -d. -f 1,2)
1963     fi
1964
1965     remote_mds_nodsh ||
1966         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
1967
1968     log "Using TIMEOUT=$TIMEOUT"
1969
1970     osc_ensure_active $SINGLEMDS M $TIMEOUT
1971     osc_ensure_active client c $TIMEOUT
1972
1973     if [ $QUOTA_AUTO -ne 0 ]; then
1974         if [ "$ENABLE_QUOTA" ]; then
1975             echo "enable quota as required"
1976             setup_quota $MOUNT || return 2
1977         else
1978             echo "disable quota as required"
1979             $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
1980         fi
1981     fi
1982
1983     return 0
1984 }
1985
1986 nfs_client_mode () {
1987     if [ "$NFSCLIENT" ]; then
1988         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
1989         local clients=$CLIENTS
1990         [ -z $clients ] && clients=$(hostname)
1991
1992         # FIXME: remove hostname when 19215 fixed
1993         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
1994         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
1995         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
1996         return
1997     fi
1998     return 1
1999 }
2000
2001 check_config_client () {
2002     local mntpt=$1
2003
2004     local mounted=$(mount | grep " $mntpt ")
2005     if [ "$CLIENTONLY" ]; then
2006         # bug 18021
2007         # CLIENTONLY should not depend on *_HOST settings
2008         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
2009         # in theory someone could create a new,
2010         # client-only config file that assumed lustre was already
2011         # configured and didn't set the MGSNID. If MGSNID is not set,
2012         # then we should use the mgs nid currently being used 
2013         # as the default value. bug 18021
2014         [[ x$MGSNID = x ]] &&
2015             MGSNID=${mgc//MGC/}
2016
2017         if [[ x$mgc != xMGC$MGSNID ]]; then
2018             if [ "$mgs_HOST" ]; then
2019                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
2020 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
2021 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
2022             fi
2023         fi
2024         return 0
2025     fi
2026
2027     local myMGS_host=$mgs_HOST   
2028     if [ "$NETTYPE" = "ptl" ]; then
2029         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
2030     fi
2031
2032     echo Checking config lustre mounted on $mntpt
2033     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
2034     mgshost=$(echo $mgshost | awk -F: '{print $1}')
2035
2036 #    if [ "$mgshost" != "$myMGS_host" ]; then
2037 #            log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
2038 #                   Please use correct config or set mds_HOST correctly!"
2039 #    fi
2040
2041 }
2042
2043 check_config_clients () {
2044     local clients=${CLIENTS:-$HOSTNAME}
2045     local mntpt=$1
2046
2047     nfs_client_mode && return
2048
2049     do_rpc_nodes $clients check_config_client $mntpt
2050
2051     sanity_mount_check ||
2052         error "environments are insane!"
2053 }
2054
2055 check_timeout () {
2056     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
2057     local cltimeout=$(lctl get_param -n timeout)
2058     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
2059         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
2060         return 1
2061     fi
2062 }
2063
2064 is_mounted () {
2065     local mntpt=$1
2066     [ -z $mntpt ] && return 1
2067     local mounted=$(mounted_lustre_filesystems)
2068
2069     echo $mounted' ' | grep -w -q $mntpt' '
2070 }
2071
2072 is_empty_dir() {
2073     [ $(find $1 -maxdepth 1 -print | wc -l) = 1 ] && return 0
2074     return 1
2075 }
2076
2077 # empty lustre filesystem may have empty directories lost+found and .lustre
2078 is_empty_fs() {
2079     [ $(find $1 -maxdepth 1 -name lost+found -o -name .lustre -prune -o \
2080        -print | wc -l) = 1 ] || return 1
2081     [ ! -d $1/lost+found ] || is_empty_dir $1/lost+found && return 0
2082     [ ! -d $1/.lustre ] || is_empty_dir $1/.lustre && return 0
2083     return 1
2084 }
2085
2086 check_and_setup_lustre() {
2087     nfs_client_mode && return
2088
2089     local MOUNTED=$(mounted_lustre_filesystems)
2090
2091     local do_check=true
2092     # 1.
2093     # both MOUNT and MOUNT2 are not mounted
2094     if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
2095         [ "$REFORMAT" ] && formatall
2096         # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
2097         setupall
2098         is_mounted $MOUNT || error "NAME=$NAME not mounted"
2099         export I_MOUNTED=yes
2100         do_check=false
2101     # 2.
2102     # MOUNT2 is mounted
2103     elif is_mounted $MOUNT2; then
2104             # 3.
2105             # MOUNT2 is mounted, while MOUNT_2 is not set
2106             if ! [ "$MOUNT_2" ]; then
2107                 cleanup_mount $MOUNT2
2108                 export I_UMOUNTED2=yes
2109
2110             # 4.
2111             # MOUNT2 is mounted, MOUNT_2 is set
2112             else
2113                 # FIXME: what to do if check_config failed?
2114                 # i.e. if:
2115                 # 1) remote client has mounted other Lustre fs ?
2116                 # 2) it has insane env ?
2117                 # let's try umount MOUNT2 on all clients and mount it again:
2118                 if ! check_config_clients $MOUNT2; then
2119                     cleanup_mount $MOUNT2
2120                     restore_mount $MOUNT2
2121                     export I_MOUNTED2=yes
2122                 fi
2123             fi 
2124
2125     # 5.
2126     # MOUNT is mounted MOUNT2 is not mounted
2127     elif [ "$MOUNT_2" ]; then
2128         restore_mount $MOUNT2
2129         export I_MOUNTED2=yes
2130     fi
2131
2132     if $do_check; then
2133         # FIXME: what to do if check_config failed?
2134         # i.e. if:
2135         # 1) remote client has mounted other Lustre fs?
2136         # 2) lustre is mounted on remote_clients atall ?
2137         check_config_clients $MOUNT
2138         init_facets_vars
2139         init_param_vars
2140
2141         do_nodes $(comma_list $(nodes_list)) "lctl set_param debug=\\\"$PTLDEBUG\\\";
2142             lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
2143             lctl set_param debug_mb=${DEBUG_SIZE};
2144             sync"
2145     fi
2146
2147     init_gss
2148     set_flavor_all $SEC
2149
2150     if [ "$ONLY" == "setup" ]; then
2151         exit 0
2152     fi
2153 }
2154
2155 restore_mount () {
2156    local clients=${CLIENTS:-$HOSTNAME}
2157    local mntpt=$1
2158
2159    zconf_mount_clients $clients $mntpt
2160 }
2161
2162 cleanup_mount () {
2163     local clients=${CLIENTS:-$HOSTNAME}
2164     local mntpt=$1
2165
2166     zconf_umount_clients $clients $mntpt    
2167 }
2168
2169 cleanup_and_setup_lustre() {
2170     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
2171         lctl set_param debug=0 || true
2172         cleanupall
2173         if [ "$ONLY" == "cleanup" ]; then
2174             exit 0
2175         fi
2176     fi
2177     check_and_setup_lustre
2178 }
2179
2180 # Get all of the server target devices from a given server node and type.
2181 get_mnt_devs() {
2182     local node=$1
2183     local type=$2
2184     local obd_type
2185     local devs
2186     local dev
2187
2188     case $type in
2189     mdt) obd_type="osd" ;;
2190     ost) obd_type="obdfilter" ;; # needs to be fixed when OST also uses an OSD
2191     *) echo "invalid server type" && return 1 ;;
2192     esac
2193
2194     devs=$(do_node $node "lctl get_param -n $obd_type*.*.mntdev")
2195     for dev in $devs; do
2196         case $dev in
2197         *loop*) do_node $node "losetup $dev" | \
2198                 sed -e "s/.*(//" -e "s/).*//" ;;
2199         *) echo $dev ;;
2200         esac
2201     done
2202 }
2203
2204 # Get all of the server target devices.
2205 get_svr_devs() {
2206     local i
2207
2208     # MDT device
2209     MDTDEV=$(get_mnt_devs $(mdts_nodes) mdt)
2210
2211     # OST devices
2212     i=0
2213     for node in $(osts_nodes); do
2214         OSTDEVS[i]=$(get_mnt_devs $node ost)
2215         i=$((i + 1))
2216     done
2217 }
2218
2219 # Run e2fsck on MDT or OST device.
2220 run_e2fsck() {
2221     local node=$1
2222     local target_dev=$2
2223     local ostidx=$3
2224     local ostdb_opt=$4
2225
2226     df > /dev/null      # update statfs data on disk
2227     local cmd="$E2FSCK -d -v -f -n $MDSDB_OPT $ostdb_opt $target_dev"
2228     echo $cmd
2229     do_node $node $cmd
2230     local rc=${PIPESTATUS[0]}
2231     [ $rc -le $FSCK_MAX_ERR ] || \
2232         error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
2233     return 0
2234 }
2235
2236 # Run e2fsck on MDT and OST(s) to generate databases used for lfsck.
2237 generate_db() {
2238     local i
2239     local ostidx
2240     local dev
2241     local tmp_file
2242
2243     [ $MDSCOUNT -eq 1 ] || error "CMD is not supported"
2244     tmp_file=$(mktemp -p $SHARED_DIRECTORY || 
2245         error "fail to create file in $SHARED_DIRECTORY")
2246
2247     # make sure everything gets to the backing store
2248     local list=$(comma_list $CLIENTS $(facet_host $SINGLEMDS) $(osts_nodes))
2249     do_nodes $list "sync; sleep 2; sync"
2250
2251     do_nodes $list ls $tmp_file || \
2252         error "$SHARED_DIRECTORY is not a shared directory"
2253     rm $tmp_file
2254
2255     run_e2fsck $(mdts_nodes) $MDTDEV
2256
2257     i=0
2258     ostidx=0
2259     OSTDB_LIST=""
2260     for node in $(osts_nodes); do
2261         for dev in ${OSTDEVS[i]}; do
2262             local ostdb_opt=`eval echo $OSTDB_OPT`
2263             run_e2fsck $node $dev $ostidx "$ostdb_opt"
2264             OSTDB_LIST="$OSTDB_LIST $OSTDB-$ostidx"
2265             ostidx=$((ostidx + 1))
2266         done
2267         i=$((i + 1))
2268     done
2269 }
2270
2271 run_lfsck() {
2272     local cmd="$LFSCK_BIN -c -l --mdsdb $MDSDB --ostdb $OSTDB_LIST $MOUNT"
2273     echo $cmd
2274     eval $cmd
2275     local rc=${PIPESTATUS[0]}
2276     [ $rc -le $FSCK_MAX_ERR ] || \
2277         error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
2278     echo "lfsck finished with rc=$rc"
2279
2280     rm -rvf $MDSDB* $OSTDB* || true
2281
2282     return $rc
2283 }
2284
2285 check_and_cleanup_lustre() {
2286     if [ "$LFSCK_ALWAYS" = "yes" ]; then
2287         get_svr_devs
2288         generate_db
2289         if [ "$SKIP_LFSCK" == "no" ]; then
2290             local rc=0
2291             run_lfsck || rc=$?
2292         else
2293             echo "skip lfsck"
2294         fi
2295     fi
2296
2297     if is_mounted $MOUNT; then
2298         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
2299         [ "$ENABLE_QUOTA" ] && restore_quota_type || true
2300     fi
2301
2302     if [ "$I_UMOUNTED2" = "yes" ]; then
2303         restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
2304     fi
2305
2306     if [ "$I_MOUNTED2" = "yes" ]; then
2307         cleanup_mount $MOUNT2
2308     fi
2309
2310     if [ "$I_MOUNTED" = "yes" ]; then
2311         cleanupall -f || error "cleanup failed"
2312         unset I_MOUNTED
2313     fi
2314 }
2315
2316 #######
2317 # General functions
2318
2319 check_network() {
2320     local NETWORK=0
2321     local WAIT=0
2322     local MAX=$2
2323     while [ $NETWORK -eq 0 ]; do
2324         if ping -c 1 -w 3 $1 > /dev/null; then
2325             NETWORK=1
2326         else
2327             WAIT=$((WAIT + 5))
2328             echo "waiting for $1, $((MAX - WAIT)) secs left"
2329             sleep 5
2330         fi
2331         if [ $WAIT -gt $MAX ]; then
2332             echo "Network not available"
2333             exit 1
2334         fi
2335     done
2336 }
2337 check_port() {
2338     while( !($DSH2 $1 "netstat -tna | grep -q $2") ) ; do
2339         sleep 9
2340     done
2341 }
2342
2343 no_dsh() {
2344     shift
2345     eval $@
2346 }
2347
2348 comma_list() {
2349     # the sed converts spaces to commas, but leaves the last space
2350     # alone, so the line doesn't end with a comma.
2351     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
2352 }
2353
2354 # list, excluded are the comma separated lists
2355 exclude_items_from_list () {
2356     local list=$1
2357     local excluded=$2
2358     local item
2359
2360     list=${list//,/ }
2361     for item in ${excluded//,/ }; do
2362         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
2363     done
2364     echo $(comma_list $list) 
2365 }
2366
2367 # list, expand  are the comma separated lists
2368 expand_list () {
2369     local list=${1//,/ }
2370     local expand=${2//,/ }
2371     local expanded=
2372
2373     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
2374     echo $(comma_list $expanded)
2375 }
2376
2377 testslist_filter () {
2378     local script=$LUSTRE/tests/${TESTSUITE}.sh
2379
2380     [ -f $script ] || return 0
2381
2382     local start_at=$START_AT
2383     local stop_at=$STOP_AT
2384
2385     local var=${TESTSUITE//-/_}_START_AT
2386     [ x"${!var}" != x ] && start_at=${!var}
2387     var=${TESTSUITE//-/_}_STOP_AT
2388     [ x"${!var}" != x ] && stop_at=${!var}
2389
2390     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
2391         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
2392             /^'${start_at}'$/ {flag = 0}
2393             {if (flag == 1) print $0}
2394             /^'${stop_at}'$/ { flag = 1 }'
2395 }
2396
2397 absolute_path() {
2398     (cd `dirname $1`; echo $PWD/`basename $1`)
2399 }
2400
2401 get_facets () {
2402     local name=$(echo $1 | tr "[:upper:]" "[:lower:]")
2403     local type=$(echo $1 | tr "[:lower:]" "[:upper:]")
2404
2405     local list=""
2406     local count=${type}COUNT
2407     for ((i=1; i<=${!count}; i++)) do
2408         list="$list ${name}$i"
2409     done
2410     echo $(comma_list $list)
2411 }
2412
2413 ##################################
2414 # Adaptive Timeouts funcs
2415
2416 at_is_enabled() {
2417     # only check mds, we assume at_max is the same on all nodes
2418     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
2419     if [ $at_max -eq 0 ]; then
2420         return 1
2421     else
2422         return 0
2423     fi
2424 }
2425
2426 at_max_get() {
2427     local facet=$1
2428
2429     # suppose that all ost-s has the same at_max set
2430     if [ $facet == "ost" ]; then
2431         do_facet ost1 "lctl get_param -n at_max"
2432     else
2433         do_facet $facet "lctl get_param -n at_max"
2434     fi
2435 }
2436
2437 at_max_set() {
2438     local at_max=$1
2439     shift
2440
2441     local facet
2442     for facet in $@; do
2443         if [ $facet == "ost" ]; then
2444             for i in `seq $OSTCOUNT`; do
2445                 do_facet ost$i "lctl set_param at_max=$at_max"
2446
2447             done
2448         elif [ $facet == "mds" ]; then
2449             for i in `seq $MDSCOUNT`; do
2450                 do_facet mds$i "lctl set_param at_max=$at_max"
2451             done
2452         else
2453             do_facet $facet "lctl set_param at_max=$at_max"
2454         fi
2455     done
2456 }
2457
2458 ##################################
2459 # OBD_FAIL funcs
2460
2461 drop_request() {
2462 # OBD_FAIL_MDS_ALL_REQUEST_NET
2463     RC=0
2464     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
2465     do_facet client "$1" || RC=$?
2466     do_facet $SINGLEMDS lctl set_param fail_loc=0
2467     return $RC
2468 }
2469
2470 drop_reply() {
2471 # OBD_FAIL_MDS_ALL_REPLY_NET
2472     RC=0
2473     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
2474     do_facet client "$@" || RC=$?
2475     do_facet $SINGLEMDS lctl set_param fail_loc=0
2476     return $RC
2477 }
2478
2479 drop_reint_reply() {
2480 # OBD_FAIL_MDS_REINT_NET_REP
2481     RC=0
2482     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
2483     do_facet client "$@" || RC=$?
2484     do_facet $SINGLEMDS lctl set_param fail_loc=0
2485     return $RC
2486 }
2487
2488 pause_bulk() {
2489 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
2490     RC=0
2491     do_facet ost1 lctl set_param fail_loc=0x214
2492     do_facet client "$1" || RC=$?
2493     do_facet client "sync"
2494     do_facet ost1 lctl set_param fail_loc=0
2495     return $RC
2496 }
2497
2498 drop_ldlm_cancel() {
2499 #define OBD_FAIL_LDLM_CANCEL             0x304
2500     RC=0
2501     do_facet client lctl set_param fail_loc=0x304
2502     do_facet client "$@" || RC=$?
2503     do_facet client lctl set_param fail_loc=0
2504     return $RC
2505 }
2506
2507 drop_bl_callback() {
2508 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
2509     RC=0
2510     do_facet client lctl set_param fail_loc=0x305
2511     do_facet client "$@" || RC=$?
2512     do_facet client lctl set_param fail_loc=0
2513     return $RC
2514 }
2515
2516 drop_ldlm_reply() {
2517 #define OBD_FAIL_LDLM_REPLY              0x30c
2518     RC=0
2519     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
2520     do_facet client "$@" || RC=$?
2521     do_facet $SINGLEMDS lctl set_param fail_loc=0
2522     return $RC
2523 }
2524
2525 clear_failloc() {
2526     facet=$1
2527     pause=$2
2528     sleep $pause
2529     echo "clearing fail_loc on $facet"
2530     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
2531 }
2532
2533 set_nodes_failloc () {
2534     do_nodes $(comma_list $1)  lctl set_param fail_loc=$2
2535 }
2536
2537 cancel_lru_locks() {
2538     $LCTL mark "cancel_lru_locks $1 start"
2539     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
2540         $LCTL set_param -n $d=clear
2541     done
2542     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
2543     $LCTL mark "cancel_lru_locks $1 stop"
2544 }
2545
2546 default_lru_size()
2547 {
2548         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
2549         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
2550         echo "$DEFAULT_LRU_SIZE"
2551 }
2552
2553 lru_resize_enable()
2554 {
2555     lctl set_param ldlm.namespaces.*$1*.lru_size=0
2556 }
2557
2558 lru_resize_disable()
2559 {
2560     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
2561 }
2562
2563 pgcache_empty() {
2564     local FILE
2565     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
2566         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
2567             echo there is still data in page cache $FILE ?
2568             lctl get_param -n $FILE
2569             return 1
2570         fi
2571     done
2572     return 0
2573 }
2574
2575 debugsave() {
2576     DEBUGSAVE="$(lctl get_param -n debug)"
2577 }
2578
2579 debugrestore() {
2580     [ -n "$DEBUGSAVE" ] && \
2581         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
2582     DEBUGSAVE=""
2583 }
2584
2585 debug_size_save() {
2586     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
2587 }
2588
2589 debug_size_restore() {
2590     [ -n "$DEBUG_SIZE_SAVED" ] && \
2591         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
2592     DEBUG_SIZE_SAVED=""
2593 }
2594
2595 start_full_debug_logging() {
2596     debugsave
2597     debug_size_save
2598
2599     local FULLDEBUG=-1
2600     local DEBUG_SIZE=150
2601
2602     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
2603     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
2604 }
2605
2606 stop_full_debug_logging() {
2607     debug_size_restore
2608     debugrestore
2609 }
2610
2611 ##################################
2612 # Test interface
2613 ##################################
2614
2615 error_noexit() {
2616     local TYPE=${TYPE:-"FAIL"}
2617
2618     local dump=true
2619     # do not dump logs if $1=false
2620     if [ "x$1" = "xfalse" ]; then
2621         shift
2622         dump=false
2623     fi
2624
2625     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
2626
2627     # We need to dump the logs on all nodes
2628     if $dump; then
2629         gather_logs $(comma_list $(nodes_list))
2630     fi
2631
2632     debugrestore
2633     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
2634     echo "$@" > $LOGDIR/err
2635 }
2636
2637 error() {
2638     error_noexit "$@"
2639     exit 1
2640 }
2641
2642 error_exit() {
2643     error "$@"
2644 }
2645
2646 # use only if we are ignoring failures for this test, bugno required.
2647 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
2648 # e.g. error_ignore 5494 "your message"
2649 error_ignore() {
2650     local TYPE="IGNORE (bz$1)"
2651     shift
2652     error_noexit "$@"
2653 }
2654
2655 skip_env () {
2656     $FAIL_ON_SKIP_ENV && error false $@ || skip $@
2657 }
2658
2659 skip () {
2660     echo
2661     log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
2662     [ "$TESTSUITELOG" ] && \
2663         echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
2664 }
2665
2666 build_test_filter() {
2667     EXCEPT="$EXCEPT $(testslist_filter)"
2668
2669     [ "$ONLY" ] && log "only running test `echo $ONLY`"
2670     for O in $ONLY; do
2671         eval ONLY_${O}=true
2672     done
2673     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
2674         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
2675     [ "$EXCEPT_SLOW" ] && \
2676         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
2677     for E in $EXCEPT $ALWAYS_EXCEPT; do
2678         eval EXCEPT_${E}=true
2679     done
2680     for E in $EXCEPT_SLOW; do
2681         eval EXCEPT_SLOW_${E}=true
2682     done
2683     for G in $GRANT_CHECK_LIST; do
2684         eval GCHECK_ONLY_${G}=true
2685         done
2686 }
2687
2688 basetest() {
2689     if [[ $1 = [a-z]* ]]; then
2690         echo $1
2691     else
2692         echo ${1%%[a-z]*}
2693     fi
2694 }
2695
2696 # print a newline if the last test was skipped
2697 export LAST_SKIPPED=
2698 #
2699 # Main entry into test-framework. This is called with the name and
2700 # description of a test. The name is used to find the function to run
2701 # the test using "test_$name".
2702 #
2703 # This supports a variety of methods of specifying specific test to
2704 # run or not run.  These need to be documented...
2705 #
2706 run_test() {
2707     assert_DIR
2708
2709     export base=`basetest $1`
2710     if [ ! -z "$ONLY" ]; then
2711         testname=ONLY_$1
2712         if [ ${!testname}x != x ]; then
2713             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2714             run_one_logged $1 "$2"
2715             return $?
2716         fi
2717         testname=ONLY_$base
2718         if [ ${!testname}x != x ]; then
2719             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2720             run_one_logged $1 "$2"
2721             return $?
2722         fi
2723         LAST_SKIPPED="y"
2724         echo -n "."
2725         return 0
2726     fi
2727     testname=EXCEPT_$1
2728     if [ ${!testname}x != x ]; then
2729         LAST_SKIPPED="y"
2730         TESTNAME=test_$1 skip "skipping excluded test $1"
2731         return 0
2732     fi
2733     testname=EXCEPT_$base
2734     if [ ${!testname}x != x ]; then
2735         LAST_SKIPPED="y"
2736         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
2737         return 0
2738     fi
2739     testname=EXCEPT_SLOW_$1
2740     if [ ${!testname}x != x ]; then
2741         LAST_SKIPPED="y"
2742         TESTNAME=test_$1 skip "skipping SLOW test $1"
2743         return 0
2744     fi
2745     testname=EXCEPT_SLOW_$base
2746     if [ ${!testname}x != x ]; then
2747         LAST_SKIPPED="y"
2748         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
2749         return 0
2750     fi
2751
2752     LAST_SKIPPED=
2753     run_one_logged $1 "$2"
2754
2755     return $?
2756 }
2757
2758 equals_msg() {
2759     banner "$*"
2760 }
2761
2762 log() {
2763     echo "$*"
2764     module_loaded lnet || load_modules
2765
2766     local MSG="$*"
2767     # Get rid of '
2768     MSG=${MSG//\'/\\\'}
2769     MSG=${MSG//\(/\\\(}
2770     MSG=${MSG//\)/\\\)}
2771     MSG=${MSG//\;/\\\;}
2772     MSG=${MSG//\|/\\\|}
2773     MSG=${MSG//\>/\\\>}
2774     MSG=${MSG//\</\\\<}
2775     MSG=${MSG//\//\\\/}
2776     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
2777 }
2778
2779 trace() {
2780         log "STARTING: $*"
2781         strace -o $TMP/$1.strace -ttt $*
2782         RC=$?
2783         log "FINISHED: $*: rc $RC"
2784         return 1
2785 }
2786
2787 pass() {
2788     # Set TEST_STATUS here; will be used for logging the result
2789     if [ -f $LOGDIR/err ]; then
2790         TEST_STATUS="FAIL"
2791     else
2792         TEST_STATUS="PASS"
2793     fi
2794     echo $TEST_STATUS " " $@
2795 }
2796
2797 check_mds() {
2798     FFREE=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filesfree | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2799     FTOTAL=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filestotal | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2800     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
2801 }
2802
2803 reset_fail_loc () {
2804     echo -n "Resetting fail_loc on all nodes..."
2805     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
2806     echo done.
2807 }
2808
2809
2810 #
2811 # Log a message (on all nodes) padded with "=" before and after. 
2812 # Also appends a timestamp and prepends the testsuite name.
2813
2814
2815 EQUALS="===================================================================================================="
2816 banner() {
2817     msg="== ${TESTSUITE} $*"
2818     last=${msg: -1:1}
2819     [[ $last != "=" && $last != " " ]] && msg="$msg "
2820     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
2821     # always include at least == after the message
2822     log "$msg== $(date +"%H:%M:%S (%s)")"
2823 }
2824
2825 #
2826 # Run a single test function and cleanup after it.  
2827 #
2828 # This function should be run in a subshell so the test func can
2829 # exit() without stopping the whole script.
2830 #
2831 run_one() {
2832     local testnum=$1
2833     local message=$2
2834     tfile=f${testnum}
2835     export tdir=d0.${TESTSUITE}/d${base}
2836     export TESTNAME=test_$testnum
2837     local SAVE_UMASK=`umask`
2838     umask 0022
2839
2840     banner "test $testnum: $message"
2841     test_${testnum} || error "test_$testnum failed with $?"
2842     cd $SAVE_PWD
2843     reset_fail_loc
2844     check_grant ${testnum} || error "check_grant $testnum failed with $?"
2845     check_catastrophe || error "LBUG/LASSERT detected"
2846     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
2847     unset TESTNAME
2848     unset tdir
2849     umask $SAVE_UMASK
2850     return 0
2851 }
2852
2853 #
2854 # Wrapper around run_one to ensure:
2855 #  - test runs in subshell
2856 #  - output of test is saved to separate log file for error reporting
2857 #  - test result is saved to data file
2858 #
2859 run_one_logged() {
2860     local BEFORE=`date +%s`
2861     local TEST_ERROR
2862     local name=${TESTSUITE}.test_${1}.test_log.$(hostname).log
2863     local test_log=$LOGDIR/$name
2864     rm -rf $LOGDIR/err
2865
2866     echo
2867     log_sub_test_begin test_${1}
2868     (run_one $1 "$2") 2>&1 | tee $test_log
2869     local RC=${PIPESTATUS[0]}
2870
2871     [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] && \
2872         echo "test_$1 returned $RC" | tee $LOGDIR/err
2873
2874     duration=$((`date +%s` - $BEFORE))
2875     pass "(${duration}s)"
2876     [ -f $LOGDIR/err ] && TEST_ERROR=$(cat $LOGDIR/err)
2877     log_sub_test_end $TEST_STATUS $duration "$RC" "$TEST_ERROR"
2878
2879     if [ -f $LOGDIR/err ]; then
2880         $FAIL_ON_ERROR && exit $RC
2881     fi
2882
2883     return 0
2884 }
2885
2886 canonical_path() {
2887     (cd `dirname $1`; echo $PWD/`basename $1`)
2888 }
2889
2890 sync_clients() {
2891     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
2892     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
2893         cd $SAVE_PWD
2894 }
2895
2896 check_grant() {
2897     export base=`basetest $1`
2898     [ "$CHECK_GRANT" == "no" ] && return 0
2899
2900         testname=GCHECK_ONLY_${base}
2901         [ ${!testname}x == x ] && return 0
2902
2903     echo -n "checking grant......"
2904         cd $SAVE_PWD
2905         # write some data to sync client lost_grant
2906         rm -f $DIR1/${tfile}_check_grant_* 2>&1
2907         for i in `seq $OSTCOUNT`; do
2908                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
2909                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
2910                                               count=1 > /dev/null 2>&1
2911         done
2912         # sync all the data and make sure no pending data on server
2913         sync_clients
2914         
2915         #get client grant and server grant
2916         client_grant=0
2917     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
2918                 client_grant=$((client_grant + $d))
2919         done
2920         server_grant=0
2921         for d in `lctl get_param -n obdfilter.*.tot_granted`; do
2922                 server_grant=$((server_grant + $d))
2923         done
2924
2925         # cleanup the check_grant file
2926         for i in `seq $OSTCOUNT`; do
2927                 rm $DIR1/${tfile}_check_grant_$i
2928         done
2929
2930         #check whether client grant == server grant
2931         if [ $client_grant != $server_grant ]; then
2932                 echo "failed: client:${client_grant} server: ${server_grant}"
2933                 return 1
2934         else
2935                 echo "pass"
2936         fi
2937 }
2938
2939 ########################
2940 # helper functions
2941
2942 osc_to_ost()
2943 {
2944     osc=$1
2945     ost=`echo $1 | awk -F_ '{print $3}'`
2946     if [ -z $ost ]; then
2947         ost=`echo $1 | sed 's/-osc.*//'`
2948     fi
2949     echo $ost
2950 }
2951
2952 remote_node () {
2953     local node=$1
2954     [ "$node" != "$(hostname)" ]
2955 }
2956
2957 remote_mds ()
2958 {
2959     local node
2960     for node in $(mdts_nodes); do
2961         remote_node $node && return 0
2962     done
2963     return 1
2964 }
2965
2966 remote_mds_nodsh()
2967 {
2968     [ "$CLIENTONLY" ] && return 0 || true
2969     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
2970 }
2971
2972 require_dsh_mds()
2973 {
2974         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
2975             MSKIPPED=1 && return 1
2976         return 0
2977 }
2978
2979 remote_ost ()
2980 {
2981     local node
2982     for node in $(osts_nodes) ; do
2983         remote_node $node && return 0
2984     done
2985     return 1
2986 }
2987
2988 remote_ost_nodsh()
2989 {
2990     [ "$CLIENTONLY" ] && return 0 || true 
2991     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2992 }
2993
2994 require_dsh_ost()
2995 {
2996         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
2997             OSKIPPED=1 && return 1
2998         return 0
2999 }
3000
3001 remote_mgs_nodsh()
3002 {
3003     local MGS 
3004     MGS=$(facet_host mgs)
3005     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
3006 }
3007
3008 local_mode ()
3009 {
3010     remote_mds_nodsh || remote_ost_nodsh || \
3011         $(single_local_node $(comma_list $(nodes_list)))
3012 }
3013
3014 mdts_nodes () {
3015     local MDSNODES
3016     local NODES_sort
3017     for num in `seq $MDSCOUNT`; do
3018         MDSNODES="$MDSNODES $(facet_host mds$num)"
3019     done
3020     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
3021
3022     echo $NODES_sort
3023 }
3024
3025 remote_servers () {
3026     remote_ost && remote_mds
3027 }
3028
3029 osts_nodes () {
3030     local OSTNODES=$(facet_host ost1)
3031     local NODES_sort
3032
3033     for num in `seq $OSTCOUNT`; do
3034         local myOST=$(facet_host ost$num)
3035         OSTNODES="$OSTNODES $myOST"
3036     done
3037     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
3038
3039     echo $NODES_sort
3040 }
3041
3042 nodes_list () {
3043     # FIXME. We need a list of clients
3044     local myNODES=$HOSTNAME
3045     local myNODES_sort
3046
3047     # CLIENTS (if specified) contains the local client
3048     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
3049
3050     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
3051         myNODES="$myNODES $(osts_nodes) $(mdts_nodes)"
3052     fi
3053
3054     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
3055
3056     echo $myNODES_sort
3057 }
3058
3059 remote_nodes_list () {
3060     local rnodes=$(nodes_list)
3061     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
3062     echo $rnodes
3063 }
3064
3065 init_clients_lists () {
3066     # Sanity check: exclude the local client from RCLIENTS
3067     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
3068
3069     # Sanity check: exclude the dup entries
3070     rclients=$(for i in $rclients; do echo $i; done | sort -u)
3071
3072     local clients="$SINGLECLIENT $HOSTNAME $rclients"
3073
3074     # Sanity check: exclude the dup entries from CLIENTS
3075     # for those configs which has SINGLCLIENT set to local client
3076     clients=$(for i in $clients; do echo $i; done | sort -u)
3077
3078     CLIENTS=`comma_list $clients`
3079     local -a remoteclients=($rclients)
3080     for ((i=0; $i<${#remoteclients[@]}; i++)); do
3081             varname=CLIENT$((i + 2))
3082             eval $varname=${remoteclients[i]}
3083     done
3084
3085     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
3086 }
3087
3088 get_random_entry () {
3089     local rnodes=$1
3090
3091     rnodes=${rnodes//,/ }
3092
3093     local -a nodes=($rnodes)
3094     local num=${#nodes[@]} 
3095     local i=$((RANDOM * num * 2 / 65536))
3096
3097     echo ${nodes[i]}
3098 }
3099
3100 client_only () {
3101     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
3102 }
3103
3104 is_patchless ()
3105 {
3106     lctl get_param version | grep -q patchless
3107 }
3108
3109 check_versions () {
3110     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
3111 }
3112
3113 get_node_count() {
3114     local nodes="$@"
3115     echo $nodes | wc -w || true
3116 }
3117
3118 mixed_ost_devs () {
3119     local nodes=$(osts_nodes)
3120     local osscount=$(get_node_count "$nodes")
3121     [ ! "$OSTCOUNT" = "$osscount" ]
3122 }
3123
3124 mixed_mdt_devs () {
3125     local nodes=$(mdts_nodes)
3126     local mdtcount=$(get_node_count "$nodes")
3127     [ ! "$MDSCOUNT" = "$mdtcount" ]
3128 }
3129
3130 generate_machine_file() {
3131     local nodes=${1//,/ }
3132     local machinefile=$2
3133     rm -f $machinefile
3134     for node in $nodes; do
3135         echo $node >>$machinefile || \
3136             { echo "can not generate machinefile $machinefile" && return 1; }
3137     done
3138 }
3139
3140 get_stripe () {
3141     local file=$1/stripe
3142     touch $file
3143     $LFS getstripe -v $file || error
3144     rm -f $file
3145 }
3146
3147 setstripe_nfsserver () {
3148     local dir=$1
3149
3150     local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
3151                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -1)
3152
3153     [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
3154
3155     do_nodev $nfsserver lfs setstripe "$@"
3156 }
3157
3158 check_runas_id_ret() {
3159     local myRC=0
3160     local myRUNAS_UID=$1
3161     local myRUNAS_GID=$2
3162     shift 2
3163     local myRUNAS=$@
3164     if [ -z "$myRUNAS" ]; then
3165         error_exit "myRUNAS command must be specified for check_runas_id"
3166     fi
3167     if $GSS_KRB5; then
3168         $myRUNAS krb5_login.sh || \
3169             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
3170     fi
3171     mkdir $DIR/d0_runas_test
3172     chmod 0755 $DIR
3173     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
3174     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
3175     rm -rf $DIR/d0_runas_test
3176     return $myRC
3177 }
3178
3179 check_runas_id() {
3180     local myRUNAS_UID=$1
3181     local myRUNAS_GID=$2
3182     shift 2
3183     local myRUNAS=$@
3184     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
3185         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
3186         Please set RUNAS_ID to some UID which exists on MDS and client or
3187         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
3188 }
3189
3190 # obtain the UID/GID for MPI_USER
3191 get_mpiuser_id() {
3192     local mpi_user=$1
3193
3194     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
3195 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
3196
3197     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
3198 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
3199 }
3200
3201 # obtain and cache Kerberos ticket-granting ticket
3202 refresh_krb5_tgt() {
3203     local myRUNAS_UID=$1
3204     local myRUNAS_GID=$2
3205     shift 2
3206     local myRUNAS=$@
3207     if [ -z "$myRUNAS" ]; then
3208         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
3209     fi
3210
3211     CLIENTS=${CLIENTS:-$HOSTNAME}
3212     do_nodes $CLIENTS "set -x
3213 if ! $myRUNAS krb5_login.sh; then
3214     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
3215     exit 1
3216 fi"
3217 }
3218
3219 # Run multiop in the background, but wait for it to print
3220 # "PAUSING" to its stdout before returning from this function.
3221 multiop_bg_pause() {
3222     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
3223     FILE=$1
3224     ARGS=$2
3225
3226     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
3227     mkfifo $TMPPIPE
3228
3229     echo "$MULTIOP_PROG $FILE v$ARGS"
3230     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
3231
3232     echo "TMPPIPE=${TMPPIPE}"
3233     read -t 60 multiop_output < $TMPPIPE
3234     if [ $? -ne 0 ]; then
3235         rm -f $TMPPIPE
3236         return 1
3237     fi
3238     rm -f $TMPPIPE
3239     if [ "$multiop_output" != "PAUSING" ]; then
3240         echo "Incorrect multiop output: $multiop_output"
3241         kill -9 $PID
3242         return 1
3243     fi
3244
3245     return 0
3246 }
3247
3248 do_and_time () {
3249     local cmd=$1
3250     local rc
3251
3252     SECONDS=0
3253     eval '$cmd'
3254     
3255     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
3256
3257     echo $SECONDS
3258     return $rc
3259 }
3260
3261 inodes_available () {
3262     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
3263     echo $IFree
3264 }
3265
3266 mdsrate_inodes_available () {
3267     echo $(($(inodes_available) - 1))
3268 }
3269
3270 # reset llite stat counters
3271 clear_llite_stats(){
3272         lctl set_param -n llite.*.stats 0
3273 }
3274
3275 # sum llite stat items
3276 calc_llite_stats() {
3277         local res=$(lctl get_param -n llite.*.stats |
3278                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
3279         echo $res
3280 }
3281
3282 # reset osc stat counters
3283 clear_osc_stats(){
3284         lctl set_param -n osc.*.osc_stats 0
3285 }
3286
3287 # sum osc stat items
3288 calc_osc_stats() {
3289         local res=$(lctl get_param -n osc.*.osc_stats |
3290                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
3291         echo $res
3292 }
3293
3294 calc_sum () {
3295         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
3296 }
3297
3298 calc_osc_kbytes () {
3299         df $MOUNT > /dev/null
3300         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
3301 }
3302
3303 # save_lustre_params(node, parameter_mask)
3304 # generate a stream of formatted strings (<node> <param name>=<param value>)
3305 save_lustre_params() {
3306         local s
3307         do_nodesv $1 "lctl get_param $2 | while read s; do echo \\\$s; done"
3308 }
3309
3310 # restore lustre parameters from input stream, produces by save_lustre_params
3311 restore_lustre_params() {
3312         local node
3313         local name
3314         local val
3315         while IFS=" =" read node name val; do
3316                 do_node ${node//:/} "lctl set_param -n $name $val"
3317         done
3318 }
3319
3320 check_catastrophe() {
3321     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
3322     local C=$CATASTROPHE
3323     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
3324
3325     if [ $rnodes ]; then
3326         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
3327 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
3328 exit \\\$rc;"
3329     fi 
3330 }
3331
3332 # $1 node
3333 # $2 file
3334 # $3 $RUNAS
3335 get_stripe_info() {
3336         local tmp_file
3337
3338         stripe_size=0
3339         stripe_count=0
3340         stripe_index=0
3341         tmp_file=$(mktemp)
3342
3343         do_facet $1 $3 lfs getstripe -v $2 > $tmp_file
3344
3345         stripe_size=`awk '$1 ~ /size/ {print $2}' $tmp_file`
3346         stripe_count=`awk '$1 ~ /count/ {print $2}' $tmp_file`
3347         stripe_index=`awk '$1 ~ /stripe_offset/ {print $2}' $tmp_file`
3348         rm -f $tmp_file
3349 }
3350
3351 # CMD: determine mds index where directory inode presents
3352 get_mds_dir () {
3353     local dir=$1
3354     local file=$dir/f0.get_mds_dir_tmpfile
3355
3356     mkdir -p $dir
3357     rm -f $file
3358     sleep 1
3359     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
3360     local -a oldused=($iused)
3361
3362     openfile -f O_CREAT:O_LOV_DELAY_CREATE -m 0644 $file > /dev/null
3363     sleep 1
3364     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
3365     local -a newused=($iused)
3366
3367     local num=0
3368     for ((i=0; i<${#newused[@]}; i++)); do
3369          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
3370              echo $(( i + 1 ))
3371              rm -f $file
3372              return 0
3373          fi
3374     done
3375     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
3376 }
3377
3378 mdsrate_cleanup () {
3379     if [ -d $4 ]; then
3380         mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
3381         rmdir $4
3382     fi
3383 }
3384
3385 delayed_recovery_enabled () {
3386     local var=${SINGLEMDS}_svc
3387     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
3388 }
3389
3390 ########################
3391
3392 convert_facet2label() { 
3393     local facet=$1
3394
3395     if [ x$facet = xost ]; then
3396        facet=ost1
3397     fi
3398
3399     local varsvc=${facet}_svc
3400
3401     if [ -n ${!varsvc} ]; then
3402         echo ${!varsvc}
3403     else  
3404         error "No lablel for $facet!"
3405     fi
3406 }
3407
3408 get_clientosc_proc_path() {
3409     local ost=$1
3410
3411     echo "{$1}-osc-*"
3412 }
3413
3414 get_lustre_version () {
3415     local node=${1:-"mds"}    
3416     do_facet $node $LCTL get_param -n version |  awk '/^lustre:/ {print $2}'
3417 }
3418
3419 get_mds_version_major () {
3420     local version=$(get_lustre_version mds)
3421     echo $version | awk -F. '{print $1}'
3422 }
3423
3424 get_mds_version_minor () {
3425     local version=$(get_lustre_version mds)
3426     echo $version | awk -F. '{print $2}'
3427 }
3428
3429 get_mdtosc_proc_path() {
3430     local ost=$1
3431     local major=$(get_mds_version_major)
3432     local minor=$(get_mds_version_minor)
3433     if [ $major -le 1 -a $minor -le 8 ] ; then
3434         echo "${ost}-osc"
3435     else
3436         echo "${ost}-osc-MDT0000"
3437     fi
3438 }
3439
3440 get_osc_import_name() {
3441     local facet=$1
3442     local ost=$2
3443     local label=$(convert_facet2label $ost)
3444
3445     if [ "$facet" == "mds" ]; then
3446         get_mdtosc_proc_path $label
3447         return 0
3448     fi
3449
3450     get_clientosc_proc_path $label
3451     return 0
3452 }
3453
3454 wait_import_state () {
3455     local expected=$1
3456     local CONN_PROC=$2
3457     local CONN_STATE
3458     local i=0
3459
3460     CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3461     while [ "${CONN_STATE}" != "${expected}" ]; do
3462         if [ "${expected}" == "DISCONN" ]; then
3463             # for disconn we can check after proc entry is removed
3464             [ "x${CONN_STATE}" == "x" ] && return 0
3465             #  with AT we can have connect request timeout ~ reconnect timeout
3466             # and test can't see real disconnect
3467             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
3468         fi
3469         # disconnect rpc should be wait not more obd_timeout
3470         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
3471             error "can't put import for $CONN_PROC into ${expected} state" && return 1
3472         sleep 1
3473         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3474         i=$(($i + 1))
3475     done
3476
3477     log "$CONN_PROC now in ${CONN_STATE} state"
3478     return 0
3479 }
3480
3481 wait_osc_import_state() {
3482     local facet=$1
3483     local ost_facet=$2
3484     local expected=$3
3485     local ost=$(get_osc_import_name $facet $ost_facet)
3486     local CONN_PROC
3487     local CONN_STATE
3488     local i=0
3489
3490     CONN_PROC="osc.${ost}.ost_server_uuid"
3491     CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3492     while [ "${CONN_STATE}" != "${expected}" ]; do
3493         if [ "${expected}" == "DISCONN" ]; then 
3494             # for disconn we can check after proc entry is removed
3495             [ "x${CONN_STATE}" == "x" ] && return 0
3496             #  with AT we can have connect request timeout ~ reconnect timeout
3497             # and test can't see real disconnect
3498             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
3499         fi
3500         # disconnect rpc should be wait not more obd_timeout
3501         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
3502             error "can't put import for ${ost}(${ost_facet}) into ${expected} state" && return 1
3503         sleep 1
3504         CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3505         i=$(($i + 1))
3506     done
3507
3508     log "${ost_facet} now in ${CONN_STATE} state"
3509     return 0
3510 }
3511 get_clientmdc_proc_path() {
3512     echo "${1}-mdc-*"
3513 }
3514
3515 do_rpc_nodes () {
3516     local list=$1
3517     shift
3518
3519     # Add paths to lustre tests for 32 and 64 bit systems.
3520     local RPATH="$RLUSTRE/tests:/usr/lib/lustre/tests:/usr/lib64/lustre/tests:$PATH"
3521     do_nodesv $list "PATH=$RPATH sh rpc.sh $@ "
3522 }
3523
3524 wait_clients_import_state () {
3525     local list=$1
3526     local facet=$2
3527     local expected=$3
3528     shift
3529
3530     local label=$(convert_facet2label $facet)
3531     local proc_path
3532     case $facet in
3533         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
3534         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
3535         *) error "unknown facet!" ;;
3536     esac
3537
3538     if ! do_rpc_nodes $list wait_import_state $expected $proc_path; then
3539         error "import is not in ${expected} state"
3540         return 1
3541     fi
3542 }
3543
3544 oos_full() {
3545         local -a AVAILA
3546         local -a GRANTA
3547         local OSCFULL=1
3548         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
3549                   $LCTL get_param obdfilter.*.kbytesavail))
3550         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
3551                   $LCTL get_param -n obdfilter.*.tot_granted))
3552         for ((i=0; i<${#AVAILA[@]}; i++)); do
3553                 local -a AVAIL1=(${AVAILA[$i]//=/ })
3554                 GRANT=$((${GRANTA[$i]}/1024))
3555                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} grnt=$GRANT diff=$((AVAIL1[1] - GRANT))
3556                 [ $((AVAIL1[1] - GRANT)) -lt 400 ] && OSCFULL=0 && echo " FULL" || echo
3557         done
3558         return $OSCFULL
3559 }
3560
3561 pool_list () {
3562    do_facet mgs lctl pool_list $1
3563 }
3564
3565 create_pool() {
3566     local fsname=${1%%.*}
3567     local poolname=${1##$fsname.}
3568
3569     do_facet mgs lctl pool_new $1
3570     local RC=$?
3571     # get param should return err unless pool is created
3572     [[ $RC -ne 0 ]] && return $RC
3573
3574     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
3575         2>/dev/null || echo foo" "" || RC=1
3576     if [[ $RC -eq 0 ]]; then
3577         add_pool_to_list $1
3578     else
3579         error "pool_new failed $1"
3580     fi
3581     return $RC
3582 }
3583
3584 add_pool_to_list () {
3585     local fsname=${1%%.*}
3586     local poolname=${1##$fsname.}
3587
3588     local listvar=${fsname}_CREATED_POOLS
3589     eval export ${listvar}=$(expand_list ${!listvar} $poolname)
3590 }
3591
3592 remove_pool_from_list () {
3593     local fsname=${1%%.*}
3594     local poolname=${1##$fsname.}
3595
3596     local listvar=${fsname}_CREATED_POOLS
3597     eval export ${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
3598 }
3599
3600 destroy_pool_int() {
3601     local ost
3602     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
3603         awk '$1 !~ /^Pool:/ {print $1}')
3604     for ost in $OSTS; do
3605         do_facet mgs lctl pool_remove $1 $ost
3606     done
3607     do_facet mgs lctl pool_destroy $1
3608 }
3609
3610 # <fsname>.<poolname> or <poolname>
3611 destroy_pool() {
3612     local fsname=${1%%.*}
3613     local poolname=${1##$fsname.}
3614
3615     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
3616
3617     local RC
3618
3619     pool_list $fsname.$poolname || return $?
3620
3621     destroy_pool_int $fsname.$poolname
3622     RC=$?
3623     [[ $RC -ne 0 ]] && return $RC
3624
3625     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
3626       2>/dev/null || echo foo" "foo" || RC=1
3627
3628     if [[ $RC -eq 0 ]]; then
3629         remove_pool_from_list $fsname.$poolname
3630     else
3631         error "destroy pool failed $1"
3632     fi
3633     return $RC
3634 }
3635
3636 destroy_pools () {
3637     local fsname=${1:-$FSNAME}
3638     local poolname
3639     local listvar=${fsname}_CREATED_POOLS
3640
3641     pool_list $fsname
3642
3643     [ x${!listvar} = x ] && return 0
3644
3645     echo destroy the created pools: ${!listvar}
3646     for poolname in ${!listvar//,/ }; do
3647         destroy_pool $fsname.$poolname 
3648     done
3649 }
3650
3651 cleanup_pools () {
3652     local fsname=${1:-$FSNAME}
3653     trap 0
3654     destroy_pools $fsname
3655 }
3656
3657 gather_logs () {
3658     local list=$1
3659
3660     local ts=$(date +%s)
3661
3662     # bug 20237, comment 11
3663     # It would also be useful to provide the option
3664     # of writing the file to an NFS directory so it doesn't need to be copied.
3665     local tmp=$TMP
3666     local docp=true
3667     [ -f $LOGDIR/shared ] && docp=false
3668  
3669     # dump lustre logs, dmesg
3670
3671     prefix="$LOGDIR/${TESTSUITE}.${TESTNAME}"
3672     suffix="$ts.log"
3673     echo "Dumping lctl log to ${prefix}.*.${suffix}"
3674
3675     if [ "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
3676         echo "Dumping logs only on local client."
3677         $LCTL dk > ${prefix}.debug_log.$(hostname).${suffix}
3678         dmesg > ${prefix}.dmesg.$(hostname).${suffix}
3679         return
3680     fi
3681
3682     do_nodesv $list \
3683         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname).${suffix};
3684          dmesg > ${prefix}.dmesg.\\\$(hostname).${suffix}"
3685     if [ ! -f $LOGDIR/shared ]; then
3686         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
3687       fi
3688
3689     local archive=$LOGDIR/${TESTSUITE}-$ts.tar.bz2
3690     tar -jcf $archive $LOGDIR/*$ts* $LOGDIR/*${TESTSUITE}*
3691
3692     echo $archive
3693 }
3694
3695 cleanup_logs () {
3696     local list=${1:-$(comma_list $(nodes_list))}
3697
3698     [ -n ${TESTSUITE} ] && do_nodes $list "rm -f $TMP/*${TESTSUITE}*" || true
3699 }
3700
3701 do_ls () {
3702     local mntpt_root=$1
3703     local num_mntpts=$2
3704     local dir=$3
3705     local i
3706     local cmd
3707     local pids
3708     local rc=0
3709
3710     for i in $(seq 0 $num_mntpts); do
3711         cmd="ls -laf ${mntpt_root}$i/$dir"
3712         echo + $cmd;
3713         $cmd > /dev/null &
3714         pids="$pids $!"
3715     done
3716     echo pids=$pids
3717     for pid in $pids; do
3718         wait $pid || rc=$?
3719     done
3720
3721     return $rc
3722 }
3723
3724 # target_start_and_reset_recovery_timer()
3725 #        service_time = at_est2timeout(service_time);
3726 #        service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC +
3727 #                             INITIAL_CONNECT_TIMEOUT);
3728 # CONNECTION_SWITCH_MAX : min(25U, max(CONNECTION_SWITCH_MIN,obd_timeout))
3729 #define CONNECTION_SWITCH_INC 1
3730 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
3731 #define CONNECTION_SWITCH_MIN 5U
3732
3733 max_recovery_time () {
3734     local init_connect_timeout=$(( TIMEOUT / 20 ))
3735     [[ $init_connect_timeout > 5 ]] || init_connect_timeout=5 
3736
3737     local service_time=$(( $(at_max_get client) + $(( 2 * $(( 25 + 1  + init_connect_timeout)) )) ))
3738
3739     echo $service_time 
3740 }
3741
3742 get_clients_mount_count () {
3743     local clients=${CLIENTS:-`hostname`}
3744
3745     # we need to take into account the clients mounts and
3746     # exclude mds/ost mounts if any;
3747     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
3748 }
3749
3750 # gss functions
3751 PROC_CLI="srpc_info"
3752
3753 combination()
3754 {
3755     local M=$1
3756     local N=$2
3757     local R=1
3758
3759     if [ $M -lt $N ]; then
3760         R=0
3761     else
3762         N=$((N + 1))
3763         while [ $N -lt $M ]; do
3764             R=$((R * N))
3765             N=$((N + 1))
3766         done
3767     fi
3768
3769     echo $R
3770     return 0
3771 }
3772
3773 calc_connection_cnt() {
3774     local dir=$1
3775
3776     # MDT->MDT = 2 * C(M, 2)
3777     # MDT->OST = M * O
3778     # CLI->OST = C * O
3779     # CLI->MDT = C * M
3780     comb_m2=$(combination $MDSCOUNT 2)
3781
3782     local num_clients=$(get_clients_mount_count)
3783
3784     local cnt_mdt2mdt=$((comb_m2 * 2))
3785     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
3786     local cnt_cli2ost=$((num_clients * OSTCOUNT))
3787     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
3788     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
3789     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
3790     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
3791
3792     local var=cnt_$dir
3793     local res=${!var}
3794
3795     echo $res
3796 }
3797
3798 set_rule()
3799 {
3800     local tgt=$1
3801     local net=$2
3802     local dir=$3
3803     local flavor=$4
3804     local cmd="$tgt.srpc.flavor"
3805
3806     if [ $net == "any" ]; then
3807         net="default"
3808     fi
3809     cmd="$cmd.$net"
3810
3811     if [ $dir != "any" ]; then
3812         cmd="$cmd.$dir"
3813     fi
3814
3815     cmd="$cmd=$flavor"
3816     log "Setting sptlrpc rule: $cmd"
3817     do_facet mgs "$LCTL conf_param $cmd"
3818 }
3819
3820 count_flvr()
3821 {
3822     local output=$1
3823     local flavor=$2
3824     local count=0
3825
3826     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
3827     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
3828
3829     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
3830
3831     if [ "x$bulkspec" != "x" ]; then
3832         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
3833
3834         if [ "x$algs" != "x" ]; then
3835             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
3836         else
3837             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
3838             if [ $bulk == "bulkn" ]; then
3839                 bulk_count=`echo "$output" | grep "bulk flavor" \
3840                             | grep "null/null" | wc -l`
3841             elif [ $bulk == "bulki" ]; then
3842                 bulk_count=`echo "$output" | grep "bulk flavor" \
3843                             | grep "/null" | grep -v "null/" | wc -l`
3844             else
3845                 bulk_count=`echo "$output" | grep "bulk flavor" \
3846                             | grep -v "/null" | grep -v "null/" | wc -l`
3847             fi
3848         fi
3849
3850         [ $bulk_count -lt $count ] && count=$bulk_count
3851     fi
3852
3853     echo $count
3854 }
3855
3856 flvr_cnt_cli2mdt()
3857 {
3858     local flavor=$1
3859     local cnt
3860
3861     local clients=${CLIENTS:-`hostname`}
3862
3863     for c in ${clients//,/ }; do
3864         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
3865         tmpcnt=`count_flvr "$output" $flavor`
3866         cnt=$((cnt + tmpcnt))
3867     done
3868     echo $cnt
3869 }
3870
3871 flvr_cnt_cli2ost()
3872 {
3873     local flavor=$1
3874     local cnt
3875
3876     local clients=${CLIENTS:-`hostname`}
3877
3878     for c in ${clients//,/ }; do
3879         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
3880         tmpcnt=`count_flvr "$output" $flavor`
3881         cnt=$((cnt + tmpcnt))
3882     done
3883     echo $cnt
3884 }
3885
3886 flvr_cnt_mdt2mdt()
3887 {
3888     local flavor=$1
3889     local cnt=0
3890
3891     if [ $MDSCOUNT -le 1 ]; then
3892         echo 0
3893         return
3894     fi
3895
3896     for num in `seq $MDSCOUNT`; do
3897         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
3898         tmpcnt=`count_flvr "$output" $flavor`
3899         cnt=$((cnt + tmpcnt))
3900     done
3901     echo $cnt;
3902 }
3903
3904 flvr_cnt_mdt2ost()
3905 {
3906     local flavor=$1
3907     local cnt=0
3908
3909     for num in `seq $MDSCOUNT`; do
3910         output=`do_facet mds$num lctl get_param -n osc.*OST*-osc-MDT*.$PROC_CLI 2>/dev/null`
3911         tmpcnt=`count_flvr "$output" $flavor`
3912         cnt=$((cnt + tmpcnt))
3913     done
3914     echo $cnt;
3915 }
3916
3917 flvr_cnt_mgc2mgs()
3918 {
3919     local flavor=$1
3920
3921     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
3922     count_flvr "$output" $flavor
3923 }
3924
3925 do_check_flavor()
3926 {
3927     local dir=$1        # from to
3928     local flavor=$2     # flavor expected
3929     local res=0
3930
3931     if [ $dir == "cli2mdt" ]; then
3932         res=`flvr_cnt_cli2mdt $flavor`
3933     elif [ $dir == "cli2ost" ]; then
3934         res=`flvr_cnt_cli2ost $flavor`
3935     elif [ $dir == "mdt2mdt" ]; then
3936         res=`flvr_cnt_mdt2mdt $flavor`
3937     elif [ $dir == "mdt2ost" ]; then
3938         res=`flvr_cnt_mdt2ost $flavor`
3939     elif [ $dir == "all2ost" ]; then
3940         res1=`flvr_cnt_mdt2ost $flavor`
3941         res2=`flvr_cnt_cli2ost $flavor`
3942         res=$((res1 + res2))
3943     elif [ $dir == "all2mdt" ]; then
3944         res1=`flvr_cnt_mdt2mdt $flavor`
3945         res2=`flvr_cnt_cli2mdt $flavor`
3946         res=$((res1 + res2))
3947     elif [ $dir == "all2all" ]; then
3948         res1=`flvr_cnt_mdt2ost $flavor`
3949         res2=`flvr_cnt_cli2ost $flavor`
3950         res3=`flvr_cnt_mdt2mdt $flavor`
3951         res4=`flvr_cnt_cli2mdt $flavor`
3952         res=$((res1 + res2 + res3 + res4))
3953     fi
3954
3955     echo $res
3956 }
3957
3958 wait_flavor()
3959 {
3960     local dir=$1        # from to
3961     local flavor=$2     # flavor expected
3962     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
3963
3964     local res=0
3965
3966     for ((i=0;i<20;i++)); do
3967         echo -n "checking..."
3968         res=$(do_check_flavor $dir $flavor)
3969         if [ $res -eq $expect ]; then
3970             echo "found $res $flavor connections of $dir, OK"
3971             return 0
3972         else
3973             echo "found $res $flavor connections of $dir, not ready ($expect)"
3974             return 0
3975             sleep 4
3976         fi
3977     done
3978
3979     echo "Error checking $flavor of $dir: expect $expect, actual $res"
3980     return 1
3981 }
3982
3983 restore_to_default_flavor()
3984 {
3985     local proc="mgs.MGS.live.$FSNAME"
3986
3987     echo "restoring to default flavor..."
3988
3989     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
3990
3991     # remove all existing rules if any
3992     if [ $nrule -ne 0 ]; then
3993         echo "$nrule existing rules"
3994         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
3995             echo "remove rule: $rule"
3996             spec=`echo $rule | awk -F = '{print $1}'`
3997             do_facet mgs "$LCTL conf_param $spec="
3998         done
3999     fi
4000
4001     # verify no rules left
4002     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
4003     [ $nrule -ne 0 ] && error "still $nrule rules left"
4004
4005     # wait for default flavor to be applied
4006     # currently default flavor for all connections are 'null'
4007     wait_flavor all2all null
4008     echo "now at default flavor settings"
4009 }
4010
4011 set_flavor_all()
4012 {
4013     local flavor=${1:-null}
4014
4015     echo "setting all flavor to $flavor"
4016
4017     # FIXME need parameter to this fn
4018     # and remove global vars
4019     local cnt_all2all=$(calc_connection_cnt all2all)
4020
4021     local res=$(do_check_flavor all2all $flavor)
4022     if [ $res -eq $cnt_all2all ]; then
4023         echo "already have total $res $flavor connections"
4024         return
4025     fi
4026
4027     echo "found $res $flavor out of total $cnt_all2all connections"
4028     restore_to_default_flavor
4029
4030     [[ $flavor = null ]] && return 0
4031
4032     set_rule $FSNAME any any $flavor
4033     wait_flavor all2all $flavor
4034 }
4035
4036
4037 check_logdir() {
4038     local dir=$1
4039     # Checking for shared logdir
4040     if [ ! -d $dir ]; then
4041         # Not found. Create local logdir
4042         mkdir -p $dir
4043     else
4044         touch $dir/node.$(hostname).yml
4045     fi
4046     return 0
4047 }
4048
4049 check_write_access() {
4050     local dir=$1
4051     for node in $(nodes_list); do
4052         if [ ! -f "$dir/node.${node}.yml" ]; then
4053             # Logdir not accessible/writable from this node.
4054             return 1
4055         fi
4056     done
4057     return 0
4058 }
4059
4060 init_logging() {
4061     if [[ -n $YAML_LOG ]]; then
4062         return
4063     fi
4064     export YAML_LOG=${LOGDIR}/results.yml
4065     mkdir -p $LOGDIR
4066     init_clients_lists
4067
4068     do_rpc_nodes $(comma_list $(nodes_list)) check_logdir $LOGDIR
4069     if check_write_access $LOGDIR; then
4070         touch $LOGDIR/shared
4071         echo "Logging to shared log directory: $LOGDIR"
4072     else
4073         echo "Logging to local directory: $LOGDIR"
4074     fi
4075
4076     yml_nodes_file $LOGDIR
4077     yml_results_file >> $YAML_LOG
4078 }
4079
4080 log_test() {
4081     yml_log_test $1 >> $YAML_LOG
4082 }
4083
4084 log_test_status() {
4085      yml_log_test_status $@ >> $YAML_LOG
4086 }
4087
4088 log_sub_test_begin() {
4089     yml_log_sub_test_begin $@ >> $YAML_LOG
4090 }
4091
4092 log_sub_test_end() {
4093     yml_log_sub_test_end $@ >> $YAML_LOG
4094 }
4095
4096 run_llverdev()
4097 {
4098         local dev=$1
4099         local devname=$(basename $1)
4100         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
4101         # loop devices aren't in /proc/partitions
4102         [ "x$size" == "x" ] && local size=$(ls -l $dev | awk '{print $5}')
4103
4104         size=$(($size / 1024 / 1024)) # Gb
4105
4106         local partial_arg=""
4107         # Run in partial (fast) mode if the size
4108         # of a partition > 10 GB
4109         [ $size -gt 10 ] && partial_arg="-p"
4110
4111         llverdev --force $partial_arg $dev
4112 }
4113
4114 remove_mdt_files() {
4115     local facet=$1
4116     local mdtdev=$2
4117     shift 2
4118     local files="$@"
4119     local mntpt=${MOUNT%/*}/$facet
4120
4121     echo "removing files from $mdtdev on $facet: $files"
4122     mount -t $FSTYPE $MDS_MOUNT_OPTS $mdtdev $mntpt || return $?
4123     rc=0;
4124     for f in $files; do
4125         rm $mntpt/ROOT/$f || { rc=$?; break; }
4126     done
4127     umount -f $mntpt || return $?
4128     return $rc
4129 }
4130
4131 duplicate_mdt_files() {
4132     local facet=$1
4133     local mdtdev=$2
4134     shift 2
4135     local files="$@"
4136     local mntpt=${MOUNT%/*}/$facet
4137
4138     echo "duplicating files on $mdtdev on $facet: $files"
4139     mkdir -p $mntpt || return $?
4140     mount -t $FSTYPE $MDS_MOUNT_OPTS $mdtdev $mntpt || return $?
4141
4142     do_umount() {
4143         trap 0
4144         popd > /dev/null
4145         rm $tmp
4146         umount -f $mntpt
4147     }
4148     trap do_umount EXIT
4149
4150     tmp=$(mktemp $TMP/setfattr.XXXXXXXXXX)
4151     pushd $mntpt/ROOT > /dev/null || return $?
4152     rc=0
4153     for f in $files; do
4154         touch $f.bad || return $?
4155         getfattr -n trusted.lov $f | sed "s#$f#&.bad#" > $tmp
4156         rc=${PIPESTATUS[0]}
4157         [ $rc -eq 0 ] || return $rc
4158         setfattr --restore $tmp || return $?
4159     done
4160     do_umount
4161 }