Whamcloud - gitweb
b=19702 fix COUNT to work properly
[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     clients_up || 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     clients_up || echo "first df failed: $?"
1143     clients_up || error "post-failover df: $?"
1144 }
1145
1146 do_lmc() {
1147     echo There is no lmc.  This is mountconf, baby.
1148     exit 1
1149 }
1150
1151 h2gm () {
1152     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1153         ID=`$PDSH $1 $GMNALNID -l | cut -d\  -f2`
1154         echo $ID"@gm"
1155     fi
1156 }
1157
1158 h2name_or_ip() {
1159     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1160         echo $1"@$2"
1161     fi
1162 }
1163
1164 h2ptl() {
1165    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1166        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
1167        if [ -z "$ID" ]; then
1168            echo "Could not get a ptl id for $1..."
1169            exit 1
1170        fi
1171        echo $ID"@ptl"
1172    fi
1173 }
1174 declare -fx h2ptl
1175
1176 h2tcp() {
1177     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1178         echo $1"@tcp"
1179     fi
1180 }
1181 declare -fx h2tcp
1182
1183 h2elan() {
1184     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1185         if type __h2elan >/dev/null 2>&1; then
1186             ID=$(__h2elan $1)
1187         else
1188             ID=`echo $1 | sed 's/[^0-9]*//g'`
1189         fi
1190         echo $ID"@elan"
1191     fi
1192 }
1193 declare -fx h2elan
1194
1195 h2openib() {
1196     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1197         ID=`echo $1 | sed 's/[^0-9]*//g'`
1198         echo $ID"@openib"
1199     fi
1200 }
1201 declare -fx h2openib
1202
1203 h2o2ib() {
1204     h2name_or_ip "$1" "o2ib"
1205 }
1206 declare -fx h2o2ib
1207
1208 facet_host() {
1209     local facet=$1
1210
1211     [ "$facet" == client ] && echo -n $HOSTNAME && return
1212     varname=${facet}_HOST
1213     if [ -z "${!varname}" ]; then
1214         if [ "${facet:0:3}" == "ost" ]; then
1215             eval ${facet}_HOST=${ost_HOST}
1216         fi
1217     fi
1218     echo -n ${!varname}
1219 }
1220
1221 facet_active() {
1222     local facet=$1
1223     local activevar=${facet}active
1224
1225     if [ -f $TMP/${facet}active ] ; then
1226         source $TMP/${facet}active
1227     fi
1228
1229     active=${!activevar}
1230     if [ -z "$active" ] ; then
1231         echo -n ${facet}
1232     else
1233         echo -n ${active}
1234     fi
1235 }
1236
1237 facet_active_host() {
1238     local facet=$1
1239     local active=`facet_active $facet`
1240     if [ "$facet" == client ]; then
1241         echo $HOSTNAME
1242     else
1243         echo `facet_host $active`
1244     fi
1245 }
1246
1247 change_active() {
1248     local facet=$1
1249     local failover=${facet}failover
1250     host=`facet_host $failover`
1251     [ -z "$host" ] && return
1252     local curactive=`facet_active $facet`
1253     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
1254         eval export ${facet}active=$facet
1255     else
1256         eval export ${facet}active=$failover
1257     fi
1258     # save the active host for this facet
1259     local activevar=${facet}active
1260     echo "$activevar=${!activevar}" > $TMP/$activevar
1261 }
1262
1263 do_node() {
1264     local verbose=false
1265     # do not stripe off hostname if verbose, bug 19215
1266     if [ x$1 = x--verbose ]; then
1267         shift
1268         verbose=true
1269     fi
1270
1271     local HOST=$1
1272     shift
1273     local myPDSH=$PDSH
1274     if [ "$HOST" = "$HOSTNAME" ]; then
1275         myPDSH="no_dsh"
1276     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
1277         echo "cannot run remote command on $HOST with $myPDSH"
1278         return 128
1279     fi
1280     if $VERBOSE; then
1281         echo "CMD: $HOST $@" >&2
1282         $myPDSH $HOST $LCTL mark "$@" > /dev/null 2>&1 || :
1283     fi
1284
1285     if [ "$myPDSH" = "rsh" ]; then
1286 # we need this because rsh does not return exit code of an executed command
1287         local command_status="$TMP/cs"
1288         rsh $HOST ":> $command_status"
1289         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
1290                     cd $RPWD; sh -c \"$@\") ||
1291                     echo command failed >$command_status"
1292         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
1293         return 0
1294     fi
1295
1296     if $verbose ; then
1297         # print HOSTNAME for myPDSH="no_dsh"
1298         if [[ $myPDSH = no_dsh ]]; then
1299             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
1300         else
1301             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")"
1302         fi
1303     else
1304         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed "s/^${HOST}: //"
1305     fi
1306     return ${PIPESTATUS[0]}
1307 }
1308
1309 single_local_node () {
1310    [ "$1" = "$HOSTNAME" ]
1311 }
1312
1313 do_nodes() {
1314     local verbose=false
1315     # do not stripe off hostname if verbose, bug 19215
1316     if [ x$1 = x--verbose ]; then
1317         shift
1318         verbose=true
1319     fi
1320
1321     local rnodes=$1
1322     shift
1323
1324     if $(single_local_node $rnodes); then
1325         if $verbose; then
1326            do_node --verbose $rnodes $@
1327         else
1328            do_node $rnodes $@
1329         fi
1330         return $?
1331     fi
1332
1333     # This is part from do_node
1334     local myPDSH=$PDSH
1335
1336     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
1337         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
1338
1339     if $VERBOSE; then
1340         echo "CMD: $rnodes $@" >&2
1341         $myPDSH $rnodes $LCTL mark "$@" > /dev/null 2>&1 || :
1342     fi
1343
1344     if $verbose ; then
1345         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")"
1346     else
1347         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed -re "s/\w+:\s//g"
1348     fi
1349     return ${PIPESTATUS[0]}
1350 }
1351
1352 do_facet() {
1353     local facet=$1
1354     shift
1355     local HOST=`facet_active_host $facet`
1356     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
1357     do_node $HOST "$@"
1358 }
1359
1360 add() {
1361     local facet=$1
1362     shift
1363     # make sure its not already running
1364     stop ${facet} -f
1365     rm -f $TMP/${facet}active
1366     do_facet ${facet} $MKFS $*
1367 }
1368
1369 ostdevname() {
1370     num=$1
1371     DEVNAME=OSTDEV$num
1372     #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
1373     eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}}
1374     echo -n $DEVPTR
1375 }
1376
1377 ########
1378 ## MountConf setup
1379
1380 stopall() {
1381     # make sure we are using the primary server, so test-framework will
1382     # be able to clean up properly.
1383     activemds=`facet_active mds`
1384     if [ $activemds != "mds" ]; then
1385         fail mds
1386     fi
1387
1388     local clients=$CLIENTS
1389     [ -z $clients ] && clients=$(hostname)
1390
1391     zconf_umount_clients $clients $MOUNT "$*" || true
1392     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
1393
1394     [ "$CLIENTONLY" ] && return
1395     # The add fn does rm ${facet}active file, this would be enough
1396     # if we use do_facet <facet> only after the facet added, but
1397     # currently we use do_facet mds in local.sh
1398     stop mds -f
1399     rm -f ${TMP}/mdsactive
1400     for num in `seq $OSTCOUNT`; do
1401         stop ost$num -f
1402         rm -f $TMP/ost${num}active
1403     done
1404     if [[ $MDSDEV != $MGSDEV ]]; then
1405         stop mgs 
1406     fi
1407
1408     return 0
1409 }
1410
1411 cleanupall() {
1412     nfs_client_mode && return
1413
1414     stopall $*
1415     unload_modules
1416 }
1417
1418 formatall() {
1419     [ "$FSTYPE" ] && FSTYPE_OPT="--backfstype $FSTYPE"
1420
1421     stopall
1422     # We need ldiskfs here, may as well load them all
1423     load_modules
1424     [ "$CLIENTONLY" ] && return
1425     echo Formatting mgs, mds, osts
1426     if [[ $MDSDEV != $MGSDEV ]] || [[ $mds_HOST != $mgs_HOST ]]; then
1427         add mgs $mgs_MKFS_OPTS $FSTYPE_OPT --reformat $MGSDEV || exit 10
1428     fi
1429
1430     if $VERBOSE; then
1431         add mds $MDS_MKFS_OPTS $FSTYPE_OPT --reformat $MDSDEV || exit 10
1432     else
1433         add mds $MDS_MKFS_OPTS $FSTYPE_OPT --reformat $MDSDEV > /dev/null || exit 10
1434     fi
1435
1436     for num in `seq $OSTCOUNT`; do
1437         if $VERBOSE; then
1438             add ost$num $OST_MKFS_OPTS $FSTYPE_OPT --reformat `ostdevname $num` || exit 10
1439         else
1440             add ost$num $OST_MKFS_OPTS $FSTYPE_OPT --reformat `ostdevname $num` > /dev/null || exit 10
1441         fi
1442     done
1443 }
1444
1445 mount_client() {
1446     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
1447 }
1448
1449 remount_client()
1450 {
1451         zconf_umount `hostname` $1 || error "umount failed"
1452         zconf_mount `hostname` $1 || error "mount failed"
1453 }
1454
1455 writeconf_facet () {
1456     local facet=$1
1457     local dev=$2
1458
1459     do_facet $facet "$TUNEFS --writeconf $dev"
1460 }
1461
1462 writeconf_all () {
1463     writeconf_facet mds $MDSDEV
1464
1465     for num in `seq $OSTCOUNT`; do
1466         DEVNAME=`ostdevname $num`
1467         writeconf_facet ost$num $DEVNAME
1468     done
1469 }
1470
1471 setupall() {
1472     nfs_client_mode && return
1473
1474     sanity_mount_check ||
1475         error "environments are insane!"
1476
1477     load_modules
1478     if [ -z "$CLIENTONLY" ]; then
1479         echo Setup mgs, mdt, osts
1480
1481         echo $WRITECONF | grep -q "writeconf" && \
1482             writeconf_all
1483
1484         if [[ $mds_HOST != $mgs_HOST ]] || [[ $MDSDEV != $MGSDEV ]]; then
1485             start mgs $MGSDEV $mgs_MOUNT_OPTS
1486         fi
1487
1488         start mds $MDSDEV $MDS_MOUNT_OPTS
1489         # We started mds, now we should set failover variable properly.
1490         # Set mdsfailover_HOST if it is not set (the default failnode).
1491         if [ -z "$mdsfailover_HOST" ]; then
1492            mdsfailover_HOST=$(facet_host mds)
1493         fi
1494
1495         for num in `seq $OSTCOUNT`; do
1496             DEVNAME=`ostdevname $num`
1497             start ost$num $DEVNAME $OST_MOUNT_OPTS
1498
1499             # We started ost$num, now we should set ost${num}failover variable properly.
1500             # Set ost${num}failover_HOST if it is not set (the default failnode).
1501             varname=ost${num}failover_HOST
1502             if [ -z "${!varname}" ]; then
1503                 eval ost${num}failover_HOST=$(facet_host ost${num})
1504             fi
1505
1506         done
1507     fi
1508     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
1509     mount_client $MOUNT
1510     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
1511
1512     if [ "$MOUNT_2" ]; then
1513         mount_client $MOUNT2
1514         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
1515     fi
1516     sleep 5
1517     init_param_vars
1518 }
1519
1520 mounted_lustre_filesystems() {
1521         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
1522 }
1523
1524 init_facet_vars () {
1525     [ "$CLIENTONLY" ] && return 0
1526     local facet=$1
1527     shift
1528     local device=$1
1529
1530     shift
1531
1532     eval export ${facet}_dev=${device}
1533     eval export ${facet}_opt=\"$@\"
1534
1535     local dev=${facet}_dev
1536     local label=$(do_facet ${facet} "$E2LABEL ${!dev}")
1537     [ -z "$label" ] && echo no label for ${!dev} && exit 1
1538
1539     eval export ${facet}_svc=${label}
1540
1541     local varname=${facet}failover_HOST
1542     if [ -z "${!varname}" ]; then
1543        eval $varname=$(facet_host $facet)
1544     fi
1545
1546     # ${facet}failover_dev is set in cfg file
1547     varname=${facet}failover_dev
1548     if [ -n "${!varname}" ] ; then
1549         eval export ${facet}failover_dev=${!varname}
1550     else
1551         eval export ${facet}failover_dev=$device
1552     fi
1553 }
1554
1555 init_facets_vars () {
1556     remote_mds_nodsh ||
1557         init_facet_vars mds $MDSDEV $MDS_MOUNT_OPTS
1558
1559     remote_ost_nodsh && return
1560
1561     for num in `seq $OSTCOUNT`; do
1562         DEVNAME=`ostdevname $num`
1563         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
1564     done
1565 }
1566
1567 init_param_vars () {
1568     if ! remote_ost_nodsh && ! remote_mds_nodsh; then
1569         export MDSVER=$(do_facet mds "lctl get_param version" | cut -d. -f1,2)
1570         export OSTVER=$(do_facet ost1 "lctl get_param version" | cut -d. -f1,2)
1571         export CLIVER=$(lctl get_param version | cut -d. -f 1,2)
1572     fi
1573
1574     remote_mds_nodsh ||
1575         TIMEOUT=$(do_facet mds "lctl get_param -n timeout")
1576
1577     log "Using TIMEOUT=$TIMEOUT"
1578
1579     if [ "$ENABLE_QUOTA" ]; then
1580         setup_quota $MOUNT  || return 2
1581     fi
1582 }
1583
1584 nfs_client_mode () {
1585     if [ "$NFSCLIENT" ]; then
1586         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
1587         local clients=$CLIENTS
1588         [ -z $clients ] && clients=$(hostname)
1589
1590         # FIXME: remove hostname when 19215 fixed
1591         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
1592         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
1593         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
1594         return
1595     fi
1596     return 1
1597 }
1598
1599 check_config_client () {
1600     local mntpt=$1
1601
1602     local mounted=$(mount | grep " $mntpt ")
1603     if [ "$CLIENTONLY" ]; then
1604         # bug 18021
1605         # CLIENTONLY should not depend on *_HOST settings
1606         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
1607         # in theory someone could create a new,
1608         # client-only config file that assumed lustre was already
1609         # configured and didn't set the MGSNID. If MGSNID is not set,
1610         # then we should use the mgs nid currently being used 
1611         # as the default value. bug 18021
1612         [[ x$MGSNID = x ]] &&
1613             MGSNID=${mgc//MGC/}
1614
1615         if [[ x$mgc != xMGC$MGSNID ]]; then
1616             if [ "$mgs_HOST" ]; then
1617                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
1618                 [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
1619                     error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
1620             fi
1621         fi
1622         return 0
1623     fi
1624
1625     local myMGS_host=$mgs_HOST
1626     if [ "$NETTYPE" = "ptl" ]; then
1627         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//)
1628     fi
1629
1630     echo Checking config lustre mounted on $mntpt
1631     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
1632     mgshost=$(echo $mgshost | awk -F: '{print $1}')
1633
1634 #    if [ "$mgshost" != "$myMGS_host" ]; then
1635 #            error_exit "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
1636 #                   Please use correct config or set mds_HOST correctly!"
1637 #    fi
1638
1639 }
1640
1641 check_config_clients () {
1642     local clients=${CLIENTS:-$HOSTNAME}
1643     local mntpt=$1
1644
1645     nfs_client_mode && return
1646
1647     do_rpc_nodes $clients check_config_client $mntpt
1648
1649     sanity_mount_check ||
1650         error "environments are insane!"
1651 }
1652
1653 check_timeout () {
1654     local mdstimeout=$(do_facet mds "lctl get_param -n timeout")
1655     local cltimeout=$(lctl get_param -n timeout)
1656     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
1657         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
1658         return 1
1659     fi
1660 }
1661
1662 is_mounted () {
1663     local mntpt=$1
1664     local mounted=$(mounted_lustre_filesystems)
1665
1666     echo $mounted' ' | grep -w -q $mntpt' '
1667 }
1668
1669 check_and_setup_lustre() {
1670     nfs_client_mode && return
1671
1672     local MOUNTED=$(mounted_lustre_filesystems)
1673
1674     local do_check=true
1675     # 1.
1676     # both MOUNT and MOUNT2 are not mounted
1677     if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
1678         [ "$REFORMAT" ] && formatall
1679         # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
1680         setupall
1681         is_mounted $MOUNT || error "NAME=$NAME not mounted"
1682         export I_MOUNTED=yes
1683         do_check=false
1684     # 2.
1685     # MOUNT2 is mounted
1686     elif is_mounted $MOUNT2; then
1687             # 3.
1688             # MOUNT2 is mounted, while MOUNT_2 is not set
1689             if ! [ "$MOUNT_2" ]; then
1690                 cleanup_mount $MOUNT2
1691                 export I_UMOUNTED2=yes
1692
1693             # 4.
1694             # MOUNT2 is mounted, MOUNT_2 is set
1695             else
1696                 # FIXME: what to do if check_config failed?
1697                 # i.e. if:
1698                 # 1) remote client has mounted other Lustre fs ?
1699                 # 2) it has insane env ?
1700                 # let's try umount MOUNT2 on all clients and mount it again:
1701                 if ! check_config_clients $MOUNT2; then
1702                     cleanup_mount $MOUNT2
1703                     restore_mount $MOUNT2
1704                     export I_MOUNTED2=yes
1705                 fi
1706             fi 
1707
1708     # 5.
1709     # MOUNT is mounted MOUNT2 is not mounted
1710     elif [ "$MOUNT_2" ]; then
1711         restore_mount $MOUNT2
1712         export I_MOUNTED2=yes
1713     fi
1714
1715     if $do_check; then
1716         # FIXME: what to do if check_config failed?
1717         # i.e. if:
1718         # 1) remote client has mounted other Lustre fs?
1719         # 2) lustre is mounted on remote_clients atall ?
1720         check_config_clients $MOUNT
1721         init_facets_vars
1722         init_param_vars
1723
1724         do_nodes $(comma_list $(nodes_list)) "lctl set_param debug=\\\"$PTLDEBUG\\\";
1725             lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
1726             lctl set_param debug_mb=${DEBUG_SIZE};
1727             sync"
1728     fi
1729     if [ "$ONLY" == "setup" ]; then
1730         exit 0
1731     fi
1732 }
1733
1734 restore_mount () {
1735    local clients=${CLIENTS:-$HOSTNAME}
1736    local mntpt=$1
1737
1738    zconf_mount_clients $clients $mntpt
1739 }
1740
1741 cleanup_mount () {
1742     local clients=${CLIENTS:-$HOSTNAME}
1743     local mntpt=$1
1744
1745     zconf_umount_clients $clients $mntpt    
1746 }
1747
1748 cleanup_and_setup_lustre() {
1749     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
1750         lctl set_param debug=0 || true
1751         cleanupall
1752         if [ "$ONLY" == "cleanup" ]; then
1753             exit 0
1754         fi
1755     fi
1756     check_and_setup_lustre
1757 }
1758
1759 check_and_cleanup_lustre() {
1760     if is_mounted $MOUNT; then
1761         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
1762         [ "$ENABLE_QUOTA" ] && restore_quota_type || true
1763     fi
1764
1765     if [ "$I_UMOUNTED2" = "yes" ]; then
1766         restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
1767     fi
1768
1769     if [ "$I_MOUNTED2" = "yes" ]; then
1770         cleanup_mount $MOUNT2
1771     fi
1772
1773     if [ "$I_MOUNTED" = "yes" ]; then
1774         cleanupall -f || error "cleanup failed"
1775         unset I_MOUNTED
1776     fi
1777 }
1778
1779 #######
1780 # General functions
1781
1782 check_network() {
1783     local NETWORK=0
1784     local WAIT=0
1785     local MAX=$2
1786     while [ $NETWORK -eq 0 ]; do
1787         if ping -c 1 -w 3 $1 > /dev/null; then
1788             NETWORK=1
1789         else
1790             WAIT=$((WAIT + 5))
1791             echo "waiting for $1, $((MAX - WAIT)) secs left"
1792             sleep 5
1793         fi
1794         if [ $WAIT -gt $MAX ]; then
1795             echo "Network not available"
1796             exit 1
1797         fi
1798     done
1799 }
1800 check_port() {
1801     while( !($DSH2 $1 "netstat -tna | grep -q $2") ) ; do
1802         sleep 9
1803     done
1804 }
1805
1806 no_dsh() {
1807     shift
1808     eval $@
1809 }
1810
1811 comma_list() {
1812     # the sed converts spaces to commas, but leaves the last space
1813     # alone, so the line doesn't end with a comma.
1814     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
1815 }
1816
1817 # list, excluded are the comma separated lists
1818 exclude_items_from_list () {
1819     local list=$1
1820     local excluded=$2
1821     local item
1822
1823     list=${list//,/ }
1824     for item in ${excluded//,/ }; do
1825         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
1826     done
1827     echo $(comma_list $list)
1828 }
1829
1830 # list, expand  are the comma separated lists
1831 expand_list () {
1832     local list=${1//,/ }
1833     local expand=${2//,/ }
1834     local expanded=
1835
1836     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
1837     echo $(comma_list $expanded)
1838 }
1839
1840 testslist_filter () {
1841     local script=$LUSTRE/tests/${TESTSUITE}.sh
1842
1843     [ -f $script ] || return 0
1844
1845     local start_at=$START_AT
1846     local stop_at=$STOP_AT
1847
1848     local var=${TESTSUITE//-/_}_START_AT
1849     [ x"${!var}" != x ] && start_at=${!var}
1850     var=${TESTSUITE//-/_}_STOP_AT
1851     [ x"${!var}" != x ] && stop_at=${!var}
1852
1853     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
1854         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
1855             /^'${start_at}'$/ {flag = 0}
1856             {if (flag == 1) print $0}
1857             /^'${stop_at}'$/ { flag = 1 }'
1858 }
1859
1860 absolute_path() {
1861     (cd `dirname $1`; echo $PWD/`basename $1`)
1862 }
1863
1864 get_facets () {
1865     local name=$(echo $1 | tr "[:upper:]" "[:lower:]")
1866     local type=$(echo $1 | tr "[:lower:]" "[:upper:]")
1867
1868     local list=""
1869
1870     case $type in
1871         MDS )    list=mds;;
1872         OST )    for ((i=1; i<=$OSTCOUNT; i++)) do
1873                     list="$list ${name}$i"
1874                  done;;
1875           * )    error "Invalid facet type"
1876                  exit 1;;
1877     esac
1878     echo $(comma_list $list)
1879 }
1880
1881 ##################################
1882 # Adaptive Timeouts funcs
1883
1884 at_is_enabled() {
1885     # only check mds, we assume at_max is the same on all nodes
1886     local at_max=$(do_facet mds "lctl get_param -n at_max")
1887     if [ $at_max -eq 0 ]; then
1888         return 1
1889     else
1890         return 0
1891     fi
1892 }
1893
1894 at_max_get() {
1895     local facet=$1
1896
1897     # suppose that all ost-s has the same at_max set
1898     if [ $facet == "ost" ]; then
1899         do_facet ost1 "lctl get_param -n at_max"
1900     else
1901         do_facet $facet "lctl get_param -n at_max"
1902     fi
1903 }
1904
1905 at_max_set() {
1906     local at_max=$1
1907     shift
1908
1909     local facet
1910     for facet in $@; do
1911         if [ $facet == "ost" ]; then
1912             for i in `seq $OSTCOUNT`; do
1913                 do_facet ost$i "lctl set_param at_max=$at_max"
1914             done
1915         else
1916             do_facet $facet "lctl set_param at_max=$at_max"
1917         fi
1918     done
1919 }
1920
1921 ##################################
1922 # OBD_FAIL funcs
1923
1924 drop_request() {
1925 # OBD_FAIL_MDS_ALL_REQUEST_NET
1926     RC=0
1927     do_facet mds lctl set_param fail_loc=0x123
1928     do_facet client "$1" || RC=$?
1929     do_facet mds lctl set_param fail_loc=0
1930     return $RC
1931 }
1932
1933 drop_reply() {
1934 # OBD_FAIL_MDS_ALL_REPLY_NET
1935     RC=0
1936     do_facet mds lctl set_param fail_loc=0x122
1937     do_facet client "$@" || RC=$?
1938     do_facet mds lctl set_param fail_loc=0
1939     return $RC
1940 }
1941
1942 drop_reint_reply() {
1943 # OBD_FAIL_MDS_REINT_NET_REP
1944     RC=0
1945     do_facet mds lctl set_param fail_loc=0x119
1946     do_facet client "$@" || RC=$?
1947     do_facet mds lctl set_param fail_loc=0
1948     return $RC
1949 }
1950
1951 pause_bulk() {
1952 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
1953     RC=0
1954     do_facet ost1 lctl set_param fail_loc=0x214
1955     do_facet client "$1" || RC=$?
1956     do_facet client "sync"
1957     do_facet ost1 lctl set_param fail_loc=0
1958     return $RC
1959 }
1960
1961 drop_ldlm_cancel() {
1962 #define OBD_FAIL_LDLM_CANCEL             0x304
1963     RC=0
1964     do_facet client lctl set_param fail_loc=0x304
1965     do_facet client "$@" || RC=$?
1966     do_facet client lctl set_param fail_loc=0
1967     return $RC
1968 }
1969
1970 drop_bl_callback() {
1971 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
1972     RC=0
1973     do_facet client lctl set_param fail_loc=0x305
1974     do_facet client "$@" || RC=$?
1975     do_facet client lctl set_param fail_loc=0
1976     return $RC
1977 }
1978
1979 drop_ldlm_reply() {
1980 #define OBD_FAIL_LDLM_REPLY              0x30c
1981     RC=0
1982     do_facet mds lctl set_param fail_loc=0x30c
1983     do_facet client "$@" || RC=$?
1984     do_facet mds lctl set_param fail_loc=0
1985     return $RC
1986 }
1987
1988 clear_failloc() {
1989     facet=$1
1990     pause=$2
1991     sleep $pause
1992     echo "clearing fail_loc on $facet"
1993     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
1994 }
1995
1996 set_nodes_failloc () {
1997     do_nodes $(comma_list $1)  lctl set_param fail_loc=$2
1998 }
1999
2000 cancel_lru_locks() {
2001     $LCTL mark "cancel_lru_locks $1 start"
2002     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
2003         $LCTL set_param -n $d=clear
2004     done
2005     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
2006     $LCTL mark "cancel_lru_locks $1 stop"
2007 }
2008
2009 default_lru_size()
2010 {
2011         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
2012         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
2013         echo "$DEFAULT_LRU_SIZE"
2014 }
2015
2016 lru_resize_enable()
2017 {
2018     lctl set_param ldlm.namespaces.*$1*.lru_size=0
2019 }
2020
2021 lru_resize_disable()
2022 {
2023     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
2024 }
2025
2026 pgcache_empty() {
2027     local FILE
2028     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
2029         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
2030             echo there is still data in page cache $FILE ?
2031             lctl get_param -n $FILE
2032             return 1
2033         fi
2034     done
2035     return 0
2036 }
2037
2038 create_fake_exports () {
2039     local facet=$1
2040     local num=$2
2041 #obd_fail_val = num;
2042 #define OBD_FAIL_TGT_FAKE_EXP 0x708
2043     do_facet $facet "lctl set_param fail_val=$num"
2044     do_facet $facet "lctl set_param fail_loc=0x80000708"
2045     fail $facet
2046 }
2047
2048 debugsave() {
2049     DEBUGSAVE="$(lctl get_param -n debug)"
2050 }
2051
2052 debugrestore() {
2053     [ -n "$DEBUGSAVE" ] && lctl set_param debug="${DEBUGSAVE}"
2054     DEBUGSAVE=""
2055 }
2056
2057 ##################################
2058 # Test interface
2059 ##################################
2060
2061 error_noexit() {
2062     local TYPE=${TYPE:-"FAIL"}
2063     local ERRLOG
2064
2065     local dump=true
2066     # do not dump logs if $1=false
2067     if [ "x$1" = "xfalse" ]; then
2068         shift
2069         dump=false
2070     fi
2071
2072     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
2073
2074     if $dump; then
2075         ERRLOG=$TMP/lustre_${TESTSUITE}_${TESTNAME}.$(date +%s)
2076         echo "Dumping lctl log to $ERRLOG"
2077         # We need to dump the logs on all nodes
2078         do_nodes $(comma_list $(nodes_list)) $NODE $LCTL dk $ERRLOG
2079     fi
2080     debugrestore
2081     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
2082     TEST_FAILED=true
2083 }
2084
2085 error() {
2086     error_noexit "$@"
2087     if $FAIL_ON_ERROR;  then
2088         reset_fail_loc
2089         exit 1
2090     fi
2091 }
2092
2093 error_exit() {
2094     error_noexit "$@"
2095     exit 1
2096 }
2097
2098 # use only if we are ignoring failures for this test, bugno required.
2099 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
2100 # e.g. error_ignore 5494 "your message"
2101 error_ignore() {
2102     local TYPE="IGNORE (bz$1)"
2103     shift
2104     error_noexit "$@"
2105 }
2106
2107 skip_env () {
2108     $FAIL_ON_SKIP_ENV && error false $@ || skip $@
2109 }
2110
2111 skip () {
2112         log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
2113         [ "$TESTSUITELOG" ] && \
2114                 echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
2115 }
2116
2117 build_test_filter() {
2118     EXCEPT="$EXCEPT $(testslist_filter)"
2119
2120     [ "$ONLY" ] && log "only running test `echo $ONLY`"
2121     for O in $ONLY; do
2122         eval ONLY_${O}=true
2123     done
2124     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
2125         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
2126     [ "$EXCEPT_SLOW" ] && \
2127         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
2128     for E in $EXCEPT $ALWAYS_EXCEPT; do
2129         eval EXCEPT_${E}=true
2130     done
2131     for E in $EXCEPT_SLOW; do
2132         eval EXCEPT_SLOW_${E}=true
2133     done
2134     for G in $GRANT_CHECK_LIST; do
2135         eval GCHECK_ONLY_${G}=true
2136         done
2137 }
2138
2139 basetest() {
2140     if [[ $1 = [a-z]* ]]; then
2141         echo $1
2142     else
2143         echo ${1%%[a-z]*}
2144     fi
2145 }
2146
2147 # print a newline if the last test was skipped
2148 export LAST_SKIPPED=
2149 run_test() {
2150     assert_DIR
2151
2152     export base=`basetest $1`
2153     if [ ! -z "$ONLY" ]; then
2154         testname=ONLY_$1
2155         if [ ${!testname}x != x ]; then
2156             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2157             run_one $1 "$2"
2158             return $?
2159         fi
2160         testname=ONLY_$base
2161         if [ ${!testname}x != x ]; then
2162             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2163             run_one $1 "$2"
2164             return $?
2165         fi
2166         LAST_SKIPPED="y"
2167         echo -n "."
2168         return 0
2169     fi
2170     testname=EXCEPT_$1
2171     if [ ${!testname}x != x ]; then
2172         LAST_SKIPPED="y"
2173         TESTNAME=test_$1 skip "skipping excluded test $1"
2174         return 0
2175     fi
2176     testname=EXCEPT_$base
2177     if [ ${!testname}x != x ]; then
2178         LAST_SKIPPED="y"
2179         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
2180         return 0
2181     fi
2182     testname=EXCEPT_SLOW_$1
2183     if [ ${!testname}x != x ]; then
2184         LAST_SKIPPED="y"
2185         TESTNAME=test_$1 skip "skipping SLOW test $1"
2186         return 0
2187     fi
2188     testname=EXCEPT_SLOW_$base
2189     if [ ${!testname}x != x ]; then
2190         LAST_SKIPPED="y"
2191         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
2192         return 0
2193     fi
2194
2195     LAST_SKIPPED=
2196     run_one $1 "$2"
2197
2198     return $?
2199 }
2200
2201 EQUALS="======================================================================"
2202 equals_msg() {
2203     msg="$@"
2204
2205     local suffixlen=$((${#EQUALS} - ${#msg}))
2206     [ $suffixlen -lt 5 ] && suffixlen=5
2207     log `echo $(printf '===== %s %.*s\n' "$msg" $suffixlen $EQUALS)`
2208 }
2209
2210 log() {
2211     echo "$*"
2212     module_loaded lnet || load_modules
2213
2214     local MSG="$*"
2215     # Get rid of '
2216     MSG=${MSG//\'/\\\'}
2217     MSG=${MSG//\(/\\\(}
2218     MSG=${MSG//\)/\\\)}
2219     MSG=${MSG//\;/\\\;}
2220     MSG=${MSG//\|/\\\|}
2221     MSG=${MSG//\>/\\\>}
2222     MSG=${MSG//\</\\\<}
2223     MSG=${MSG//\//\\\/}
2224     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
2225 }
2226
2227 trace() {
2228         log "STARTING: $*"
2229         strace -o $TMP/$1.strace -ttt $*
2230         RC=$?
2231         log "FINISHED: $*: rc $RC"
2232         return 1
2233 }
2234
2235 pass() {
2236     $TEST_FAILED && echo -n "FAIL " || echo -n "PASS "
2237     echo $@
2238 }
2239
2240 check_mds() {
2241     FFREE=`lctl get_param -n mds.*.filesfree`
2242     FTOTAL=`lctl get_param -n mds.*.filestotal`
2243     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
2244 }
2245
2246 reset_fail_loc () {
2247     echo -n "Resetting fail_loc on all nodes..."
2248     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
2249     echo done.
2250 }
2251
2252 run_one() {
2253     testnum=$1
2254     message=$2
2255     tfile=f${testnum}
2256     export tdir=d0.${TESTSUITE}/d${base}
2257
2258     local SAVE_UMASK=`umask`
2259     umask 0022
2260
2261     local BEFORE=`date +%s`
2262     echo
2263     log "== test $testnum: $message == `date +%H:%M:%S` ($BEFORE)"
2264     #check_mds
2265     export TESTNAME=test_$testnum
2266     TEST_FAILED=false
2267     test_${testnum} || error "test_$testnum failed with $?"
2268     #check_mds
2269     cd $SAVE_PWD
2270     reset_fail_loc
2271     check_grant ${testnum} || error "check_grant $testnum failed with $?"
2272     check_catastrophe || error "LBUG/LASSERT detected"
2273     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
2274     pass "($((`date +%s` - $BEFORE))s)"
2275     TEST_FAILED=false
2276     unset TESTNAME
2277     unset tdir
2278     umask $SAVE_UMASK
2279 }
2280
2281 canonical_path() {
2282     (cd `dirname $1`; echo $PWD/`basename $1`)
2283 }
2284
2285 sync_clients() {
2286     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
2287     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
2288         cd $SAVE_PWD
2289 }
2290
2291 check_grant() {
2292     export base=`basetest $1`
2293     [ "$CHECK_GRANT" == "no" ] && return 0
2294
2295         testname=GCHECK_ONLY_${base}
2296     [ ${!testname}x == x ] && return 0
2297
2298     echo -n "checking grant......"
2299         cd $SAVE_PWD
2300         # write some data to sync client lost_grant
2301         rm -f $DIR1/${tfile}_check_grant_* 2>&1
2302         for i in `seq $OSTCOUNT`; do
2303                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
2304                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
2305                                               count=1 > /dev/null 2>&1
2306         done
2307     # sync all the data and make sure no pending data on server
2308     sync_clients
2309
2310     #get client grant and server grant
2311     client_grant=0
2312     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
2313         client_grant=$((client_grant + $d))
2314     done
2315     server_grant=0
2316     for d in `lctl get_param -n obdfilter.*.tot_granted`; do
2317         server_grant=$((server_grant + $d))
2318     done
2319
2320         # cleanup the check_grant file
2321         for i in `seq $OSTCOUNT`; do
2322                 rm $DIR1/${tfile}_check_grant_$i
2323         done
2324
2325         #check whether client grant == server grant
2326         if [ $client_grant != $server_grant ]; then
2327                 echo "failed: client:${client_grant} server: ${server_grant}"
2328                 return 1
2329         else
2330                 echo "pass"
2331         fi
2332 }
2333
2334 ########################
2335 # helper functions
2336
2337 osc_to_ost()
2338 {
2339     osc=$1
2340     ost=`echo $1 | awk -F_ '{print $3}'`
2341     if [ -z $ost ]; then
2342         ost=`echo $1 | sed 's/-osc.*//'`
2343     fi
2344     echo $ost
2345 }
2346
2347 remote_node () {
2348     local node=$1
2349     [ "$node" != "$(hostname)" ]
2350 }
2351
2352 remote_mds ()
2353 {
2354     remote_node $mds_HOST
2355 }
2356
2357 remote_mds_nodsh()
2358 {
2359     [ "$CLIENTONLY" ] && return 0 || true
2360     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
2361 }
2362
2363 remote_ost ()
2364 {
2365     local node
2366     for node in $(osts_nodes) ; do
2367         remote_node $node && return 0
2368     done
2369     return 1
2370 }
2371
2372 remote_ost_nodsh()
2373 {
2374     [ "$CLIENTONLY" ] && return 0 || true 
2375     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2376 }
2377
2378 remote_mgs_nodsh()
2379 {
2380     local MGS
2381     MGS=$(facet_host mgs)
2382     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2383 }
2384
2385 remote_servers () {
2386     remote_ost && remote_mds
2387 }
2388
2389 osts_nodes () {
2390     local OSTNODES=$(facet_host ost1)
2391     local NODES_sort
2392
2393     for num in `seq $OSTCOUNT`; do
2394         local myOST=$(facet_host ost$num)
2395         OSTNODES="$OSTNODES $myOST"
2396     done
2397     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
2398
2399     echo $NODES_sort
2400 }
2401
2402 nodes_list () {
2403     # FIXME. We need a list of clients
2404     local myNODES=$HOSTNAME
2405     local myNODES_sort
2406
2407     # CLIENTS (if specified) contains the local client
2408     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
2409
2410     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
2411         myNODES="$myNODES $(osts_nodes) $mds_HOST"
2412     fi
2413
2414     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
2415
2416     echo $myNODES_sort
2417 }
2418
2419 remote_nodes_list () {
2420     local rnodes=$(nodes_list)
2421     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2422     echo $rnodes
2423 }
2424
2425 init_clients_lists () {
2426     # Sanity check: exclude the local client from RCLIENTS
2427     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2428
2429     # Sanity check: exclude the dup entries
2430     rclients=$(for i in $rclients; do echo $i; done | sort -u)
2431
2432     local clients="$SINGLECLIENT $HOSTNAME $rclients"
2433
2434     # Sanity check: exclude the dup entries from CLIENTS
2435     # for those configs which has SINGLCLIENT set to local client
2436     clients=$(for i in $clients; do echo $i; done | sort -u)
2437
2438     CLIENTS=`comma_list $clients`
2439     local -a remoteclients=($rclients)
2440     for ((i=0; $i<${#remoteclients[@]}; i++)); do
2441             varname=CLIENT$((i + 2))
2442             eval $varname=${remoteclients[i]}
2443     done
2444
2445     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
2446 }
2447
2448 get_random_entry () {
2449     local rnodes=$1
2450
2451     rnodes=${rnodes//,/ }
2452
2453     local -a nodes=($rnodes)
2454     local num=${#nodes[@]}
2455     local i=$((RANDOM * num * 2 / 65536))
2456
2457     echo ${nodes[i]}
2458 }
2459
2460 client_only () {
2461     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
2462 }
2463
2464 is_patchless ()
2465 {
2466     lctl get_param version | grep -q patchless
2467 }
2468
2469 check_versions () {
2470     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
2471 }
2472
2473 get_node_count() {
2474     local nodes="$@"
2475     echo $nodes | wc -w || true
2476 }
2477
2478 mixed_ost_devs () {
2479     local nodes=$(osts_nodes)
2480     local osscount=$(get_node_count "$nodes")
2481     [ ! "$OSTCOUNT" = "$osscount" ]
2482 }
2483
2484 generate_machine_file() {
2485     local nodes=${1//,/ }
2486     local machinefile=$2
2487     rm -f $machinefile || error "can't rm $machinefile"
2488     for node in $nodes; do
2489         echo $node >>$machinefile
2490     done
2491 }
2492
2493 get_stripe () {
2494     local file=$1/stripe
2495     touch $file
2496     $LFS getstripe -v $file || error
2497     rm -f $file
2498 }
2499
2500 check_runas_id_ret() {
2501     local myRC=0
2502     local myRUNAS_UID=$1
2503     local myRUNAS_GID=$2
2504     shift 2
2505     local myRUNAS=$@
2506     if [ -z "$myRUNAS" ]; then
2507         error_exit "myRUNAS command must be specified for check_runas_id"
2508     fi
2509     mkdir $DIR/d0_runas_test
2510     chmod 0755 $DIR
2511     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
2512     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=1
2513     rm -rf $DIR/d0_runas_test
2514     return $myRC
2515 }
2516
2517 check_runas_id() {
2518     local myRUNAS_UID=$1
2519     local myRUNAS_GID=$2
2520     shift 2
2521     local myRUNAS=$@
2522     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
2523         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
2524         Please set RUNAS_ID to some UID which exists on MDS and client or
2525         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
2526 }
2527
2528 # Run multiop in the background, but wait for it to print
2529 # "PAUSING" to its stdout before returning from this function.
2530 multiop_bg_pause() {
2531     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
2532     FILE=$1
2533     ARGS=$2
2534
2535     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
2536     mkfifo $TMPPIPE
2537
2538     echo "$MULTIOP_PROG $FILE v$ARGS"
2539     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
2540
2541     echo "TMPPIPE=${TMPPIPE}"
2542     local multiop_output
2543
2544     read -t 60 multiop_output < $TMPPIPE
2545     if [ $? -ne 0 ]; then
2546         rm -f $TMPPIPE
2547         return 1
2548     fi
2549     rm -f $TMPPIPE
2550     if [ "$multiop_output" != "PAUSING" ]; then
2551         echo "Incorrect multiop output: $multiop_output"
2552         kill -9 $PID
2553         return 1
2554     fi
2555
2556     return 0
2557 }
2558
2559 do_and_time () {
2560     local cmd=$1
2561     local rc
2562
2563     SECONDS=0
2564     eval '$cmd'
2565     
2566     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
2567
2568     echo $SECONDS
2569     return $rc
2570 }
2571
2572 inodes_available () {
2573     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
2574     echo $IFree
2575 }
2576
2577 # reset llite stat counters
2578 clear_llite_stats(){
2579         lctl set_param -n llite.*.stats 0
2580 }
2581
2582 # sum llite stat items
2583 calc_llite_stats() {
2584         local res=$(lctl get_param -n llite.*.stats |
2585                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
2586         echo $res
2587 }
2588
2589 calc_sum () {
2590         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
2591 }
2592
2593 calc_osc_kbytes () {
2594         df $MOUNT > /dev/null
2595         $LCTL get_param -n osc.*[oO][sS][cC][-_]*.$1 | calc_sum
2596 }
2597
2598 # save_lustre_params(node, parameter_mask)
2599 # generate a stream of formatted strings (<node> <param name>=<param value>)
2600 save_lustre_params() {
2601         local s
2602         do_nodes --verbose $1 "lctl get_param $2 | while read s; do echo \\\$s; done"
2603 }
2604
2605 # restore lustre parameters from input stream, produces by save_lustre_params
2606 restore_lustre_params() {
2607         local node
2608         local name
2609         local val
2610         while IFS=" =" read node name val; do
2611                 do_node ${node//:/} "lctl set_param -n $name $val"
2612         done
2613 }
2614
2615 check_catastrophe() {
2616     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
2617     local C=$CATASTROPHE
2618     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
2619
2620     if [ $rnodes ]; then
2621         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
2622 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
2623 exit \\\$rc;"
2624     fi
2625 }
2626
2627 # $1 node
2628 # $2 file
2629 # $3 $RUNAS
2630 get_stripe_info() {
2631         local tmp_file
2632
2633         stripe_size=0
2634         stripe_count=0
2635         stripe_index=0
2636         tmp_file=$(mktemp)
2637
2638         do_facet $1 $3 lfs getstripe -v $2 > $tmp_file
2639
2640         stripe_size=`awk '$1 ~ /size/ {print $2}' $tmp_file`
2641         stripe_count=`awk '$1 ~ /count/ {print $2}' $tmp_file`
2642         stripe_index=`awk '$1 ~ /stripe_offset/ {print $2}' $tmp_file`
2643         rm -f $tmp_file
2644 }
2645
2646 mdsrate_cleanup () {
2647     mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
2648 }
2649
2650 delayed_recovery_enabled () {
2651     do_facet mds "lctl get_param -n mds.${mds_svc}.stale_export_age" > /dev/null 2>&1
2652 }
2653
2654 ################################################################################
2655 # The following functions are used to enable interop testing between
2656 # 1.8 and 2.0. The lprocfs layout changed from 1.8 to 2.0 as the followings:
2657 # mds -> mdt
2658 # {blocksize filesfree filestotal fstype kbytesavail kbytesfree kbytestotal mntdev} moved from mds to osd
2659 # mdt lov: fsname-mdtlov -> fsname-MDTXXXX-mdtlov
2660 # mdt osc: fsname-OSTXXXX-osc -> fsname-OSTXXXX-osc-MDTXXXX
2661 ################################################################################
2662
2663 get_lustre_version () {
2664     local node=${1:-"mds"}
2665     do_facet $node $LCTL get_param -n version |  awk '/^lustre:/ {print $2}'
2666 }
2667
2668 get_mds_version_major () {
2669     local version=$(get_lustre_version mds)
2670     echo $version | awk -F. '{print $1}'
2671 }
2672
2673 get_mds_version_minor () {
2674     local version=$(get_lustre_version mds)
2675     echo $version | awk -F. '{print $2}'
2676 }
2677
2678 get_mds_version_patch () {
2679     local version=$(get_lustre_version mds)
2680     echo $version | awk -F. '{print $3}'
2681 }
2682
2683 get_mds_version_fix () {
2684     local version=$(get_lustre_version mds)
2685     echo $version | awk -F. '{print $4}'
2686 }
2687
2688 get_mds_fsstat_proc_path() {
2689     local major=$(get_mds_version_major)
2690     local minor=$(get_mds_version_minor)
2691     if [ $major -le 1 -a $minor -le 8 ] ; then
2692         echo "mds"
2693     else
2694         echo "osd"
2695     fi
2696 }
2697
2698 get_mds_mntdev_proc_path() {
2699     local fsstat_dev=$(get_mds_fsstat_proc_path)
2700     echo "$fsstat_dev.*.mntdev"
2701 }
2702
2703 get_mdtlov_proc_path() {
2704     local fsname=$1
2705     local major=$(get_mds_version_major)
2706     local minor=$(get_mds_version_minor)
2707     if [ $major -le 1 -a $minor -le 8 ] ; then
2708         echo "${fsname}-mdtlov"
2709     else
2710         echo "${fsname}-MDT0000-mdtlov"
2711     fi
2712 }
2713
2714 get_mdtosc_proc_path() {
2715     local ost=$1
2716     local major=$(get_mds_version_major)
2717     local minor=$(get_mds_version_minor)
2718     if [ $major -le 1 -a $minor -le 8 ] ; then
2719         echo "${ost}-osc"
2720     else
2721         echo "${ost}-osc-MDT0000"
2722     fi
2723 }
2724
2725 get_mds_mdt_device_proc_path() {
2726     local major=$(get_mds_version_major)
2727     local minor=$(get_mds_version_minor)
2728     if [ $major -le 1 -a $minor -le 8 ] ; then
2729         echo "mds"
2730     else
2731         echo "mdt"
2732     fi
2733 }
2734
2735 ########################
2736
2737 convert_facet2label() { 
2738     local facet=$1
2739
2740     if [ x$facet = xost ]; then
2741        facet=ost1
2742     fi
2743
2744     local varsvc=${facet}_svc
2745
2746     if [ -n ${!varsvc} ]; then
2747         echo ${!varsvc}
2748     else  
2749         error "No lablel for $facet!"
2750     fi
2751 }
2752
2753 get_clientosc_proc_path() {
2754     local ost=$1
2755
2756     echo "{$1}-osc-*"
2757 }
2758
2759 get_osc_import_name() {
2760     local facet=$1
2761     local ost=$2
2762     local label=$(convert_facet2label $ost)
2763
2764     if [ "$facet" == "mds" ]; then
2765         get_mdtosc_proc_path $label
2766         return 0
2767     fi
2768
2769     get_clientosc_proc_path $label
2770     return 0
2771 }
2772
2773 wait_import_state () {
2774     local expected=$1
2775     local CONN_PROC=$2
2776     local CONN_STATE
2777     local i=0
2778
2779     CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
2780     while [ "${CONN_STATE}" != "${expected}" ]; do
2781         if [ "${expected}" == "DISCONN" ]; then
2782             # for disconn we can check after proc entry is removed
2783             [ "x${CONN_STATE}" == "x" ] && return 0
2784             #  with AT we can have connect request timeout ~ reconnect timeout
2785             # and test can't see real disconnect
2786             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
2787         fi
2788         # disconnect rpc should be wait not more obd_timeout
2789         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
2790             error "can't put import for $CONN_PROC into ${expected} state" && return 1
2791         sleep 1
2792         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
2793         i=$(($i + 1))
2794     done
2795
2796     log "$CONN_PROC now in ${CONN_STATE} state"
2797     return 0
2798 }
2799
2800 wait_osc_import_state() {
2801     local facet=$1
2802     local ost_facet=$2
2803     local expected=$3
2804     local ost=$(get_osc_import_name $facet $ost_facet)
2805     local CONN_PROC
2806     local CONN_STATE
2807     local i=0
2808
2809     CONN_PROC="osc.${ost}.ost_server_uuid"
2810     CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
2811     while [ "${CONN_STATE}" != "${expected}" ]; do
2812         if [ "${expected}" == "DISCONN" ]; then 
2813             # for disconn we can check after proc entry is removed
2814             [ "x${CONN_STATE}" == "x" ] && return 0
2815             #  with AT enabled, we can have connect request timeout near of 
2816             # reconnect timeout and test can't see real disconnect
2817             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
2818         fi
2819         # disconnect rpc should be wait not more obd_timeout
2820         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
2821             error "can't put import for ${ost}(${ost_facet}) into ${expected} state" && return 1
2822         sleep 1
2823         CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC | cut -f2)
2824         i=$(($i + 1))
2825     done
2826
2827     log "${ost_facet} now in ${CONN_STATE} state"
2828     return 0
2829 }
2830
2831 get_clientmdc_proc_path() {
2832     echo "${1}-mdc-*"
2833 }
2834
2835 do_rpc_nodes () {
2836     local list=$1
2837     shift
2838
2839     do_nodes --verbose $list "PATH=$LUSTRE/tests/:$PATH sh rpc.sh $@ " 
2840 }
2841
2842 wait_clients_import_state () {
2843     local list=$1
2844     local facet=$2
2845     local expected=$3
2846     shift
2847
2848     local label=$(convert_facet2label $facet)
2849     local proc_path
2850     case $facet in
2851         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
2852         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
2853         *) error "unknown facet!" ;;
2854     esac
2855
2856     if ! do_rpc_nodes $list wait_import_state $expected $proc_path; then
2857         error "import is not in ${expected} state"
2858         return 1
2859     fi
2860 }
2861
2862 destroy_pool_int() {
2863     local ost
2864     local OSTS=$(do_facet mds lctl pool_list $1 | awk '$1 !~ /^Pool:/ {print $1}')
2865     for ost in $OSTS; do
2866         do_facet mgs lctl pool_remove $1 $ost
2867     done
2868     do_facet mgs lctl pool_destroy $1
2869 }
2870
2871 # <fsname>.<poolname> or <poolname>
2872 destroy_pool() {
2873     local fsname=${1%%.*}
2874     local poolname=${1##$fsname.}
2875
2876     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
2877
2878     local RC
2879
2880     pool_list $fsname.$poolname || return $?
2881
2882     destroy_pool_int $fsname.$poolname
2883     RC=$?
2884     [[ $RC -ne 0 ]] && return $RC
2885
2886     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
2887       2>/dev/null || echo foo" "foo" || RC=1
2888
2889     if [[ $RC -eq 0 ]]; then
2890         remove_pool_from_list $fsname.$poolname
2891     else
2892         error "destroy pool failed $1"
2893     fi
2894     return $RC
2895 }
2896
2897 destroy_pools () {
2898     local fsname=${1:-$FSNAME}
2899     local poolname
2900     local listvar=${fsname}_CREATED_POOLS
2901
2902     pool_list $fsname
2903
2904     [ x${!listvar} = x ] && return 0
2905
2906     echo destroy the created pools: ${!listvar}
2907     for poolname in ${!listvar//,/ }; do
2908         destroy_pool $fsname.$poolname
2909     done
2910 }
2911
2912 cleanup_pools () {
2913     local fsname=${1:-$FSNAME}
2914     trap 0
2915     destroy_pools $fsname
2916 }
2917
2918 gather_logs () {
2919     local list=$1
2920
2921     local ts=$(date +%s)
2922
2923     # bug 20237, comment 11
2924     # It would also be useful to provide the option
2925     # of writing the file to an NFS directory so it doesn't need to be copied.
2926     local tmp=$TMP
2927     local docp=true
2928     [ -d "$SHARED_DIR_LOGS" ] && tmp=$SHARED_DIR_LOGS && docp=false
2929
2930     # dump lustre logs, dmesg
2931     do_nodes $list "log=$tmp/\\\$(hostname)-debug-$ts.log ;
2932 lctl dk \\\$log >/dev/null;
2933 log=$tmp/\\\$(hostname)-dmesg-$ts.log;
2934 dmesg > \\\$log; "
2935
2936     # FIXME: does it make sense to collect the logs for $ts only, but all
2937     # TESTSUITE logs?
2938     # rsync $TMP/*${TESTSUITE}* to gather the logs dumped by error fn
2939     local logs=$TMP/'*'${TESTSUITE}'*'
2940     if $docp; then
2941         logs=$logs' '$tmp/'*'$ts'*'
2942     fi
2943     for node in ${list//,/ }; do
2944         rsync -az $node:"$logs" $TMP
2945     done
2946
2947     local archive=$TMP/${TESTSUITE}-$ts.tar.bz2
2948     tar -jcf $archive $tmp/*$ts* $TMP/*${TESTSUITE}*
2949
2950     echo $archive
2951 }
2952
2953 cleanup_logs () {
2954     local list=${1:-$(comma_list $(nodes_list))}
2955
2956     [ -n ${TESTSUITE} ] && do_nodes $list "rm -f $TMP/*${TESTSUITE}*" || true
2957 }
2958
2959 do_ls () {
2960     local mntpt_root=$1
2961     local num_mntpts=$2
2962     local dir=$3
2963     local i
2964     local cmd
2965     local pids
2966     local rc=0
2967
2968     for i in $(seq 0 $num_mntpts); do
2969         cmd="ls -laf ${mntpt_root}$i/$dir"
2970         echo + $cmd;
2971         $cmd > /dev/null &
2972         pids="$pids $!"
2973     done
2974     echo pids=$pids
2975     for pid in $pids; do
2976         wait $pid || rc=$?
2977     done
2978
2979     return $rc
2980 }
2981