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