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