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