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