Whamcloud - gitweb
b=22283 clarify writeconf in man page
[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     local mounted=$(mounted_lustre_filesystems)
2039
2040     echo $mounted' ' | grep -w -q $mntpt' '
2041 }
2042
2043 check_and_setup_lustre() {
2044     nfs_client_mode && return
2045
2046     local MOUNTED=$(mounted_lustre_filesystems)
2047
2048     local do_check=true
2049     # 1.
2050     # both MOUNT and MOUNT2 are not mounted
2051     if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
2052         [ "$REFORMAT" ] && formatall
2053         # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
2054         setupall
2055         is_mounted $MOUNT || error "NAME=$NAME not mounted"
2056         export I_MOUNTED=yes
2057         do_check=false
2058     # 2.
2059     # MOUNT2 is mounted
2060     elif is_mounted $MOUNT2; then
2061             # 3.
2062             # MOUNT2 is mounted, while MOUNT_2 is not set
2063             if ! [ "$MOUNT_2" ]; then
2064                 cleanup_mount $MOUNT2
2065                 export I_UMOUNTED2=yes
2066
2067             # 4.
2068             # MOUNT2 is mounted, MOUNT_2 is set
2069             else
2070                 # FIXME: what to do if check_config failed?
2071                 # i.e. if:
2072                 # 1) remote client has mounted other Lustre fs ?
2073                 # 2) it has insane env ?
2074                 # let's try umount MOUNT2 on all clients and mount it again:
2075                 if ! check_config_clients $MOUNT2; then
2076                     cleanup_mount $MOUNT2
2077                     restore_mount $MOUNT2
2078                     export I_MOUNTED2=yes
2079                 fi
2080             fi 
2081
2082     # 5.
2083     # MOUNT is mounted MOUNT2 is not mounted
2084     elif [ "$MOUNT_2" ]; then
2085         restore_mount $MOUNT2
2086         export I_MOUNTED2=yes
2087     fi
2088
2089     if $do_check; then
2090         # FIXME: what to do if check_config failed?
2091         # i.e. if:
2092         # 1) remote client has mounted other Lustre fs?
2093         # 2) lustre is mounted on remote_clients atall ?
2094         check_config_clients $MOUNT
2095         init_facets_vars
2096         init_param_vars
2097
2098         do_nodes $(comma_list $(nodes_list)) "lctl set_param debug=\\\"$PTLDEBUG\\\";
2099             lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
2100             lctl set_param debug_mb=${DEBUG_SIZE};
2101             sync"
2102     fi
2103
2104     init_gss
2105     set_flavor_all $SEC
2106
2107     if [ "$ONLY" == "setup" ]; then
2108         exit 0
2109     fi
2110 }
2111
2112 restore_mount () {
2113    local clients=${CLIENTS:-$HOSTNAME}
2114    local mntpt=$1
2115
2116    zconf_mount_clients $clients $mntpt
2117 }
2118
2119 cleanup_mount () {
2120     local clients=${CLIENTS:-$HOSTNAME}
2121     local mntpt=$1
2122
2123     zconf_umount_clients $clients $mntpt    
2124 }
2125
2126 cleanup_and_setup_lustre() {
2127     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
2128         lctl set_param debug=0 || true
2129         cleanupall
2130         if [ "$ONLY" == "cleanup" ]; then
2131             exit 0
2132         fi
2133     fi
2134     check_and_setup_lustre
2135 }
2136
2137 check_and_cleanup_lustre() {
2138     if is_mounted $MOUNT; then
2139         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
2140         [ "$ENABLE_QUOTA" ] && restore_quota_type || true
2141     fi
2142
2143     if [ "$I_UMOUNTED2" = "yes" ]; then
2144         restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
2145     fi
2146
2147     if [ "$I_MOUNTED2" = "yes" ]; then
2148         cleanup_mount $MOUNT2
2149     fi
2150
2151     if [ "$I_MOUNTED" = "yes" ]; then
2152         cleanupall -f || error "cleanup failed"
2153         unset I_MOUNTED
2154     fi
2155 }
2156
2157 #######
2158 # General functions
2159
2160 check_network() {
2161     local NETWORK=0
2162     local WAIT=0
2163     local MAX=$2
2164     while [ $NETWORK -eq 0 ]; do
2165         if ping -c 1 -w 3 $1 > /dev/null; then
2166             NETWORK=1
2167         else
2168             WAIT=$((WAIT + 5))
2169             echo "waiting for $1, $((MAX - WAIT)) secs left"
2170             sleep 5
2171         fi
2172         if [ $WAIT -gt $MAX ]; then
2173             echo "Network not available"
2174             exit 1
2175         fi
2176     done
2177 }
2178 check_port() {
2179     while( !($DSH2 $1 "netstat -tna | grep -q $2") ) ; do
2180         sleep 9
2181     done
2182 }
2183
2184 no_dsh() {
2185     shift
2186     eval $@
2187 }
2188
2189 comma_list() {
2190     # the sed converts spaces to commas, but leaves the last space
2191     # alone, so the line doesn't end with a comma.
2192     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
2193 }
2194
2195 # list, excluded are the comma separated lists
2196 exclude_items_from_list () {
2197     local list=$1
2198     local excluded=$2
2199     local item
2200
2201     list=${list//,/ }
2202     for item in ${excluded//,/ }; do
2203         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
2204     done
2205     echo $(comma_list $list) 
2206 }
2207
2208 # list, expand  are the comma separated lists
2209 expand_list () {
2210     local list=${1//,/ }
2211     local expand=${2//,/ }
2212     local expanded=
2213
2214     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
2215     echo $(comma_list $expanded)
2216 }
2217
2218 testslist_filter () {
2219     local script=$LUSTRE/tests/${TESTSUITE}.sh
2220
2221     [ -f $script ] || return 0
2222
2223     local start_at=$START_AT
2224     local stop_at=$STOP_AT
2225
2226     local var=${TESTSUITE//-/_}_START_AT
2227     [ x"${!var}" != x ] && start_at=${!var}
2228     var=${TESTSUITE//-/_}_STOP_AT
2229     [ x"${!var}" != x ] && stop_at=${!var}
2230
2231     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
2232         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
2233             /^'${start_at}'$/ {flag = 0}
2234             {if (flag == 1) print $0}
2235             /^'${stop_at}'$/ { flag = 1 }'
2236 }
2237
2238 absolute_path() {
2239     (cd `dirname $1`; echo $PWD/`basename $1`)
2240 }
2241
2242 get_facets () {
2243     local name=$(echo $1 | tr "[:upper:]" "[:lower:]")
2244     local type=$(echo $1 | tr "[:lower:]" "[:upper:]")
2245
2246     local list=""
2247     local count=${type}COUNT
2248     for ((i=1; i<=${!count}; i++)) do
2249         list="$list ${name}$i"
2250     done
2251     echo $(comma_list $list)
2252 }
2253
2254 ##################################
2255 # Adaptive Timeouts funcs
2256
2257 at_is_enabled() {
2258     # only check mds, we assume at_max is the same on all nodes
2259     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
2260     if [ $at_max -eq 0 ]; then
2261         return 1
2262     else
2263         return 0
2264     fi
2265 }
2266
2267 at_max_get() {
2268     local facet=$1
2269
2270     # suppose that all ost-s has the same at_max set
2271     if [ $facet == "ost" ]; then
2272         do_facet ost1 "lctl get_param -n at_max"
2273     else
2274         do_facet $facet "lctl get_param -n at_max"
2275     fi
2276 }
2277
2278 at_max_set() {
2279     local at_max=$1
2280     shift
2281
2282     local facet
2283     for facet in $@; do
2284         if [ $facet == "ost" ]; then
2285             for i in `seq $OSTCOUNT`; do
2286                 do_facet ost$i "lctl set_param at_max=$at_max"
2287
2288             done
2289         elif [ $facet == "mds" ]; then
2290             for i in `seq $MDSCOUNT`; do
2291                 do_facet mds$i "lctl set_param at_max=$at_max"
2292             done
2293         else
2294             do_facet $facet "lctl set_param at_max=$at_max"
2295         fi
2296     done
2297 }
2298
2299 ##################################
2300 # OBD_FAIL funcs
2301
2302 drop_request() {
2303 # OBD_FAIL_MDS_ALL_REQUEST_NET
2304     RC=0
2305     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
2306     do_facet client "$1" || RC=$?
2307     do_facet $SINGLEMDS lctl set_param fail_loc=0
2308     return $RC
2309 }
2310
2311 drop_reply() {
2312 # OBD_FAIL_MDS_ALL_REPLY_NET
2313     RC=0
2314     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
2315     do_facet client "$@" || RC=$?
2316     do_facet $SINGLEMDS lctl set_param fail_loc=0
2317     return $RC
2318 }
2319
2320 drop_reint_reply() {
2321 # OBD_FAIL_MDS_REINT_NET_REP
2322     RC=0
2323     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
2324     do_facet client "$@" || RC=$?
2325     do_facet $SINGLEMDS lctl set_param fail_loc=0
2326     return $RC
2327 }
2328
2329 pause_bulk() {
2330 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
2331     RC=0
2332     do_facet ost1 lctl set_param fail_loc=0x214
2333     do_facet client "$1" || RC=$?
2334     do_facet client "sync"
2335     do_facet ost1 lctl set_param fail_loc=0
2336     return $RC
2337 }
2338
2339 drop_ldlm_cancel() {
2340 #define OBD_FAIL_LDLM_CANCEL             0x304
2341     RC=0
2342     do_facet client lctl set_param fail_loc=0x304
2343     do_facet client "$@" || RC=$?
2344     do_facet client lctl set_param fail_loc=0
2345     return $RC
2346 }
2347
2348 drop_bl_callback() {
2349 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
2350     RC=0
2351     do_facet client lctl set_param fail_loc=0x305
2352     do_facet client "$@" || RC=$?
2353     do_facet client lctl set_param fail_loc=0
2354     return $RC
2355 }
2356
2357 drop_ldlm_reply() {
2358 #define OBD_FAIL_LDLM_REPLY              0x30c
2359     RC=0
2360     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
2361     do_facet client "$@" || RC=$?
2362     do_facet $SINGLEMDS lctl set_param fail_loc=0
2363     return $RC
2364 }
2365
2366 clear_failloc() {
2367     facet=$1
2368     pause=$2
2369     sleep $pause
2370     echo "clearing fail_loc on $facet"
2371     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
2372 }
2373
2374 set_nodes_failloc () {
2375     do_nodes $(comma_list $1)  lctl set_param fail_loc=$2
2376 }
2377
2378 cancel_lru_locks() {
2379     $LCTL mark "cancel_lru_locks $1 start"
2380     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
2381         $LCTL set_param -n $d=clear
2382     done
2383     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
2384     $LCTL mark "cancel_lru_locks $1 stop"
2385 }
2386
2387 default_lru_size()
2388 {
2389         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
2390         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
2391         echo "$DEFAULT_LRU_SIZE"
2392 }
2393
2394 lru_resize_enable()
2395 {
2396     lctl set_param ldlm.namespaces.*$1*.lru_size=0
2397 }
2398
2399 lru_resize_disable()
2400 {
2401     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
2402 }
2403
2404 pgcache_empty() {
2405     local FILE
2406     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
2407         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
2408             echo there is still data in page cache $FILE ?
2409             lctl get_param -n $FILE
2410             return 1
2411         fi
2412     done
2413     return 0
2414 }
2415
2416 debugsave() {
2417     DEBUGSAVE="$(lctl get_param -n debug)"
2418 }
2419
2420 debugrestore() {
2421     [ -n "$DEBUGSAVE" ] && \
2422         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
2423     DEBUGSAVE=""
2424 }
2425
2426 debug_size_save() {
2427     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
2428 }
2429
2430 debug_size_restore() {
2431     [ -n "$DEBUG_SIZE_SAVED" ] && \
2432         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
2433     DEBUG_SIZE_SAVED=""
2434 }
2435
2436 start_full_debug_logging() {
2437     debugsave
2438     debug_size_save
2439
2440     local FULLDEBUG=-1
2441     local DEBUG_SIZE=150
2442
2443     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
2444     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
2445 }
2446
2447 stop_full_debug_logging() {
2448     debug_size_restore
2449     debugrestore
2450 }
2451
2452 ##################################
2453 # Test interface
2454 ##################################
2455
2456 error_noexit() {
2457     local TYPE=${TYPE:-"FAIL"}
2458
2459     local dump=true
2460     # do not dump logs if $1=false
2461     if [ "x$1" = "xfalse" ]; then
2462         shift
2463         dump=false
2464     fi
2465
2466     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
2467
2468     # We need to dump the logs on all nodes
2469     if $dump; then
2470         gather_logs $(comma_list $(nodes_list))
2471     fi
2472
2473     debugrestore
2474     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
2475     echo "$@" > $LOGDIR/err
2476 }
2477
2478 error() {
2479     error_noexit "$@"
2480     exit 1
2481 }
2482
2483 error_exit() {
2484     error "$@"
2485 }
2486
2487 # use only if we are ignoring failures for this test, bugno required.
2488 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
2489 # e.g. error_ignore 5494 "your message"
2490 error_ignore() {
2491     local TYPE="IGNORE (bz$1)"
2492     shift
2493     error_noexit "$@"
2494 }
2495
2496 skip_env () {
2497     $FAIL_ON_SKIP_ENV && error false $@ || skip $@
2498 }
2499
2500 skip () {
2501     echo
2502     log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
2503     [ "$TESTSUITELOG" ] && \
2504         echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
2505 }
2506
2507 build_test_filter() {
2508     EXCEPT="$EXCEPT $(testslist_filter)"
2509
2510     [ "$ONLY" ] && log "only running test `echo $ONLY`"
2511     for O in $ONLY; do
2512         eval ONLY_${O}=true
2513     done
2514     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
2515         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
2516     [ "$EXCEPT_SLOW" ] && \
2517         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
2518     for E in $EXCEPT $ALWAYS_EXCEPT; do
2519         eval EXCEPT_${E}=true
2520     done
2521     for E in $EXCEPT_SLOW; do
2522         eval EXCEPT_SLOW_${E}=true
2523     done
2524     for G in $GRANT_CHECK_LIST; do
2525         eval GCHECK_ONLY_${G}=true
2526         done
2527 }
2528
2529 basetest() {
2530     if [[ $1 = [a-z]* ]]; then
2531         echo $1
2532     else
2533         echo ${1%%[a-z]*}
2534     fi
2535 }
2536
2537 # print a newline if the last test was skipped
2538 export LAST_SKIPPED=
2539 #
2540 # Main entry into test-framework. This is called with the name and
2541 # description of a test. The name is used to find the function to run
2542 # the test using "test_$name".
2543 #
2544 # This supports a variety of methods of specifying specific test to
2545 # run or not run.  These need to be documented...
2546 #
2547 run_test() {
2548     assert_DIR
2549
2550     export base=`basetest $1`
2551     if [ ! -z "$ONLY" ]; then
2552         testname=ONLY_$1
2553         if [ ${!testname}x != x ]; then
2554             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2555             run_one_logged $1 "$2"
2556             return $?
2557         fi
2558         testname=ONLY_$base
2559         if [ ${!testname}x != x ]; then
2560             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2561             run_one_logged $1 "$2"
2562             return $?
2563         fi
2564         LAST_SKIPPED="y"
2565         echo -n "."
2566         return 0
2567     fi
2568     testname=EXCEPT_$1
2569     if [ ${!testname}x != x ]; then
2570         LAST_SKIPPED="y"
2571         TESTNAME=test_$1 skip "skipping excluded test $1"
2572         return 0
2573     fi
2574     testname=EXCEPT_$base
2575     if [ ${!testname}x != x ]; then
2576         LAST_SKIPPED="y"
2577         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
2578         return 0
2579     fi
2580     testname=EXCEPT_SLOW_$1
2581     if [ ${!testname}x != x ]; then
2582         LAST_SKIPPED="y"
2583         TESTNAME=test_$1 skip "skipping SLOW test $1"
2584         return 0
2585     fi
2586     testname=EXCEPT_SLOW_$base
2587     if [ ${!testname}x != x ]; then
2588         LAST_SKIPPED="y"
2589         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
2590         return 0
2591     fi
2592
2593     LAST_SKIPPED=
2594     run_one_logged $1 "$2"
2595
2596     return $?
2597 }
2598
2599 equals_msg() {
2600     banner "$*"
2601 }
2602
2603 log() {
2604     echo "$*"
2605     module_loaded lnet || load_modules
2606
2607     local MSG="$*"
2608     # Get rid of '
2609     MSG=${MSG//\'/\\\'}
2610     MSG=${MSG//\(/\\\(}
2611     MSG=${MSG//\)/\\\)}
2612     MSG=${MSG//\;/\\\;}
2613     MSG=${MSG//\|/\\\|}
2614     MSG=${MSG//\>/\\\>}
2615     MSG=${MSG//\</\\\<}
2616     MSG=${MSG//\//\\\/}
2617     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
2618 }
2619
2620 trace() {
2621         log "STARTING: $*"
2622         strace -o $TMP/$1.strace -ttt $*
2623         RC=$?
2624         log "FINISHED: $*: rc $RC"
2625         return 1
2626 }
2627
2628 pass() {
2629     # Set TEST_STATUS here; will be used for logging the result
2630     if [ -f $LOGDIR/err ]; then
2631         TEST_STATUS="FAIL"
2632     else
2633         TEST_STATUS="PASS"
2634     fi
2635     echo $TEST_STATUS " " $@
2636 }
2637
2638 check_mds() {
2639     FFREE=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filesfree | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2640     FTOTAL=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filestotal | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2641     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
2642 }
2643
2644 reset_fail_loc () {
2645     echo -n "Resetting fail_loc on all nodes..."
2646     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
2647     echo done.
2648 }
2649
2650
2651 #
2652 # Log a message (on all nodes) padded with "=" before and after. 
2653 # Also appends a timestamp and prepends the testsuite name.
2654
2655
2656 EQUALS="===================================================================================================="
2657 banner() {
2658     msg="== ${TESTSUITE} $*"
2659     last=${msg: -1:1}
2660     [[ $last != "=" && $last != " " ]] && msg="$msg "
2661     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
2662     # always include at least == after the message
2663     log "$msg== $(date +"%H:%M:%S (%s)")"
2664 }
2665
2666 #
2667 # Run a single test function and cleanup after it.  
2668 #
2669 # This function should be run in a subshell so the test func can
2670 # exit() without stopping the whole script.
2671 #
2672 run_one() {
2673     local testnum=$1
2674     local message=$2
2675     tfile=f${testnum}
2676     export tdir=d0.${TESTSUITE}/d${base}
2677     export TESTNAME=test_$testnum
2678     local SAVE_UMASK=`umask`
2679     umask 0022
2680
2681     banner "test $testnum: $message"
2682     test_${testnum} || error "test_$testnum failed with $?"
2683     cd $SAVE_PWD
2684     reset_fail_loc
2685     check_grant ${testnum} || error "check_grant $testnum failed with $?"
2686     check_catastrophe || error "LBUG/LASSERT detected"
2687     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
2688     unset TESTNAME
2689     unset tdir
2690     umask $SAVE_UMASK
2691     return 0
2692 }
2693
2694 #
2695 # Wrapper around run_one to ensure:
2696 #  - test runs in subshell
2697 #  - output of test is saved to separate log file for error reporting
2698 #  - test result is saved to data file
2699 #
2700 run_one_logged() {
2701     local BEFORE=`date +%s`
2702     local TEST_ERROR
2703     local name=${TESTSUITE}.test_${1}.test_log.$(hostname).log
2704     local test_log=$LOGDIR/$name
2705     rm -rf $LOGDIR/err
2706
2707     echo
2708     log_sub_test_begin test_${1}
2709     (run_one $1 "$2") 2>&1 | tee $test_log
2710     local RC=${PIPESTATUS[0]}
2711
2712     [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] && \
2713         echo "test_$1 returned $RC" | tee $LOGDIR/err
2714
2715     duration=$((`date +%s` - $BEFORE))
2716     pass "(${duration}s)"
2717     [ -f $LOGDIR/err ] && TEST_ERROR=$(cat $LOGDIR/err)
2718     log_sub_test_end $TEST_STATUS $duration "$RC" "$TEST_ERROR"
2719
2720     if [ -f $LOGDIR/err ]; then
2721         $FAIL_ON_ERROR && exit $RC
2722     fi
2723
2724     return 0
2725 }
2726
2727 canonical_path() {
2728     (cd `dirname $1`; echo $PWD/`basename $1`)
2729 }
2730
2731 sync_clients() {
2732     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
2733     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
2734         cd $SAVE_PWD
2735 }
2736
2737 check_grant() {
2738     export base=`basetest $1`
2739     [ "$CHECK_GRANT" == "no" ] && return 0
2740
2741         testname=GCHECK_ONLY_${base}
2742         [ ${!testname}x == x ] && return 0
2743
2744     echo -n "checking grant......"
2745         cd $SAVE_PWD
2746         # write some data to sync client lost_grant
2747         rm -f $DIR1/${tfile}_check_grant_* 2>&1
2748         for i in `seq $OSTCOUNT`; do
2749                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
2750                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
2751                                               count=1 > /dev/null 2>&1
2752         done
2753         # sync all the data and make sure no pending data on server
2754         sync_clients
2755         
2756         #get client grant and server grant
2757         client_grant=0
2758     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
2759                 client_grant=$((client_grant + $d))
2760         done
2761         server_grant=0
2762         for d in `lctl get_param -n obdfilter.*.tot_granted`; do
2763                 server_grant=$((server_grant + $d))
2764         done
2765
2766         # cleanup the check_grant file
2767         for i in `seq $OSTCOUNT`; do
2768                 rm $DIR1/${tfile}_check_grant_$i
2769         done
2770
2771         #check whether client grant == server grant
2772         if [ $client_grant != $server_grant ]; then
2773                 echo "failed: client:${client_grant} server: ${server_grant}"
2774                 return 1
2775         else
2776                 echo "pass"
2777         fi
2778 }
2779
2780 ########################
2781 # helper functions
2782
2783 osc_to_ost()
2784 {
2785     osc=$1
2786     ost=`echo $1 | awk -F_ '{print $3}'`
2787     if [ -z $ost ]; then
2788         ost=`echo $1 | sed 's/-osc.*//'`
2789     fi
2790     echo $ost
2791 }
2792
2793 remote_node () {
2794     local node=$1
2795     [ "$node" != "$(hostname)" ]
2796 }
2797
2798 remote_mds ()
2799 {
2800     local node
2801     for node in $(mdts_nodes); do
2802         remote_node $node && return 0
2803     done
2804     return 1
2805 }
2806
2807 remote_mds_nodsh()
2808 {
2809     [ "$CLIENTONLY" ] && return 0 || true
2810     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
2811 }
2812
2813 require_dsh_mds()
2814 {
2815         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
2816             MSKIPPED=1 && return 1
2817         return 0
2818 }
2819
2820 remote_ost ()
2821 {
2822     local node
2823     for node in $(osts_nodes) ; do
2824         remote_node $node && return 0
2825     done
2826     return 1
2827 }
2828
2829 remote_ost_nodsh()
2830 {
2831     [ "$CLIENTONLY" ] && return 0 || true 
2832     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2833 }
2834
2835 require_dsh_ost()
2836 {
2837         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
2838             OSKIPPED=1 && return 1
2839         return 0
2840 }
2841
2842 remote_mgs_nodsh()
2843 {
2844     local MGS 
2845     MGS=$(facet_host mgs)
2846     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2847 }
2848
2849 local_mode ()
2850 {
2851     remote_mds_nodsh || remote_ost_nodsh || \
2852         $(single_local_node $(comma_list $(nodes_list)))
2853 }
2854
2855 mdts_nodes () {
2856     local MDSNODES
2857     local NODES_sort
2858     for num in `seq $MDSCOUNT`; do
2859         MDSNODES="$MDSNODES $(facet_host mds$num)"
2860     done
2861     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
2862
2863     echo $NODES_sort
2864 }
2865
2866 remote_servers () {
2867     remote_ost && remote_mds
2868 }
2869
2870 osts_nodes () {
2871     local OSTNODES=$(facet_host ost1)
2872     local NODES_sort
2873
2874     for num in `seq $OSTCOUNT`; do
2875         local myOST=$(facet_host ost$num)
2876         OSTNODES="$OSTNODES $myOST"
2877     done
2878     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
2879
2880     echo $NODES_sort
2881 }
2882
2883 nodes_list () {
2884     # FIXME. We need a list of clients
2885     local myNODES=$HOSTNAME
2886     local myNODES_sort
2887
2888     # CLIENTS (if specified) contains the local client
2889     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
2890
2891     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
2892         myNODES="$myNODES $(osts_nodes) $(mdts_nodes)"
2893     fi
2894
2895     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
2896
2897     echo $myNODES_sort
2898 }
2899
2900 remote_nodes_list () {
2901     local rnodes=$(nodes_list)
2902     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2903     echo $rnodes
2904 }
2905
2906 init_clients_lists () {
2907     # Sanity check: exclude the local client from RCLIENTS
2908     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2909
2910     # Sanity check: exclude the dup entries
2911     rclients=$(for i in $rclients; do echo $i; done | sort -u)
2912
2913     local clients="$SINGLECLIENT $HOSTNAME $rclients"
2914
2915     # Sanity check: exclude the dup entries from CLIENTS
2916     # for those configs which has SINGLCLIENT set to local client
2917     clients=$(for i in $clients; do echo $i; done | sort -u)
2918
2919     CLIENTS=`comma_list $clients`
2920     local -a remoteclients=($rclients)
2921     for ((i=0; $i<${#remoteclients[@]}; i++)); do
2922             varname=CLIENT$((i + 2))
2923             eval $varname=${remoteclients[i]}
2924     done
2925
2926     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
2927 }
2928
2929 get_random_entry () {
2930     local rnodes=$1
2931
2932     rnodes=${rnodes//,/ }
2933
2934     local -a nodes=($rnodes)
2935     local num=${#nodes[@]} 
2936     local i=$((RANDOM * num * 2 / 65536))
2937
2938     echo ${nodes[i]}
2939 }
2940
2941 client_only () {
2942     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
2943 }
2944
2945 is_patchless ()
2946 {
2947     lctl get_param version | grep -q patchless
2948 }
2949
2950 check_versions () {
2951     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
2952 }
2953
2954 get_node_count() {
2955     local nodes="$@"
2956     echo $nodes | wc -w || true
2957 }
2958
2959 mixed_ost_devs () {
2960     local nodes=$(osts_nodes)
2961     local osscount=$(get_node_count "$nodes")
2962     [ ! "$OSTCOUNT" = "$osscount" ]
2963 }
2964
2965 mixed_mdt_devs () {
2966     local nodes=$(mdts_nodes)
2967     local mdtcount=$(get_node_count "$nodes")
2968     [ ! "$MDSCOUNT" = "$mdtcount" ]
2969 }
2970
2971 generate_machine_file() {
2972     local nodes=${1//,/ }
2973     local machinefile=$2
2974     rm -f $machinefile
2975     for node in $nodes; do
2976         echo $node >>$machinefile || \
2977             { echo "can not generate machinefile $machinefile" && return 1; }
2978     done
2979 }
2980
2981 get_stripe () {
2982     local file=$1/stripe
2983     touch $file
2984     $LFS getstripe -v $file || error
2985     rm -f $file
2986 }
2987
2988 setstripe_nfsserver () {
2989     local dir=$1
2990
2991     local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
2992                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -1)
2993
2994     [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
2995
2996     do_nodev $nfsserver lfs setstripe "$@"
2997 }
2998
2999 check_runas_id_ret() {
3000     local myRC=0
3001     local myRUNAS_UID=$1
3002     local myRUNAS_GID=$2
3003     shift 2
3004     local myRUNAS=$@
3005     if [ -z "$myRUNAS" ]; then
3006         error_exit "myRUNAS command must be specified for check_runas_id"
3007     fi
3008     if $GSS_KRB5; then
3009         $myRUNAS krb5_login.sh || \
3010             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
3011     fi
3012     mkdir $DIR/d0_runas_test
3013     chmod 0755 $DIR
3014     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
3015     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
3016     rm -rf $DIR/d0_runas_test
3017     return $myRC
3018 }
3019
3020 check_runas_id() {
3021     local myRUNAS_UID=$1
3022     local myRUNAS_GID=$2
3023     shift 2
3024     local myRUNAS=$@
3025     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
3026         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
3027         Please set RUNAS_ID to some UID which exists on MDS and client or
3028         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
3029 }
3030
3031 # obtain the UID/GID for MPI_USER
3032 get_mpiuser_id() {
3033     local mpi_user=$1
3034
3035     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
3036 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
3037
3038     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
3039 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
3040 }
3041
3042 # obtain and cache Kerberos ticket-granting ticket
3043 refresh_krb5_tgt() {
3044     local myRUNAS_UID=$1
3045     local myRUNAS_GID=$2
3046     shift 2
3047     local myRUNAS=$@
3048     if [ -z "$myRUNAS" ]; then
3049         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
3050     fi
3051
3052     CLIENTS=${CLIENTS:-$HOSTNAME}
3053     do_nodes $CLIENTS "set -x
3054 if ! $myRUNAS krb5_login.sh; then
3055     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
3056     exit 1
3057 fi"
3058 }
3059
3060 # Run multiop in the background, but wait for it to print
3061 # "PAUSING" to its stdout before returning from this function.
3062 multiop_bg_pause() {
3063     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
3064     FILE=$1
3065     ARGS=$2
3066
3067     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
3068     mkfifo $TMPPIPE
3069
3070     echo "$MULTIOP_PROG $FILE v$ARGS"
3071     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
3072
3073     echo "TMPPIPE=${TMPPIPE}"
3074     read -t 60 multiop_output < $TMPPIPE
3075     if [ $? -ne 0 ]; then
3076         rm -f $TMPPIPE
3077         return 1
3078     fi
3079     rm -f $TMPPIPE
3080     if [ "$multiop_output" != "PAUSING" ]; then
3081         echo "Incorrect multiop output: $multiop_output"
3082         kill -9 $PID
3083         return 1
3084     fi
3085
3086     return 0
3087 }
3088
3089 do_and_time () {
3090     local cmd=$1
3091     local rc
3092
3093     SECONDS=0
3094     eval '$cmd'
3095     
3096     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
3097
3098     echo $SECONDS
3099     return $rc
3100 }
3101
3102 inodes_available () {
3103     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
3104     echo $IFree
3105 }
3106
3107 mdsrate_inodes_available () {
3108     echo $(($(inodes_available) - 1))
3109 }
3110
3111 # reset llite stat counters
3112 clear_llite_stats(){
3113         lctl set_param -n llite.*.stats 0
3114 }
3115
3116 # sum llite stat items
3117 calc_llite_stats() {
3118         local res=$(lctl get_param -n llite.*.stats |
3119                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
3120         echo $res
3121 }
3122
3123 # reset osc stat counters
3124 clear_osc_stats(){
3125         lctl set_param -n osc.*.osc_stats 0
3126 }
3127
3128 # sum osc stat items
3129 calc_osc_stats() {
3130         local res=$(lctl get_param -n osc.*.osc_stats |
3131                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
3132         echo $res
3133 }
3134
3135 calc_sum () {
3136         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
3137 }
3138
3139 calc_osc_kbytes () {
3140         df $MOUNT > /dev/null
3141         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
3142 }
3143
3144 # save_lustre_params(node, parameter_mask)
3145 # generate a stream of formatted strings (<node> <param name>=<param value>)
3146 save_lustre_params() {
3147         local s
3148         do_nodesv $1 "lctl get_param $2 | while read s; do echo \\\$s; done"
3149 }
3150
3151 # restore lustre parameters from input stream, produces by save_lustre_params
3152 restore_lustre_params() {
3153         local node
3154         local name
3155         local val
3156         while IFS=" =" read node name val; do
3157                 do_node ${node//:/} "lctl set_param -n $name $val"
3158         done
3159 }
3160
3161 check_catastrophe() {
3162     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
3163     local C=$CATASTROPHE
3164     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
3165
3166     if [ $rnodes ]; then
3167         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
3168 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
3169 exit \\\$rc;"
3170     fi 
3171 }
3172
3173 # $1 node
3174 # $2 file
3175 # $3 $RUNAS
3176 get_stripe_info() {
3177         local tmp_file
3178
3179         stripe_size=0
3180         stripe_count=0
3181         stripe_index=0
3182         tmp_file=$(mktemp)
3183
3184         do_facet $1 $3 lfs getstripe -v $2 > $tmp_file
3185
3186         stripe_size=`awk '$1 ~ /size/ {print $2}' $tmp_file`
3187         stripe_count=`awk '$1 ~ /count/ {print $2}' $tmp_file`
3188         stripe_index=`awk '$1 ~ /stripe_offset/ {print $2}' $tmp_file`
3189         rm -f $tmp_file
3190 }
3191
3192 # CMD: determine mds index where directory inode presents
3193 get_mds_dir () {
3194     local dir=$1
3195     local file=$dir/f0.get_mds_dir_tmpfile
3196
3197     mkdir -p $dir
3198     rm -f $file
3199     sleep 1
3200     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
3201     local -a oldused=($iused)
3202
3203     openfile -f O_CREAT:O_LOV_DELAY_CREATE -m 0644 $file > /dev/null
3204     sleep 1
3205     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
3206     local -a newused=($iused)
3207
3208     local num=0
3209     for ((i=0; i<${#newused[@]}; i++)); do
3210          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
3211              echo $(( i + 1 ))
3212              rm -f $file
3213              return 0
3214          fi
3215     done
3216     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
3217 }
3218
3219 mdsrate_cleanup () {
3220     if [ -d $4 ]; then
3221         mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
3222         rmdir $4
3223     fi
3224 }
3225
3226 delayed_recovery_enabled () {
3227     local var=${SINGLEMDS}_svc
3228     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
3229 }
3230
3231 ########################
3232
3233 convert_facet2label() { 
3234     local facet=$1
3235
3236     if [ x$facet = xost ]; then
3237        facet=ost1
3238     fi
3239
3240     local varsvc=${facet}_svc
3241
3242     if [ -n ${!varsvc} ]; then
3243         echo ${!varsvc}
3244     else  
3245         error "No lablel for $facet!"
3246     fi
3247 }
3248
3249 get_clientosc_proc_path() {
3250     local ost=$1
3251
3252     echo "{$1}-osc-*"
3253 }
3254
3255 get_lustre_version () {
3256     local node=${1:-"mds"}    
3257     do_facet $node $LCTL get_param -n version |  awk '/^lustre:/ {print $2}'
3258 }
3259
3260 get_mds_version_major () {
3261     local version=$(get_lustre_version mds)
3262     echo $version | awk -F. '{print $1}'
3263 }
3264
3265 get_mds_version_minor () {
3266     local version=$(get_lustre_version mds)
3267     echo $version | awk -F. '{print $2}'
3268 }
3269
3270 get_mdtosc_proc_path() {
3271     local ost=$1
3272     local major=$(get_mds_version_major)
3273     local minor=$(get_mds_version_minor)
3274     if [ $major -le 1 -a $minor -le 8 ] ; then
3275         echo "${ost}-osc"
3276     else
3277         echo "${ost}-osc-MDT0000"
3278     fi
3279 }
3280
3281 get_osc_import_name() {
3282     local facet=$1
3283     local ost=$2
3284     local label=$(convert_facet2label $ost)
3285
3286     if [ "$facet" == "mds" ]; then
3287         get_mdtosc_proc_path $label
3288         return 0
3289     fi
3290
3291     get_clientosc_proc_path $label
3292     return 0
3293 }
3294
3295 wait_import_state () {
3296     local expected=$1
3297     local CONN_PROC=$2
3298     local CONN_STATE
3299     local i=0
3300
3301     CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3302     while [ "${CONN_STATE}" != "${expected}" ]; do
3303         if [ "${expected}" == "DISCONN" ]; then
3304             # for disconn we can check after proc entry is removed
3305             [ "x${CONN_STATE}" == "x" ] && return 0
3306             #  with AT we can have connect request timeout ~ reconnect timeout
3307             # and test can't see real disconnect
3308             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
3309         fi
3310         # disconnect rpc should be wait not more obd_timeout
3311         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
3312             error "can't put import for $CONN_PROC into ${expected} state" && return 1
3313         sleep 1
3314         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3315         i=$(($i + 1))
3316     done
3317
3318     log "$CONN_PROC now in ${CONN_STATE} state"
3319     return 0
3320 }
3321
3322 wait_osc_import_state() {
3323     local facet=$1
3324     local ost_facet=$2
3325     local expected=$3
3326     local ost=$(get_osc_import_name $facet $ost_facet)
3327     local CONN_PROC
3328     local CONN_STATE
3329     local i=0
3330
3331     CONN_PROC="osc.${ost}.ost_server_uuid"
3332     CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3333     while [ "${CONN_STATE}" != "${expected}" ]; do
3334         if [ "${expected}" == "DISCONN" ]; then 
3335             # for disconn we can check after proc entry is removed
3336             [ "x${CONN_STATE}" == "x" ] && return 0
3337             #  with AT we can have connect request timeout ~ reconnect timeout
3338             # and test can't see real disconnect
3339             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
3340         fi
3341         # disconnect rpc should be wait not more obd_timeout
3342         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
3343             error "can't put import for ${ost}(${ost_facet}) into ${expected} state" && return 1
3344         sleep 1
3345         CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3346         i=$(($i + 1))
3347     done
3348
3349     log "${ost_facet} now in ${CONN_STATE} state"
3350     return 0
3351 }
3352 get_clientmdc_proc_path() {
3353     echo "${1}-mdc-*"
3354 }
3355
3356 do_rpc_nodes () {
3357     local list=$1
3358     shift
3359
3360     # Add paths to lustre tests for 32 and 64 bit systems.
3361     local RPATH="$RLUSTRE/tests:/usr/lib/lustre/tests:/usr/lib64/lustre/tests:$PATH"
3362     do_nodesv $list "PATH=$RPATH sh rpc.sh $@ "
3363 }
3364
3365 wait_clients_import_state () {
3366     local list=$1
3367     local facet=$2
3368     local expected=$3
3369     shift
3370
3371     local label=$(convert_facet2label $facet)
3372     local proc_path
3373     case $facet in
3374         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
3375         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
3376         *) error "unknown facet!" ;;
3377     esac
3378
3379     if ! do_rpc_nodes $list wait_import_state $expected $proc_path; then
3380         error "import is not in ${expected} state"
3381         return 1
3382     fi
3383 }
3384
3385 oos_full() {
3386         local -a AVAILA
3387         local -a GRANTA
3388         local OSCFULL=1
3389         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
3390                   $LCTL get_param obdfilter.*.kbytesavail))
3391         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
3392                   $LCTL get_param -n obdfilter.*.tot_granted))
3393         for ((i=0; i<${#AVAILA[@]}; i++)); do
3394                 local -a AVAIL1=(${AVAILA[$i]//=/ })
3395                 GRANT=$((${GRANTA[$i]}/1024))
3396                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} grnt=$GRANT diff=$((AVAIL1[1] - GRANT))
3397                 [ $((AVAIL1[1] - GRANT)) -lt 400 ] && OSCFULL=0 && echo " FULL" || echo
3398         done
3399         return $OSCFULL
3400 }
3401
3402 pool_list () {
3403    do_facet mgs lctl pool_list $1
3404 }
3405
3406 create_pool() {
3407     local fsname=${1%%.*}
3408     local poolname=${1##$fsname.}
3409
3410     do_facet mgs lctl pool_new $1
3411     local RC=$?
3412     # get param should return err unless pool is created
3413     [[ $RC -ne 0 ]] && return $RC
3414
3415     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
3416         2>/dev/null || echo foo" "" || RC=1
3417     if [[ $RC -eq 0 ]]; then
3418         add_pool_to_list $1
3419     else
3420         error "pool_new failed $1"
3421     fi
3422     return $RC
3423 }
3424
3425 add_pool_to_list () {
3426     local fsname=${1%%.*}
3427     local poolname=${1##$fsname.}
3428
3429     local listvar=${fsname}_CREATED_POOLS
3430     eval export ${listvar}=$(expand_list ${!listvar} $poolname)
3431 }
3432
3433 remove_pool_from_list () {
3434     local fsname=${1%%.*}
3435     local poolname=${1##$fsname.}
3436
3437     local listvar=${fsname}_CREATED_POOLS
3438     eval export ${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
3439 }
3440
3441 destroy_pool_int() {
3442     local ost
3443     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
3444         awk '$1 !~ /^Pool:/ {print $1}')
3445     for ost in $OSTS; do
3446         do_facet mgs lctl pool_remove $1 $ost
3447     done
3448     do_facet mgs lctl pool_destroy $1
3449 }
3450
3451 # <fsname>.<poolname> or <poolname>
3452 destroy_pool() {
3453     local fsname=${1%%.*}
3454     local poolname=${1##$fsname.}
3455
3456     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
3457
3458     local RC
3459
3460     pool_list $fsname.$poolname || return $?
3461
3462     destroy_pool_int $fsname.$poolname
3463     RC=$?
3464     [[ $RC -ne 0 ]] && return $RC
3465
3466     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
3467       2>/dev/null || echo foo" "foo" || RC=1
3468
3469     if [[ $RC -eq 0 ]]; then
3470         remove_pool_from_list $fsname.$poolname
3471     else
3472         error "destroy pool failed $1"
3473     fi
3474     return $RC
3475 }
3476
3477 destroy_pools () {
3478     local fsname=${1:-$FSNAME}
3479     local poolname
3480     local listvar=${fsname}_CREATED_POOLS
3481
3482     pool_list $fsname
3483
3484     [ x${!listvar} = x ] && return 0
3485
3486     echo destroy the created pools: ${!listvar}
3487     for poolname in ${!listvar//,/ }; do
3488         destroy_pool $fsname.$poolname 
3489     done
3490 }
3491
3492 cleanup_pools () {
3493     local fsname=${1:-$FSNAME}
3494     trap 0
3495     destroy_pools $fsname
3496 }
3497
3498 gather_logs () {
3499     local list=$1
3500
3501     local ts=$(date +%s)
3502
3503     # bug 20237, comment 11
3504     # It would also be useful to provide the option
3505     # of writing the file to an NFS directory so it doesn't need to be copied.
3506     local tmp=$TMP
3507     local docp=true
3508     [ -f $LOGDIR/shared ] && docp=false
3509  
3510     # dump lustre logs, dmesg
3511
3512     prefix="$LOGDIR/${TESTSUITE}.${TESTNAME}"
3513     suffix="$ts.log"
3514     echo "Dumping lctl log to ${prefix}.*.${suffix}"
3515
3516     if [ "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
3517         echo "Dumping logs only on local client."
3518         $LCTL dk > ${prefix}.debug_log.$(hostname).${suffix}
3519         dmesg > ${prefix}.dmesg.$(hostname).${suffix}
3520         return
3521     fi
3522
3523     do_nodesv $list \
3524         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname).${suffix};
3525          dmesg > ${prefix}.dmesg.\\\$(hostname).${suffix}"
3526     if [ ! -f $LOGDIR/shared ]; then
3527         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
3528       fi
3529
3530     local archive=$LOGDIR/${TESTSUITE}-$ts.tar.bz2
3531     tar -jcf $archive $LOGDIR/*$ts* $LOGDIR/*${TESTSUITE}*
3532
3533     echo $archive
3534 }
3535
3536 cleanup_logs () {
3537     local list=${1:-$(comma_list $(nodes_list))}
3538
3539     [ -n ${TESTSUITE} ] && do_nodes $list "rm -f $TMP/*${TESTSUITE}*" || true
3540 }
3541
3542 do_ls () {
3543     local mntpt_root=$1
3544     local num_mntpts=$2
3545     local dir=$3
3546     local i
3547     local cmd
3548     local pids
3549     local rc=0
3550
3551     for i in $(seq 0 $num_mntpts); do
3552         cmd="ls -laf ${mntpt_root}$i/$dir"
3553         echo + $cmd;
3554         $cmd > /dev/null &
3555         pids="$pids $!"
3556     done
3557     echo pids=$pids
3558     for pid in $pids; do
3559         wait $pid || rc=$?
3560     done
3561
3562     return $rc
3563 }
3564
3565 # target_start_and_reset_recovery_timer()
3566 #        service_time = at_est2timeout(service_time);
3567 #        service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC +
3568 #                             INITIAL_CONNECT_TIMEOUT);
3569 # CONNECTION_SWITCH_MAX : min(25U, max(CONNECTION_SWITCH_MIN,obd_timeout))
3570 #define CONNECTION_SWITCH_INC 1
3571 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
3572 #define CONNECTION_SWITCH_MIN 5U
3573
3574 max_recovery_time () {
3575     local init_connect_timeout=$(( TIMEOUT / 20 ))
3576     [[ $init_connect_timeout > 5 ]] || init_connect_timeout=5 
3577
3578     local service_time=$(( $(at_max_get client) + $(( 2 * $(( 25 + 1  + init_connect_timeout)) )) ))
3579
3580     echo $service_time 
3581 }
3582
3583 get_clients_mount_count () {
3584     local clients=${CLIENTS:-`hostname`}
3585
3586     # we need to take into account the clients mounts and
3587     # exclude mds/ost mounts if any;
3588     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
3589 }
3590
3591 # gss functions
3592 PROC_CLI="srpc_info"
3593
3594 combination()
3595 {
3596     local M=$1
3597     local N=$2
3598     local R=1
3599
3600     if [ $M -lt $N ]; then
3601         R=0
3602     else
3603         N=$((N + 1))
3604         while [ $N -le $M ]; do
3605             R=$((R * N))
3606             N=$((N + 1))
3607         done
3608     fi
3609
3610     echo $R
3611     return 0
3612 }
3613
3614 calc_connection_cnt() {
3615     local dir=$1
3616
3617     # MDT->MDT = 2 * C(M, 2)
3618     # MDT->OST = M * O
3619     # CLI->OST = C * O
3620     # CLI->MDT = C * M
3621     comb_m2=$(combination $MDSCOUNT 2)
3622
3623     local num_clients=$(get_clients_mount_count)
3624
3625     local cnt_mdt2mdt=$((comb_m2 * 2))
3626     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
3627     local cnt_cli2ost=$((num_clients * OSTCOUNT))
3628     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
3629     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
3630     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
3631     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
3632
3633     local var=cnt_$dir
3634     local res=${!var}
3635
3636     echo $res
3637 }
3638
3639 set_rule()
3640 {
3641     local tgt=$1
3642     local net=$2
3643     local dir=$3
3644     local flavor=$4
3645     local cmd="$tgt.srpc.flavor"
3646
3647     if [ $net == "any" ]; then
3648         net="default"
3649     fi
3650     cmd="$cmd.$net"
3651
3652     if [ $dir != "any" ]; then
3653         cmd="$cmd.$dir"
3654     fi
3655
3656     cmd="$cmd=$flavor"
3657     log "Setting sptlrpc rule: $cmd"
3658     do_facet mgs "$LCTL conf_param $cmd"
3659 }
3660
3661 count_flvr()
3662 {
3663     local output=$1
3664     local flavor=$2
3665     local count=0
3666
3667     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
3668     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
3669
3670     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
3671
3672     if [ "x$bulkspec" != "x" ]; then
3673         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
3674
3675         if [ "x$algs" != "x" ]; then
3676             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
3677         else
3678             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
3679             if [ $bulk == "bulkn" ]; then
3680                 bulk_count=`echo "$output" | grep "bulk flavor" \
3681                             | grep "null/null" | wc -l`
3682             elif [ $bulk == "bulki" ]; then
3683                 bulk_count=`echo "$output" | grep "bulk flavor" \
3684                             | grep "/null" | grep -v "null/" | wc -l`
3685             else
3686                 bulk_count=`echo "$output" | grep "bulk flavor" \
3687                             | grep -v "/null" | grep -v "null/" | wc -l`
3688             fi
3689         fi
3690
3691         [ $bulk_count -lt $count ] && count=$bulk_count
3692     fi
3693
3694     echo $count
3695 }
3696
3697 flvr_cnt_cli2mdt()
3698 {
3699     local flavor=$1
3700     local cnt
3701
3702     local clients=${CLIENTS:-`hostname`}
3703
3704     for c in ${clients//,/ }; do
3705         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
3706         tmpcnt=`count_flvr "$output" $flavor`
3707         cnt=$((cnt + tmpcnt))
3708     done
3709     echo $cnt
3710 }
3711
3712 flvr_cnt_cli2ost()
3713 {
3714     local flavor=$1
3715     local cnt
3716
3717     local clients=${CLIENTS:-`hostname`}
3718
3719     for c in ${clients//,/ }; do
3720         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
3721         tmpcnt=`count_flvr "$output" $flavor`
3722         cnt=$((cnt + tmpcnt))
3723     done
3724     echo $cnt
3725 }
3726
3727 flvr_cnt_mdt2mdt()
3728 {
3729     local flavor=$1
3730     local cnt=0
3731
3732     if [ $MDSCOUNT -le 1 ]; then
3733         echo 0
3734         return
3735     fi
3736
3737     for num in `seq $MDSCOUNT`; do
3738         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
3739         tmpcnt=`count_flvr "$output" $flavor`
3740         cnt=$((cnt + tmpcnt))
3741     done
3742     echo $cnt;
3743 }
3744
3745 flvr_cnt_mdt2ost()
3746 {
3747     local flavor=$1
3748     local cnt=0
3749
3750     for num in `seq $MDSCOUNT`; do
3751         output=`do_facet mds$num lctl get_param -n osc.*OST*-osc-MDT*.$PROC_CLI 2>/dev/null`
3752         tmpcnt=`count_flvr "$output" $flavor`
3753         cnt=$((cnt + tmpcnt))
3754     done
3755     echo $cnt;
3756 }
3757
3758 flvr_cnt_mgc2mgs()
3759 {
3760     local flavor=$1
3761
3762     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
3763     count_flvr "$output" $flavor
3764 }
3765
3766 do_check_flavor()
3767 {
3768     local dir=$1        # from to
3769     local flavor=$2     # flavor expected
3770     local res=0
3771
3772     if [ $dir == "cli2mdt" ]; then
3773         res=`flvr_cnt_cli2mdt $flavor`
3774     elif [ $dir == "cli2ost" ]; then
3775         res=`flvr_cnt_cli2ost $flavor`
3776     elif [ $dir == "mdt2mdt" ]; then
3777         res=`flvr_cnt_mdt2mdt $flavor`
3778     elif [ $dir == "mdt2ost" ]; then
3779         res=`flvr_cnt_mdt2ost $flavor`
3780     elif [ $dir == "all2ost" ]; then
3781         res1=`flvr_cnt_mdt2ost $flavor`
3782         res2=`flvr_cnt_cli2ost $flavor`
3783         res=$((res1 + res2))
3784     elif [ $dir == "all2mdt" ]; then
3785         res1=`flvr_cnt_mdt2mdt $flavor`
3786         res2=`flvr_cnt_cli2mdt $flavor`
3787         res=$((res1 + res2))
3788     elif [ $dir == "all2all" ]; then
3789         res1=`flvr_cnt_mdt2ost $flavor`
3790         res2=`flvr_cnt_cli2ost $flavor`
3791         res3=`flvr_cnt_mdt2mdt $flavor`
3792         res4=`flvr_cnt_cli2mdt $flavor`
3793         res=$((res1 + res2 + res3 + res4))
3794     fi
3795
3796     echo $res
3797 }
3798
3799 wait_flavor()
3800 {
3801     local dir=$1        # from to
3802     local flavor=$2     # flavor expected
3803     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
3804
3805     local res=0
3806
3807     for ((i=0;i<20;i++)); do
3808         echo -n "checking..."
3809         res=$(do_check_flavor $dir $flavor)
3810         if [ $res -eq $expect ]; then
3811             echo "found $res $flavor connections of $dir, OK"
3812             return 0
3813         else
3814             echo "found $res $flavor connections of $dir, not ready ($expect)"
3815             sleep 4
3816         fi
3817     done
3818
3819     echo "Error checking $flavor of $dir: expect $expect, actual $res"
3820     return 1
3821 }
3822
3823 restore_to_default_flavor()
3824 {
3825     local proc="mgs.MGS.live.$FSNAME"
3826
3827     echo "restoring to default flavor..."
3828
3829     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
3830
3831     # remove all existing rules if any
3832     if [ $nrule -ne 0 ]; then
3833         echo "$nrule existing rules"
3834         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
3835             echo "remove rule: $rule"
3836             spec=`echo $rule | awk -F = '{print $1}'`
3837             do_facet mgs "$LCTL conf_param $spec="
3838         done
3839     fi
3840
3841     # verify no rules left
3842     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
3843     [ $nrule -ne 0 ] && error "still $nrule rules left"
3844
3845     # wait for default flavor to be applied
3846     # currently default flavor for all connections are 'null'
3847     wait_flavor all2all null
3848     echo "now at default flavor settings"
3849 }
3850
3851 set_flavor_all()
3852 {
3853     local flavor=${1:-null}
3854
3855     echo "setting all flavor to $flavor"
3856
3857     # FIXME need parameter to this fn
3858     # and remove global vars
3859     local cnt_all2all=$(calc_connection_cnt all2all)
3860
3861     local res=$(do_check_flavor all2all $flavor)
3862     if [ $res -eq $cnt_all2all ]; then
3863         echo "already have total $res $flavor connections"
3864         return
3865     fi
3866
3867     echo "found $res $flavor out of total $cnt_all2all connections"
3868     restore_to_default_flavor
3869
3870     [[ $flavor = null ]] && return 0
3871
3872     set_rule $FSNAME any any $flavor
3873     wait_flavor all2all $flavor
3874 }
3875
3876
3877 check_logdir() {
3878     local dir=$1
3879     # Checking for shared logdir
3880     if [ ! -d $dir ]; then
3881         # Not found. Create local logdir
3882         mkdir -p $dir
3883     else
3884         touch $dir/node.$(hostname).yml
3885     fi
3886     return 0
3887 }
3888
3889 check_write_access() {
3890     local dir=$1
3891     for node in $(nodes_list); do
3892         if [ ! -f "$dir/node.${node}.yml" ]; then
3893             # Logdir not accessible/writable from this node.
3894             return 1
3895         fi
3896     done
3897     return 0
3898 }
3899
3900 init_logging() {
3901     if [[ -n $YAML_LOG ]]; then
3902         return
3903     fi
3904     export YAML_LOG=${LOGDIR}/results.yml
3905     mkdir -p $LOGDIR
3906     init_clients_lists
3907
3908     do_rpc_nodes $(comma_list $(nodes_list)) check_logdir $LOGDIR
3909     if check_write_access $LOGDIR; then
3910         touch $LOGDIR/shared
3911         echo "Logging to shared log directory: $LOGDIR"
3912     else
3913         echo "Logging to local directory: $LOGDIR"
3914     fi
3915
3916     yml_nodes_file $LOGDIR
3917     yml_results_file >> $YAML_LOG
3918 }
3919
3920 log_test() {
3921     yml_log_test $1 >> $YAML_LOG
3922 }
3923
3924 log_sub_test_begin() {
3925     yml_log_sub_test_begin $@ >> $YAML_LOG
3926 }
3927
3928 log_sub_test_end() {
3929     yml_log_sub_test_end $@ >> $YAML_LOG
3930 }
3931
3932 run_llverdev()
3933 {
3934         local dev=$1
3935         local devname=$(basename $1)
3936         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
3937         # loop devices aren't in /proc/partitions
3938         [ "x$size" == "x" ] && local size=$(ls -l $dev | awk '{print $5}')
3939
3940         size=$(($size / 1024 / 1024)) # Gb
3941
3942         local partial_arg=""
3943         # Run in partial (fast) mode if the size
3944         # of a partition > 10 GB
3945         [ $size -gt 10 ] && partial_arg="-p"
3946
3947         llverdev --force $partial_arg $dev
3948 }