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