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