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