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