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