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