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