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