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