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