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