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