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