Whamcloud - gitweb
*** empty log message ***
[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 clients=$1
704     local mnt=$2
705     local OPTIONS=${3:-$MOUNTOPT}
706
707     # Only supply -o to mount if we have options
708     if [ "$OPTIONS" ]; then
709         OPTIONS="-o $OPTIONS"
710     fi
711     local device=$MGSNID:/$FSNAME
712     if [ -z "$mnt" -o -z "$FSNAME" ]; then
713         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
714         exit 1
715     fi
716
717     echo "Starting client $clients: $OPTIONS $device $mnt"
718
719     do_nodes $clients "
720 running=\\\$(mount | grep -c $mnt' ');
721 rc=0;
722 if [ \\\$running -eq 0 ] ; then
723     mkdir -p $mnt;
724     mount -t lustre $OPTIONS $device $mnt;
725     rc=\\\$?;
726 fi;
727 exit \\\$rc" || return ${PIPESTATUS[0]}
728
729     echo "Started clients $clients: "
730     do_nodes $clients "mount | grep -w $mnt"
731
732     do_nodes $clients "lctl set_param debug=\\\"$PTLDEBUG\\\";
733         lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
734         lctl set_param debug_mb=${DEBUG_SIZE};"
735
736     return 0
737 }
738
739 zconf_umount_clients() {
740     local clients=$1
741     local mnt=$2
742     local force
743
744     [ "$3" ] && force=-f
745
746     echo "Stopping clients: $clients $mnt (opts:$force)"
747     do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
748 if [ \\\$running -ne 0 ] ; then
749 echo Stopping client \\\$(hostname) $mnt opts:$force;
750 lsof -t $mnt || need_kill=no;
751 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
752     pids=\\\$(lsof -t $mnt | sort -u);
753     if [ -n \\\"\\\$pids\\\" ]; then
754              kill -9 \\\$pids;
755     fi
756 fi;
757 busy=\\\$(umount $force $mnt 2>&1 | grep -c "busy");
758 if [ \\\$busy -ne 0 ] ; then
759     echo "$mnt is still busy, wait one second" && sleep 1;
760     umount $force $mnt;
761 fi
762 fi"
763 }
764
765 shudown_node_hard () {
766     local host=$1
767     local attempts=3
768
769     for i in $(seq $attempts) ; do
770         $POWER_DOWN $host
771         sleep 1
772         ping -w 3 -c 1 $host > /dev/null 2>&1 || return 0
773         echo "waiting for $host to fail attempts=$attempts"
774         [ $i -lt $attempts ] || \
775             { echo "$host still pingable after power down! attempts=$attempts" && return 1; } 
776     done
777 }
778
779 shutdown_client() {
780     local client=$1
781     local mnt=${2:-$MOUNT}
782     local attempts=3
783
784     if [ "$FAILURE_MODE" = HARD ]; then
785         shudown_node_hard $client 
786     else
787        zconf_umount_clients $client $mnt -f
788     fi
789 }
790
791 shutdown_facet() {
792     local facet=$1
793     if [ "$FAILURE_MODE" = HARD ]; then
794         shudown_node_hard $(facet_active_host $facet)
795     elif [ "$FAILURE_MODE" = SOFT ]; then
796         stop $facet
797     fi
798 }
799
800 reboot_facet() {
801     facet=$1
802     if [ "$FAILURE_MODE" = HARD ]; then
803         $POWER_UP `facet_active_host $facet`
804     else
805         sleep 10
806     fi
807 }
808
809 boot_node() {
810     local node=$1
811     if [ "$FAILURE_MODE" = HARD ]; then
812        $POWER_UP $node
813        wait_for_host $node
814     fi
815 }
816
817 # recovery-scale functions
818 check_progs_installed () {
819     local clients=$1
820     shift
821     local progs=$@
822
823     do_nodes $clients "PATH=:$PATH; status=true;
824 for prog in $progs; do
825     if ! [ \\\"\\\$(which \\\$prog)\\\"  -o  \\\"\\\${!prog}\\\" ]; then
826        echo \\\$prog missing on \\\$(hostname);
827        status=false;
828     fi
829 done;
830 eval \\\$status"
831 }
832
833 client_var_name() {
834     echo __$(echo $1 | tr '-' 'X')
835 }
836
837 start_client_load() {
838     local client=$1
839     local load=$2
840     local var=$(client_var_name $client)_load
841     eval export ${var}=$load
842
843     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
844                               BREAK_ON_ERROR=$BREAK_ON_ERROR \
845                               END_RUN_FILE=$END_RUN_FILE \
846                               LOAD_PID_FILE=$LOAD_PID_FILE \
847                               TESTSUITELOG=$TESTSUITELOG \
848                               run_${load}.sh" &
849     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $!"
850     log "Started client load: ${load} on $client"
851
852     return 0
853 }
854
855 start_client_loads () {
856     local -a clients=(${1//,/ })
857     local numloads=${#CLIENT_LOADS[@]}
858     local testnum
859
860     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
861         testnum=$((nodenum % numloads))
862         start_client_load ${clients[nodenum]} ${CLIENT_LOADS[testnum]}
863     done
864 }
865
866 # only for remote client 
867 check_client_load () {
868     local client=$1
869     local var=$(client_var_name $client)_load
870     local TESTLOAD=run_${!var}.sh
871
872     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
873     
874     # bug 18914: try to connect several times not only when
875     # check ps, but  while check_catastrophe also
876     local tries=3
877     local RC=254
878     while [ $RC = 254 -a $tries -gt 0 ]; do
879         let tries=$tries-1
880         # assume success
881         RC=0
882         if ! check_catastrophe $client; then
883             RC=${PIPESTATUS[0]}
884             if [ $RC -eq 254 ]; then
885                 # FIXME: not sure how long we shuold sleep here
886                 sleep 10
887                 continue
888             fi
889             echo "check catastrophe failed: RC=$RC "
890             return $RC
891         fi
892     done
893     # We can continue try to connect if RC=254
894     # Just print the warning about this
895     if [ $RC = 254 ]; then
896         echo "got a return status of $RC from do_node while checking catastrophe on $client"
897     fi
898
899     # see if the load is still on the client
900     tries=3
901     RC=254
902     while [ $RC = 254 -a $tries -gt 0 ]; do
903         let tries=$tries-1
904         # assume success
905         RC=0
906         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
907             RC=${PIPESTATUS[0]}
908             sleep 30
909         fi
910     done
911     if [ $RC = 254 ]; then
912         echo "got a return status of $RC from do_node while checking (catastrophe and 'ps') the client load on $client"
913         # see if we can diagnose a bit why this is
914     fi
915
916     return $RC
917 }
918 check_client_loads () {
919    local clients=${1//,/ }
920    local client=
921    local rc=0
922
923    for client in $clients; do
924       check_client_load $client
925       rc=${PIPESTATUS[0]}
926       if [ "$rc" != 0 ]; then
927         log "Client load failed on node $client, rc=$rc"
928         return $rc
929       fi
930    done
931 }
932
933 restart_client_loads () {
934     local clients=${1//,/ }
935     local expectedfail=${2:-""}
936     local client=
937     local rc=0
938
939     for client in $clients; do
940         check_client_load $client
941         rc=${PIPESTATUS[0]}
942         if [ "$rc" != 0 -a "$expectedfail" ]; then
943             local var=$(client_var_name $client)_load
944             start_client_load $client ${!var}
945             echo "Restarted client load ${!var}: on $client. Checking ..."
946             check_client_load $client
947             rc=${PIPESTATUS[0]}
948             if [ "$rc" != 0 ]; then
949                 log "Client load failed to restart on node $client, rc=$rc"
950                 # failure one client load means test fail
951                 # we do not need to check other 
952                 return $rc
953             fi
954         else
955             return $rc
956         fi
957     done
958 }
959 # End recovery-scale functions
960
961 # verify that lustre actually cleaned up properly
962 cleanup_check() {
963     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
964         error "LBUG/LASSERT detected"
965     BUSY=`dmesg | grep -i destruct || true`
966     if [ "$BUSY" ]; then
967         echo "$BUSY" 1>&2
968         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
969         exit 205
970     fi
971
972     check_mem_leak || exit 204
973
974     [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl && \
975         echo "$0: lustre didn't clean up..." 1>&2 && return 202 || true
976
977     if module_loaded lnet || module_loaded libcfs; then
978         echo "$0: modules still loaded..." 1>&2
979         /sbin/lsmod 1>&2
980         return 203
981     fi
982     return 0
983 }
984
985 wait_update () {
986     local node=$1
987     local TEST=$2
988     local FINAL=$3
989     local MAX=${4:-90}
990
991         local RESULT
992         local WAIT=0
993         local sleep=5
994         while [ true ]; do
995             RESULT=$(do_node $node "$TEST")
996             if [ "$RESULT" == "$FINAL" ]; then
997                 echo "Updated after $WAIT sec: wanted '$FINAL' got '$RESULT'"
998                 return 0
999             fi
1000             [ $WAIT -ge $MAX ] && break
1001             echo "Waiting $((MAX - WAIT)) secs for update"
1002             WAIT=$((WAIT + sleep))
1003             sleep $sleep
1004         done
1005         echo "Update not seen after $MAX sec: wanted '$FINAL' got '$RESULT'"
1006         return 3
1007 }
1008
1009 wait_update_facet () {
1010     local facet=$1
1011     wait_update  $(facet_active_host $facet) "$@"
1012 }
1013
1014 wait_delete_completed () {
1015     local TOTALPREV=`lctl get_param -n osc.*.kbytesavail | \
1016                      awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1017
1018     local WAIT=0
1019     local MAX_WAIT=20
1020     while [ "$WAIT" -ne "$MAX_WAIT" ]; do
1021         sleep 1
1022         TOTAL=`lctl get_param -n osc.*.kbytesavail | \
1023                awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1024         [ "$TOTAL" -eq "$TOTALPREV" ] && return 0
1025         echo "Waiting delete completed ... prev: $TOTALPREV current: $TOTAL "
1026         TOTALPREV=$TOTAL
1027         WAIT=$(( WAIT + 1))
1028     done
1029     echo "Delete is not completed in $MAX_WAIT sec"
1030     return 1
1031 }
1032
1033 wait_for_host() {
1034     local host=$1
1035     check_network "$host" 900
1036     while ! do_node $host hostname  > /dev/null; do sleep 5; done
1037 }
1038
1039 wait_for() {
1040     local facet=$1
1041     local host=`facet_active_host $facet`
1042     wait_for_host $host
1043 }
1044
1045 wait_recovery_complete () {
1046     local facet=$1
1047
1048     # Use default policy if $2 is not passed by caller.
1049     #define OBD_RECOVERY_TIMEOUT (obd_timeout * 5 / 2)
1050     # as we are in process of changing obd_timeout in different ways
1051     # let's set MAX longer than that
1052     local MAX=${2:-$(( TIMEOUT * 4 ))}
1053
1054     local var_svc=${facet}_svc
1055     local procfile="*.${!var_svc}.recovery_status"
1056     local WAIT=0
1057     local STATUS=
1058
1059     while [ $WAIT -lt $MAX ]; do
1060         STATUS=$(do_facet $facet lctl get_param -n $procfile | grep status)
1061         [[ $STATUS = "status: COMPLETE" ]] && return 0
1062         sleep 5
1063         WAIT=$((WAIT + 5))
1064         echo "Waiting $((MAX - WAIT)) secs for $facet recovery done. $STATUS"
1065     done
1066     echo "$facet recovery not done in $MAX sec. $STATUS"
1067     return 1
1068 }
1069
1070 wait_mds_ost_sync () {
1071     # just because recovery is done doesn't mean we've finished
1072     # orphan cleanup. Wait for llogs to get synchronized.
1073     echo "Waiting for orphan cleanup..."
1074     # MAX value includes time needed for MDS-OST reconnection
1075     local MAX=$(( TIMEOUT * 2 ))
1076     local WAIT=0
1077     while [ $WAIT -lt $MAX ]; do
1078         local -a sync=($(do_nodes $(comma_list $(osts_nodes)) \
1079             "$LCTL get_param -n obdfilter.*.mds_sync"))
1080         local con=1
1081         for ((i=0; i<${#sync[@]}; i++)); do
1082             [ ${sync[$i]} -eq 0 ] && continue
1083             # there is a not finished MDS-OST synchronization
1084             con=0
1085             break;
1086         done
1087         sleep 2 # increase waiting time and cover statfs cache
1088         [ ${con} -eq 1 ] && return 0
1089         echo "Waiting $WAIT secs for $facet mds-ost sync done."
1090         WAIT=$((WAIT + 2))
1091     done
1092     echo "$facet recovery not done in $MAX sec. $STATUS"
1093     return 1
1094 }
1095
1096 wait_destroy_complete () {
1097     echo "Waiting for destroy to be done..."
1098     # MAX value shouldn't be big as this mean server responsiveness
1099     # never increase this just to make test pass but investigate
1100     # why it takes so long time
1101     local MAX=5
1102     local WAIT=0
1103     while [ $WAIT -lt $MAX ]; do
1104         local -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))
1105         local con=1
1106         for ((i=0; i<${#RPCs[@]}; i++)); do
1107             [ ${RPCs[$i]} -eq 0 ] && continue
1108             # there are still some destroy RPCs in flight
1109             con=0
1110             break;
1111         done
1112         sleep 1
1113         [ ${con} -eq 1 ] && return 0 # done waiting
1114         echo "Waiting $WAIT secs for destroys to be done."
1115         WAIT=$((WAIT + 1))
1116     done
1117     echo "Destroys weren't done in $MAX sec."
1118     return 1
1119 }
1120
1121 wait_exit_ST () {
1122     local facet=$1
1123
1124     local WAIT=0
1125     local INTERVAL=1
1126     local running
1127     # conf-sanity 31 takes a long time cleanup
1128     while [ $WAIT -lt 300 ]; do
1129         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
1130         [ -z "${running}" ] && return 0
1131         echo "waited $WAIT for${running}"
1132         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
1133         sleep $INTERVAL
1134         WAIT=$((WAIT + INTERVAL))
1135     done
1136     echo "service didn't stop after $WAIT seconds.  Still running:"
1137     echo ${running}
1138     return 1
1139 }
1140
1141 wait_remote_prog () {
1142    local prog=$1
1143    local WAIT=0
1144    local INTERVAL=5
1145    local rc=0
1146
1147    [ "$PDSH" = "no_dsh" ] && return 0
1148
1149    while [ $WAIT -lt $2 ]; do
1150         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
1151         [ -z "${running}" ] && return 0 || true
1152         echo "waited $WAIT for: "
1153         echo "$running"
1154         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
1155         sleep $INTERVAL
1156         WAIT=$((WAIT + INTERVAL))
1157     done
1158     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
1159     [ -z "$pids" ] && return 0
1160     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
1161     # FIXME: not portable
1162     for pid in $pids; do
1163         cat /proc/${pid}/status || true
1164         cat /proc/${pid}/wchan || true
1165         echo "Killing $pid"
1166         kill -9 $pid || true
1167         sleep 1
1168         ps -P $pid && rc=1
1169     done
1170
1171     return $rc
1172 }
1173
1174 clients_up() {
1175     # not every config has many clients
1176     sleep 1
1177     if [ ! -z "$CLIENTS" ]; then
1178         $PDSH $CLIENTS "stat -f $MOUNT" > /dev/null
1179     else
1180         stat -f $MOUNT > /dev/null
1181     fi
1182 }
1183
1184 client_up() {
1185     local client=$1
1186     # usually checked on particular client or locally
1187     sleep 1
1188     if [ ! -z "$client" ]; then
1189         $PDSH $client "stat -f $MOUNT" > /dev/null
1190     else
1191         stat -f $MOUNT > /dev/null
1192     fi
1193 }
1194
1195 client_evicted() {
1196     ! client_up $1
1197 }
1198
1199 client_reconnect() {
1200     uname -n >> $MOUNT/recon
1201     if [ -z "$CLIENTS" ]; then
1202         df $MOUNT; uname -n >> $MOUNT/recon
1203     else
1204         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
1205     fi
1206     echo Connected clients:
1207     cat $MOUNT/recon
1208     ls -l $MOUNT/recon > /dev/null
1209     rm $MOUNT/recon
1210 }
1211
1212 facet_failover() {
1213     local facet=$1
1214     local sleep_time=$2
1215     echo "Failing $facet on node `facet_active_host $facet`"
1216     shutdown_facet $facet
1217     [ -n "$sleep_time" ] && sleep $sleep_time
1218     reboot_facet $facet
1219     change_active $facet
1220     local TO=`facet_active_host $facet`
1221     echo "Failover $facet to $TO"
1222     wait_for $facet
1223     mount_facet $facet || error "Restart of $facet failed"
1224 }
1225
1226 obd_name() {
1227     local facet=$1
1228 }
1229
1230 replay_barrier() {
1231     local facet=$1
1232     do_facet $facet sync
1233     df $MOUNT
1234     local svc=${facet}_svc
1235     do_facet $facet $LCTL --device %${!svc} notransno
1236     do_facet $facet $LCTL --device %${!svc} readonly
1237     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1238     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1239 }
1240
1241 replay_barrier_nodf() {
1242     local facet=$1    echo running=${running}
1243     do_facet $facet sync
1244     local svc=${facet}_svc
1245     echo Replay barrier on ${!svc}
1246     do_facet $facet $LCTL --device %${!svc} notransno
1247     do_facet $facet $LCTL --device %${!svc} readonly
1248     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1249     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1250 }
1251
1252 replay_barrier_nosync() {
1253     local facet=$1    echo running=${running}
1254     local svc=${facet}_svc
1255     echo Replay barrier on ${!svc}
1256     do_facet $facet $LCTL --device %${!svc} notransno
1257     do_facet $facet $LCTL --device %${!svc} readonly
1258     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1259     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1260 }
1261
1262 mds_evict_client() {
1263     UUID=`lctl get_param -n mdc.${mds1_svc}-mdc-*.uuid`
1264     do_facet mds1 "lctl set_param -n mdt.${mds1_svc}.evict_client $UUID"
1265 }
1266
1267 ost_evict_client() {
1268     UUID=`lctl get_param -n devices| grep ${ost1_svc}-osc- | egrep -v 'MDT' | awk '{print $5}'`
1269     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
1270 }
1271
1272 fail() {
1273     facet_failover $* || error "failover: $?"
1274     clients_up || error "post-failover df: $?"
1275 }
1276
1277 fail_nodf() {
1278         local facet=$1
1279         facet_failover $facet
1280 }
1281
1282 fail_abort() {
1283     local facet=$1
1284     stop $facet
1285     change_active $facet
1286     mount_facet $facet -o abort_recovery
1287     clients_up || echo "first df failed: $?"
1288     clients_up || error "post-failover df: $?"
1289 }
1290
1291 do_lmc() {
1292     echo There is no lmc.  This is mountconf, baby.
1293     exit 1
1294 }
1295
1296 h2gm () {
1297     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1298         ID=`$PDSH $1 $GMNALNID -l | cut -d\  -f2`
1299         echo $ID"@gm"
1300     fi
1301 }
1302
1303 h2name_or_ip() {
1304     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1305         echo $1"@$2"
1306     fi
1307 }
1308
1309 h2ptl() {
1310    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1311        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
1312        if [ -z "$ID" ]; then
1313            echo "Could not get a ptl id for $1..."
1314            exit 1
1315        fi
1316        echo $ID"@ptl"
1317    fi
1318 }
1319 declare -fx h2ptl
1320
1321 h2tcp() {
1322     h2name_or_ip "$1" "tcp"
1323 }
1324 declare -fx h2tcp
1325
1326 h2elan() {
1327     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1328         if type __h2elan >/dev/null 2>&1; then
1329             ID=$(__h2elan $1)
1330         else
1331             ID=`echo $1 | sed 's/[^0-9]*//g'`
1332         fi
1333         echo $ID"@elan"
1334     fi
1335 }
1336 declare -fx h2elan
1337
1338 h2openib() {
1339     h2name_or_ip "$1" "openib"
1340 }
1341 declare -fx h2openib
1342
1343 h2o2ib() {
1344     h2name_or_ip "$1" "o2ib"
1345 }
1346 declare -fx h2o2ib
1347
1348 facet_host() {
1349     local facet=$1
1350
1351     [ "$facet" == client ] && echo -n $HOSTNAME && return
1352     varname=${facet}_HOST
1353     if [ -z "${!varname}" ]; then
1354         if [ "${facet:0:3}" == "ost" ]; then
1355             eval ${facet}_HOST=${ost_HOST}
1356         fi
1357     fi
1358     echo -n ${!varname}
1359 }
1360
1361 facet_active() {
1362     local facet=$1
1363     local activevar=${facet}active
1364
1365     if [ -f $TMP/${facet}active ] ; then
1366         source $TMP/${facet}active
1367     fi
1368
1369     active=${!activevar}
1370     if [ -z "$active" ] ; then
1371         echo -n ${facet}
1372     else
1373         echo -n ${active}
1374     fi
1375 }
1376
1377 facet_active_host() {
1378     local facet=$1
1379     local active=`facet_active $facet`
1380     if [ "$facet" == client ]; then
1381         echo $HOSTNAME
1382     else
1383         echo `facet_host $active`
1384     fi
1385 }
1386
1387 change_active() {
1388     local facet=$1
1389     local failover=${facet}failover
1390     host=`facet_host $failover`
1391     [ -z "$host" ] && return
1392     local curactive=`facet_active $facet`
1393     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
1394         eval export ${facet}active=$facet
1395     else
1396         eval export ${facet}active=$failover
1397     fi
1398     # save the active host for this facet
1399     local activevar=${facet}active
1400     echo "$activevar=${!activevar}" > $TMP/$activevar
1401 }
1402
1403 do_node() {
1404     local verbose=false
1405     # do not stripe off hostname if verbose, bug 19215
1406     if [ x$1 = x--verbose ]; then
1407         shift
1408         verbose=true
1409     fi
1410
1411     local HOST=$1
1412     shift
1413     local myPDSH=$PDSH
1414     if [ "$HOST" = "$HOSTNAME" ]; then
1415         myPDSH="no_dsh"
1416     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
1417         echo "cannot run remote command on $HOST with $myPDSH"
1418         return 128
1419     fi
1420     if $VERBOSE; then
1421         echo "CMD: $HOST $@" >&2
1422         $myPDSH $HOST $LCTL mark "$@" > /dev/null 2>&1 || :
1423     fi
1424
1425     if [ "$myPDSH" = "rsh" ]; then
1426 # we need this because rsh does not return exit code of an executed command
1427         local command_status="$TMP/cs"
1428         rsh $HOST ":> $command_status"
1429         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
1430                     cd $RPWD; sh -c \"$@\") ||
1431                     echo command failed >$command_status"
1432         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
1433         return 0
1434     fi
1435
1436     if $verbose ; then
1437         # print HOSTNAME for myPDSH="no_dsh"
1438         if [[ $myPDSH = no_dsh ]]; then
1439             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
1440         else
1441             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")"
1442         fi
1443     else
1444         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed "s/^${HOST}: //"
1445     fi
1446     return ${PIPESTATUS[0]}
1447 }
1448
1449 single_local_node () {
1450    [ "$1" = "$HOSTNAME" ]
1451 }
1452
1453 do_nodes() {
1454     local verbose=false
1455     # do not stripe off hostname if verbose, bug 19215
1456     if [ x$1 = x--verbose ]; then
1457         shift
1458         verbose=true
1459     fi
1460
1461     local rnodes=$1
1462     shift
1463
1464     if $(single_local_node $rnodes); then
1465         if $verbose; then
1466            do_node --verbose $rnodes $@
1467         else
1468            do_node $rnodes $@
1469         fi
1470         return $?
1471     fi
1472
1473     # This is part from do_node
1474     local myPDSH=$PDSH
1475
1476     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
1477         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
1478
1479     if $VERBOSE; then
1480         echo "CMD: $rnodes $@" >&2
1481         $myPDSH $rnodes $LCTL mark "$@" > /dev/null 2>&1 || :
1482     fi
1483
1484     if $verbose ; then
1485         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")"
1486     else
1487         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed -re "s/\w+:\s//g"
1488     fi
1489     return ${PIPESTATUS[0]}
1490 }
1491
1492 do_facet() {
1493     local facet=$1
1494     shift
1495     local HOST=`facet_active_host $facet`
1496     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
1497     do_node $HOST "$@"
1498 }
1499
1500 add() {
1501     local facet=$1
1502     shift
1503     # make sure its not already running
1504     stop ${facet} -f
1505     rm -f $TMP/${facet}active
1506     do_facet ${facet} $MKFS $*
1507 }
1508
1509 ostdevname() {
1510     num=$1
1511     DEVNAME=OSTDEV$num
1512     #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
1513     eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}}
1514     echo -n $DEVPTR
1515 }
1516
1517 mdsdevname() {
1518     num=$1
1519     DEVNAME=MDSDEV$num
1520     #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
1521     eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}}
1522     echo -n $DEVPTR
1523 }
1524
1525 ########
1526 ## MountConf setup
1527
1528 stopall() {
1529     # make sure we are using the primary server, so test-framework will
1530     # be able to clean up properly.
1531     activemds=`facet_active mds1`
1532     if [ $activemds != "mds1" ]; then
1533         fail mds1
1534     fi
1535
1536     local clients=$CLIENTS
1537     [ -z $clients ] && clients=$(hostname)
1538
1539     zconf_umount_clients $clients $MOUNT "$*" || true
1540     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
1541
1542     [ "$CLIENTONLY" ] && return
1543     # The add fn does rm ${facet}active file, this would be enough
1544     # if we use do_facet <facet> only after the facet added, but
1545     # currently we use do_facet mds in local.sh
1546     for num in `seq $MDSCOUNT`; do
1547         stop mds$num -f
1548         rm -f ${TMP}/mds${num}active
1549     done
1550
1551     for num in `seq $OSTCOUNT`; do
1552         stop ost$num -f
1553         rm -f $TMP/ost${num}active
1554     done
1555
1556     return 0
1557 }
1558
1559 cleanupall() {
1560     nfs_client_mode && return
1561
1562     stopall $*
1563     unload_modules
1564     cleanup_gss
1565 }
1566
1567 mdsmkfsopts()
1568 {
1569     local nr=$1
1570     test $nr = 1 && echo -n $MDS_MKFS_OPTS || echo -n $MDSn_MKFS_OPTS
1571 }
1572
1573 formatall() {
1574     if [ "$IAMDIR" == "yes" ]; then
1575         MDS_MKFS_OPTS="$MDS_MKFS_OPTS --iam-dir"
1576         MDSn_MKFS_OPTS="$MDSn_MKFS_OPTS --iam-dir"
1577     fi
1578
1579     [ "$FSTYPE" ] && FSTYPE_OPT="--backfstype $FSTYPE"
1580
1581     if [ ! -z $SEC ]; then
1582         MDS_MKFS_OPTS="$MDS_MKFS_OPTS --param srpc.flavor.default=$SEC"
1583         MDSn_MKFS_OPTS="$MDSn_MKFS_OPTS --param srpc.flavor.default=$SEC"
1584         OST_MKFS_OPTS="$OST_MKFS_OPTS --param srpc.flavor.default=$SEC"
1585     fi
1586
1587     stopall
1588     # We need ldiskfs here, may as well load them all
1589     load_modules
1590     [ "$CLIENTONLY" ] && return
1591     echo Formatting mgs, mds, osts
1592     if [[ $MDSDEV1 != $MGSDEV ]] || [[ $mds1_HOST != $mgs_HOST ]]; then
1593         add mgs $mgs_MKFS_OPTS $FSTYPE_OPT --reformat $MGSDEV || exit 10
1594     fi
1595
1596     for num in `seq $MDSCOUNT`; do
1597         echo "Format mds$num: $(mdsdevname $num)"
1598         if $VERBOSE; then
1599             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` || exit 9
1600         else
1601             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` > /dev/null || exit 9
1602         fi
1603     done
1604
1605     for num in `seq $OSTCOUNT`; do
1606         echo "Format ost$num: $(ostdevname $num)"
1607         if $VERBOSE; then
1608             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` || exit 10
1609         else
1610             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` > /dev/null || exit 10
1611         fi
1612     done
1613 }
1614
1615 mount_client() {
1616     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
1617 }
1618
1619 umount_client() {
1620     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
1621 }
1622
1623 # return value:
1624 # 0: success, the old identity set already.
1625 # 1: success, the old identity does not set.
1626 # 2: fail.
1627 switch_identity() {
1628     local num=$1
1629     local switch=$2
1630     local j=`expr $num - 1`
1631     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
1632
1633     if [ -z "$MDT" ]; then
1634         return 2
1635     fi
1636
1637     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
1638
1639     if $switch; then
1640         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
1641     else
1642         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
1643     fi
1644
1645     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush \"-1\""
1646
1647     if [ $old = "NONE" ]; then
1648         return 1
1649     else
1650         return 0
1651     fi
1652 }
1653
1654 remount_client()
1655 {
1656         zconf_umount `hostname` $1 || error "umount failed"
1657         zconf_mount `hostname` $1 || error "mount failed"
1658 }
1659
1660 writeconf_facet () {
1661     local facet=$1
1662     local dev=$2
1663
1664     do_facet $facet "$TUNEFS --writeconf $dev"
1665 }
1666
1667 writeconf_all () {
1668     for num in `seq $MDSCOUNT`; do
1669         DEVNAME=$(mdsdevname $num)
1670         writeconf_facet mds$num $DEVNAME
1671     done
1672
1673     for num in `seq $OSTCOUNT`; do
1674         DEVNAME=$(ostdevname $num)
1675         writeconf_facet ost$num $DEVNAME
1676     done
1677 }
1678
1679 setupall() {
1680     nfs_client_mode && return
1681
1682     sanity_mount_check ||
1683         error "environments are insane!"
1684
1685     load_modules
1686     init_gss
1687     if [ -z "$CLIENTONLY" ]; then
1688         echo Setup mgs, mdt, osts
1689         echo $WRITECONF | grep -q "writeconf" && \
1690             writeconf_all
1691         if [[ $mds1_HOST != $mgs_HOST ]] || [[ $MDSDEV1 != $MGSDEV ]]; then
1692             start mgs $MGSDEV $mgs_MOUNT_OPTS
1693         fi
1694
1695         for num in `seq $MDSCOUNT`; do
1696             DEVNAME=$(mdsdevname $num)
1697             start mds$num $DEVNAME $MDS_MOUNT_OPTS
1698
1699             # We started mds, now we should set failover variables properly.
1700             # Set mds${num}failover_HOST if it is not set (the default failnode).
1701             local varname=mds${num}failover_HOST
1702             if [ -z "${!varname}" ]; then
1703                 eval mds${num}failover_HOST=$(facet_host mds$num)
1704             fi
1705
1706             if [ $IDENTITY_UPCALL != "default" ]; then
1707                 switch_identity $num $IDENTITY_UPCALL
1708             fi
1709         done
1710         for num in `seq $OSTCOUNT`; do
1711             DEVNAME=$(ostdevname $num)
1712             start ost$num $DEVNAME $OST_MOUNT_OPTS
1713
1714             # We started ost$num, now we should set ost${num}failover variable properly.
1715             # Set ost${num}failover_HOST if it is not set (the default failnode).
1716             varname=ost${num}failover_HOST
1717             if [ -z "${!varname}" ]; then
1718                 eval ost${num}failover_HOST=$(facet_host ost${num})
1719             fi
1720
1721         done
1722     fi
1723     # wait a while to allow sptlrpc configuration be propogated to targets,
1724     # only needed when mounting new target devices.
1725     $GSS && sleep 10
1726
1727     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
1728     mount_client $MOUNT
1729     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
1730
1731     if [ "$MOUNT_2" ]; then
1732         mount_client $MOUNT2
1733         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
1734     fi
1735
1736     init_param_vars
1737
1738     # by remounting mdt before ost, initial connect from mdt to ost might
1739     # timeout because ost is not ready yet. wait some time to its fully
1740     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
1741     # by a context negotiation rpc with $TIMEOUT.
1742     # FIXME better by monitoring import status.
1743     if $GSS; then
1744         sleep $((TIMEOUT + 5))
1745     else
1746         sleep 5
1747     fi
1748 }
1749
1750 mounted_lustre_filesystems() {
1751         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
1752 }
1753
1754 init_facet_vars () {
1755     [ "$CLIENTONLY" ] && return 0
1756     local facet=$1
1757     shift
1758     local device=$1
1759
1760     shift
1761
1762     eval export ${facet}_dev=${device}
1763     eval export ${facet}_opt=\"$@\"
1764
1765     local dev=${facet}_dev
1766     local label=$(do_facet ${facet} "$E2LABEL ${!dev}")
1767     [ -z "$label" ] && echo no label for ${!dev} && exit 1
1768
1769     eval export ${facet}_svc=${label}
1770
1771     local varname=${facet}failover_HOST
1772     if [ -z "${!varname}" ]; then
1773        eval $varname=$(facet_host $facet) 
1774     fi
1775
1776     # ${facet}failover_dev is set in cfg file
1777     varname=${facet}failover_dev
1778     if [ -n "${!varname}" ] ; then
1779         eval export ${facet}failover_dev=${!varname}
1780     else
1781         eval export ${facet}failover_dev=$device
1782     fi
1783 }
1784
1785 init_facets_vars () {
1786     local DEVNAME
1787
1788     if ! remote_mds_nodsh; then 
1789         for num in `seq $MDSCOUNT`; do
1790             DEVNAME=`mdsdevname $num`
1791             init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
1792         done
1793     fi
1794
1795     remote_ost_nodsh && return
1796
1797     for num in `seq $OSTCOUNT`; do
1798         DEVNAME=`ostdevname $num`
1799         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
1800     done
1801 }
1802
1803 osc_ensure_active () {
1804     local facet=$1
1805     local type=$2
1806     local timeout=$3
1807     local period=0
1808
1809     while [ $period -lt $timeout ]; do
1810         count=$(do_facet $facet "lctl dl | grep '${FSNAME}-OST.*-osc-${type}' | grep ' IN ' 2>/dev/null | wc -l")
1811         if [ $count -eq 0 ]; then
1812             break
1813         fi
1814
1815         echo "There are $count OST are inactive, wait $period seconds, and try again"
1816         sleep 3
1817         period=$((period+3))
1818     done
1819
1820     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
1821 }
1822
1823 som_check() {
1824     SOM_ENABLED=$(do_facet $SINGLEMDS "$LCTL get_param mdt.*.som" | awk -F= ' {print $2}' | head -n 1)
1825     echo $SOM_ENABLED
1826 }
1827
1828 init_param_vars () {
1829     if ! remote_ost_nodsh && ! remote_mds_nodsh; then
1830         export MDSVER=$(do_facet $SINGLEMDS "lctl get_param version" | cut -d. -f1,2)
1831         export OSTVER=$(do_facet ost1 "lctl get_param version" | cut -d. -f1,2)
1832         export CLIVER=$(lctl get_param version | cut -d. -f 1,2)
1833     fi
1834
1835     remote_mds_nodsh ||
1836         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
1837
1838     log "Using TIMEOUT=$TIMEOUT"
1839
1840     osc_ensure_active $SINGLEMDS M $TIMEOUT
1841     osc_ensure_active client c $TIMEOUT
1842
1843     if [ x"$(som_check)" = x"enabled" ]; then
1844         ENABLE_QUOTA=""
1845         echo "disable quota temporary when SOM enabled"
1846     fi
1847     if [ $QUOTA_AUTO -ne 0 ]; then
1848         if [ "$ENABLE_QUOTA" ]; then
1849             echo "enable quota as required"
1850             setup_quota $MOUNT || return 2
1851         else
1852             echo "disable quota as required"
1853             $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
1854         fi
1855     fi
1856 }
1857
1858 nfs_client_mode () {
1859     if [ "$NFSCLIENT" ]; then
1860         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
1861         local clients=$CLIENTS
1862         [ -z $clients ] && clients=$(hostname)
1863
1864         # FIXME: remove hostname when 19215 fixed
1865         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
1866         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
1867         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
1868         return
1869     fi
1870     return 1
1871 }
1872
1873 check_config () {
1874     nfs_client_mode && return
1875
1876     local mntpt=$1
1877
1878     local mounted=$(mount | grep " $mntpt ")
1879     if [ "$CLIENTONLY" ]; then
1880         # bug 18021
1881         # CLIENTONLY should not depend on *_HOST settings
1882         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
1883         # in theory someone could create a new,
1884         # client-only config file that assumed lustre was already
1885         # configured and didn't set the MGSNID. If MGSNID is not set,
1886         # then we should use the mgs nid currently being used 
1887         # as the default value. bug 18021
1888         [[ x$MGSNID = x ]] &&
1889             MGSNID=${mgc//MGC/}
1890
1891         if [[ x$mgc != xMGC$MGSNID ]]; then
1892             if [ "$mgs_HOST" ]; then
1893                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
1894 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
1895 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
1896             fi
1897         fi
1898         return 0
1899     fi
1900
1901     local myMGS_host=$mgs_HOST   
1902     if [ "$NETTYPE" = "ptl" ]; then
1903         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
1904     fi
1905
1906     echo Checking config lustre mounted on $mntpt
1907     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
1908     mgshost=$(echo $mgshost | awk -F: '{print $1}')
1909
1910     if [ "$mgshost" != "$myMGS_host" ]; then
1911             log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
1912                    Please use correct config or set mds_HOST correctly!"
1913     fi
1914
1915     sanity_mount_check ||
1916         error "environments are insane!"
1917 }
1918
1919 check_timeout () {
1920     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
1921     local cltimeout=$(lctl get_param -n timeout)
1922     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
1923         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
1924         return 1
1925     fi
1926 }
1927
1928 check_and_setup_lustre() {
1929     nfs_client_mode && return
1930
1931     local MOUNTED=$(mounted_lustre_filesystems)
1932
1933     local do_check=true
1934     # MOUNT is not mounted
1935     if [ -z "$MOUNTED" ] || ! $(echo $MOUNTED | grep -w -q $MOUNT); then
1936         [ "$REFORMAT" ] && formatall
1937         setupall
1938         MOUNTED=$(mounted_lustre_filesystems | head -1)
1939         [ -z "$MOUNTED" ] && error "NAME=$NAME not mounted"
1940         export I_MOUNTED=yes
1941         do_check=false
1942
1943     # MOUNT and MOUNT2 are mounted
1944     elif $(echo $MOUNTED | grep -w -q $MOUNT2); then
1945
1946         # MOUNT2 is mounted,  MOUNT_2 is not set
1947         if ! [ "$MOUNT_2" ]; then
1948             zconf_umount `hostname` $MOUNT2
1949             export I_UMOUNTED2=yes
1950
1951         # MOUNT2 is mounted, MOUNT_2 is set
1952         else
1953             check_config $MOUNT2
1954         fi 
1955     fi
1956
1957     if $do_check; then
1958         check_config $MOUNT
1959         init_facets_vars
1960         init_param_vars
1961
1962         do_nodes $(comma_list $(nodes_list)) "lctl set_param debug=\\\"$PTLDEBUG\\\";
1963             lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
1964             lctl set_param debug_mb=${DEBUG_SIZE};
1965             sync"
1966     fi
1967     if [ "$ONLY" == "setup" ]; then
1968         exit 0
1969     fi
1970 }
1971
1972 cleanup_and_setup_lustre() {
1973     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
1974         lctl set_param debug=0 || true
1975         cleanupall
1976         if [ "$ONLY" == "cleanup" ]; then
1977             exit 0
1978         fi
1979     fi
1980     check_and_setup_lustre
1981 }
1982
1983 check_and_cleanup_lustre() {
1984     if [ "`mount | grep $MOUNT`" ]; then
1985         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
1986         [ "$ENABLE_QUOTA" ] && restore_quota_type || true
1987     fi
1988     if [ "$I_UMOUNTED2" = "yes" ]; then
1989         mount_client $MOUNT2 || error "restore $MOUNT2 failed"
1990     fi
1991
1992     if [ "$I_MOUNTED" = "yes" ]; then
1993         cleanupall -f || error "cleanup failed"
1994     fi
1995     unset I_MOUNTED
1996 }
1997
1998 #######
1999 # General functions
2000
2001 check_network() {
2002     local NETWORK=0
2003     local WAIT=0
2004     local MAX=$2
2005     while [ $NETWORK -eq 0 ]; do
2006         if ping -c 1 -w 3 $1 > /dev/null; then
2007             NETWORK=1
2008         else
2009             WAIT=$((WAIT + 5))
2010             echo "waiting for $1, $((MAX - WAIT)) secs left"
2011             sleep 5
2012         fi
2013         if [ $WAIT -gt $MAX ]; then
2014             echo "Network not available"
2015             exit 1
2016         fi
2017     done
2018 }
2019 check_port() {
2020     while( !($DSH2 $1 "netstat -tna | grep -q $2") ) ; do
2021         sleep 9
2022     done
2023 }
2024
2025 no_dsh() {
2026     shift
2027     eval $@
2028 }
2029
2030 comma_list() {
2031     # the sed converts spaces to commas, but leaves the last space
2032     # alone, so the line doesn't end with a comma.
2033     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
2034 }
2035
2036 # list, excluded are the comma separated lists
2037 exclude_items_from_list () {
2038     local list=$1
2039     local excluded=$2
2040     local item
2041
2042     list=${list//,/ }
2043     for item in ${excluded//,/ }; do
2044         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
2045     done
2046     echo $(comma_list $list) 
2047 }
2048
2049 # list, expand  are the comma separated lists
2050 expand_list () {
2051     local list=${1//,/ }
2052     local expand=${2//,/ }
2053     local expanded=
2054
2055     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
2056     echo $(comma_list $expanded)
2057 }
2058
2059 testslist_filter () {
2060     local script=$LUSTRE/tests/${TESTSUITE}.sh
2061
2062     [ -f $script ] || return 0
2063
2064     local start_at=$START_AT
2065     local stop_at=$STOP_AT
2066
2067     local var=${TESTSUITE//-/_}_START_AT
2068     [ x"${!var}" != x ] && start_at=${!var}
2069     var=${TESTSUITE//-/_}_STOP_AT
2070     [ x"${!var}" != x ] && stop_at=${!var}
2071
2072     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
2073         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
2074             /^'${start_at}'$/ {flag = 0}
2075             {if (flag == 1) print $0}
2076             /^'${stop_at}'$/ { flag = 1 }'
2077 }
2078
2079 absolute_path() {
2080     (cd `dirname $1`; echo $PWD/`basename $1`)
2081 }
2082
2083 get_facets () {
2084     local name=$(echo $1 | tr "[:upper:]" "[:lower:]")
2085     local type=$(echo $1 | tr "[:lower:]" "[:upper:]")
2086
2087     local list=""
2088     local count=${type}COUNT
2089     for ((i=1; i<=${!count}; i++)) do
2090         list="$list ${name}$i"
2091     done
2092     echo $(comma_list $list)
2093 }
2094
2095 ##################################
2096 # Adaptive Timeouts funcs
2097
2098 at_is_enabled() {
2099     # only check mds, we assume at_max is the same on all nodes
2100     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
2101     if [ $at_max -eq 0 ]; then
2102         return 1
2103     else
2104         return 0
2105     fi
2106 }
2107
2108 at_max_get() {
2109     local facet=$1
2110
2111     # suppose that all ost-s has the same at_max set
2112     if [ $facet == "ost" ]; then
2113         do_facet ost1 "lctl get_param -n at_max"
2114     else
2115         do_facet $facet "lctl get_param -n at_max"
2116     fi
2117 }
2118
2119 at_max_set() {
2120     local at_max=$1
2121     shift
2122
2123     local facet
2124     for facet in $@; do
2125         if [ $facet == "ost" ]; then
2126             for i in `seq $OSTCOUNT`; do
2127                 do_facet ost$i "lctl set_param at_max=$at_max"
2128
2129             done
2130         elif [ $facet == "mds" ]; then
2131             for i in `seq $MDSCOUNT`; do
2132                 do_facet mds$i "lctl set_param at_max=$at_max"
2133             done
2134         else
2135             do_facet $facet "lctl set_param at_max=$at_max"
2136         fi
2137     done
2138 }
2139
2140 ##################################
2141 # OBD_FAIL funcs
2142
2143 drop_request() {
2144 # OBD_FAIL_MDS_ALL_REQUEST_NET
2145     RC=0
2146     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
2147     do_facet client "$1" || RC=$?
2148     do_facet $SINGLEMDS lctl set_param fail_loc=0
2149     return $RC
2150 }
2151
2152 drop_reply() {
2153 # OBD_FAIL_MDS_ALL_REPLY_NET
2154     RC=0
2155     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
2156     do_facet client "$@" || RC=$?
2157     do_facet $SINGLEMDS lctl set_param fail_loc=0
2158     return $RC
2159 }
2160
2161 drop_reint_reply() {
2162 # OBD_FAIL_MDS_REINT_NET_REP
2163     RC=0
2164     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
2165     do_facet client "$@" || RC=$?
2166     do_facet $SINGLEMDS lctl set_param fail_loc=0
2167     return $RC
2168 }
2169
2170 pause_bulk() {
2171 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
2172     RC=0
2173     do_facet ost1 lctl set_param fail_loc=0x214
2174     do_facet client "$1" || RC=$?
2175     do_facet client "sync"
2176     do_facet ost1 lctl set_param fail_loc=0
2177     return $RC
2178 }
2179
2180 drop_ldlm_cancel() {
2181 #define OBD_FAIL_LDLM_CANCEL             0x304
2182     RC=0
2183     do_facet client lctl set_param fail_loc=0x304
2184     do_facet client "$@" || RC=$?
2185     do_facet client lctl set_param fail_loc=0
2186     return $RC
2187 }
2188
2189 drop_bl_callback() {
2190 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
2191     RC=0
2192     do_facet client lctl set_param fail_loc=0x305
2193     do_facet client "$@" || RC=$?
2194     do_facet client lctl set_param fail_loc=0
2195     return $RC
2196 }
2197
2198 drop_ldlm_reply() {
2199 #define OBD_FAIL_LDLM_REPLY              0x30c
2200     RC=0
2201     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
2202     do_facet client "$@" || RC=$?
2203     do_facet $SINGLEMDS lctl set_param fail_loc=0
2204     return $RC
2205 }
2206
2207 clear_failloc() {
2208     facet=$1
2209     pause=$2
2210     sleep $pause
2211     echo "clearing fail_loc on $facet"
2212     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
2213 }
2214
2215 set_nodes_failloc () {
2216     do_nodes $(comma_list $1)  lctl set_param fail_loc=$2
2217 }
2218
2219 cancel_lru_locks() {
2220     $LCTL mark "cancel_lru_locks $1 start"
2221     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
2222         $LCTL set_param -n $d=clear
2223     done
2224     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
2225     $LCTL mark "cancel_lru_locks $1 stop"
2226 }
2227
2228 default_lru_size()
2229 {
2230         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
2231         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
2232         echo "$DEFAULT_LRU_SIZE"
2233 }
2234
2235 lru_resize_enable()
2236 {
2237     lctl set_param ldlm.namespaces.*$1*.lru_size=0
2238 }
2239
2240 lru_resize_disable()
2241 {
2242     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
2243 }
2244
2245 pgcache_empty() {
2246     local FILE
2247     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
2248         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
2249             echo there is still data in page cache $FILE ?
2250             lctl get_param -n $FILE
2251             return 1
2252         fi
2253     done
2254     if [[ $MDSDEV1 != $MGSDEV ]]; then
2255         stop mgs 
2256     fi
2257
2258     return 0
2259 }
2260
2261 debugsave() {
2262     DEBUGSAVE="$(lctl get_param -n debug)"
2263 }
2264
2265 debugrestore() {
2266     [ -n "$DEBUGSAVE" ] && \
2267         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
2268     DEBUGSAVE=""
2269 }
2270
2271 debug_size_save() {
2272     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
2273 }
2274
2275 debug_size_restore() {
2276     [ -n "$DEBUG_SIZE_SAVED" ] && \
2277         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
2278     DEBUG_SIZE_SAVED=""
2279 }
2280
2281 start_full_debug_logging() {
2282     debugsave
2283     debug_size_save
2284
2285     local FULLDEBUG=-1
2286     local DEBUG_SIZE=150
2287
2288     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
2289     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
2290 }
2291
2292 stop_full_debug_logging() {
2293     debug_size_restore
2294     debugrestore
2295 }
2296
2297 ##################################
2298 # Test interface
2299 ##################################
2300
2301 error_noexit() {
2302     local TYPE=${TYPE:-"FAIL"}
2303     local ERRLOG
2304
2305     local dump=true
2306     # do not dump logs if $1=false
2307     if [ "x$1" = "xfalse" ]; then
2308         shift
2309         dump=false
2310     fi
2311
2312     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
2313
2314     if $dump; then
2315         ERRLOG=$TMP/lustre_${TESTSUITE}_${TESTNAME}.$(date +%s)
2316         echo "Dumping lctl log to $ERRLOG"
2317         # We need to dump the logs on all nodes
2318         do_nodes $(comma_list $(nodes_list)) $NODE $LCTL dk $ERRLOG
2319     fi
2320     debugrestore
2321     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
2322     TEST_FAILED=true
2323 }
2324
2325 error() {
2326     error_noexit "$@"
2327     if $FAIL_ON_ERROR; then
2328         reset_fail_loc
2329         exit 1
2330     fi
2331 }
2332
2333 error_exit() {
2334     error_noexit "$@"
2335     exit 1
2336 }
2337
2338 # use only if we are ignoring failures for this test, bugno required.
2339 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
2340 # e.g. error_ignore 5494 "your message"
2341 error_ignore() {
2342     local TYPE="IGNORE (bz$1)"
2343     shift
2344     error_noexit "$@"
2345 }
2346
2347 skip_env () {
2348     $FAIL_ON_SKIP_ENV && error false $@ || skip $@
2349 }
2350
2351 skip () {
2352     echo
2353     log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
2354     [ "$TESTSUITELOG" ] && \
2355         echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
2356 }
2357
2358 build_test_filter() {
2359     EXCEPT="$EXCEPT $(testslist_filter)"
2360
2361     [ "$ONLY" ] && log "only running test `echo $ONLY`"
2362     for O in $ONLY; do
2363         eval ONLY_${O}=true
2364     done
2365     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
2366         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
2367     [ "$EXCEPT_SLOW" ] && \
2368         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
2369     for E in $EXCEPT $ALWAYS_EXCEPT; do
2370         eval EXCEPT_${E}=true
2371     done
2372     for E in $EXCEPT_SLOW; do
2373         eval EXCEPT_SLOW_${E}=true
2374     done
2375     for G in $GRANT_CHECK_LIST; do
2376         eval GCHECK_ONLY_${G}=true
2377         done
2378 }
2379
2380 basetest() {
2381     if [[ $1 = [a-z]* ]]; then
2382         echo $1
2383     else
2384         echo ${1%%[a-z]*}
2385     fi
2386 }
2387
2388 # print a newline if the last test was skipped
2389 export LAST_SKIPPED=
2390 run_test() {
2391     assert_DIR
2392
2393     export base=`basetest $1`
2394     if [ ! -z "$ONLY" ]; then
2395         testname=ONLY_$1
2396         if [ ${!testname}x != x ]; then
2397             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2398             run_one $1 "$2"
2399             return $?
2400         fi
2401         testname=ONLY_$base
2402         if [ ${!testname}x != x ]; then
2403             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2404             run_one $1 "$2"
2405             return $?
2406         fi
2407         LAST_SKIPPED="y"
2408         echo -n "."
2409         return 0
2410     fi
2411     testname=EXCEPT_$1
2412     if [ ${!testname}x != x ]; then
2413         LAST_SKIPPED="y"
2414         TESTNAME=test_$1 skip "skipping excluded test $1"
2415         return 0
2416     fi
2417     testname=EXCEPT_$base
2418     if [ ${!testname}x != x ]; then
2419         LAST_SKIPPED="y"
2420         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
2421         return 0
2422     fi
2423     testname=EXCEPT_SLOW_$1
2424     if [ ${!testname}x != x ]; then
2425         LAST_SKIPPED="y"
2426         TESTNAME=test_$1 skip "skipping SLOW test $1"
2427         return 0
2428     fi
2429     testname=EXCEPT_SLOW_$base
2430     if [ ${!testname}x != x ]; then
2431         LAST_SKIPPED="y"
2432         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
2433         return 0
2434     fi
2435
2436     LAST_SKIPPED=
2437     run_one $1 "$2"
2438
2439     return $?
2440 }
2441
2442 EQUALS="======================================================================"
2443 equals_msg() {
2444     msg="$@"
2445
2446     local suffixlen=$((${#EQUALS} - ${#msg}))
2447     [ $suffixlen -lt 5 ] && suffixlen=5
2448     log `echo $(printf '===== %s %.*s\n' "$msg" $suffixlen $EQUALS)`
2449 }
2450
2451 log() {
2452     echo "$*"
2453     module_loaded lnet || load_modules
2454
2455     local MSG="$*"
2456     # Get rid of '
2457     MSG=${MSG//\'/\\\'}
2458     MSG=${MSG//\(/\\\(}
2459     MSG=${MSG//\)/\\\)}
2460     MSG=${MSG//\;/\\\;}
2461     MSG=${MSG//\|/\\\|}
2462     MSG=${MSG//\>/\\\>}
2463     MSG=${MSG//\</\\\<}
2464     MSG=${MSG//\//\\\/}
2465     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
2466 }
2467
2468 trace() {
2469         log "STARTING: $*"
2470         strace -o $TMP/$1.strace -ttt $*
2471         RC=$?
2472         log "FINISHED: $*: rc $RC"
2473         return 1
2474 }
2475
2476 pass() {
2477     $TEST_FAILED && echo -n "FAIL " || echo -n "PASS " 
2478     echo $@
2479 }
2480
2481 check_mds() {
2482     FFREE=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filesfree | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2483     FTOTAL=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filestotal | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2484     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
2485 }
2486
2487 reset_fail_loc () {
2488     echo -n "Resetting fail_loc on all nodes..."
2489     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
2490     echo done.
2491 }
2492
2493 run_one() {
2494     testnum=$1
2495     message=$2
2496     tfile=f${testnum}
2497     export tdir=d0.${TESTSUITE}/d${base}
2498
2499     local SAVE_UMASK=`umask`
2500     umask 0022
2501
2502     local BEFORE=`date +%s`
2503     echo
2504     log "== test $testnum: $message == `date +%H:%M:%S` ($BEFORE)"
2505     #check_mds
2506     export TESTNAME=test_$testnum
2507     TEST_FAILED=false
2508     test_${testnum} || error "test_$testnum failed with $?"
2509     #check_mds
2510     cd $SAVE_PWD
2511     reset_fail_loc
2512     check_grant ${testnum} || error "check_grant $testnum failed with $?"
2513     check_catastrophe || error "LBUG/LASSERT detected"
2514     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
2515     pass "($((`date +%s` - $BEFORE))s)"
2516     TEST_FAILED=false
2517     unset TESTNAME
2518     unset tdir
2519     umask $SAVE_UMASK
2520 }
2521
2522 canonical_path() {
2523     (cd `dirname $1`; echo $PWD/`basename $1`)
2524 }
2525
2526 sync_clients() {
2527     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
2528     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
2529         cd $SAVE_PWD
2530 }
2531
2532 check_grant() {
2533     export base=`basetest $1`
2534     [ "$CHECK_GRANT" == "no" ] && return 0
2535
2536         testname=GCHECK_ONLY_${base}
2537         [ ${!testname}x == x ] && return 0
2538
2539     echo -n "checking grant......"
2540         cd $SAVE_PWD
2541         # write some data to sync client lost_grant
2542         rm -f $DIR1/${tfile}_check_grant_* 2>&1
2543         for i in `seq $OSTCOUNT`; do
2544                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
2545                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
2546                                               count=1 > /dev/null 2>&1
2547         done
2548         # sync all the data and make sure no pending data on server
2549         sync_clients
2550         
2551         #get client grant and server grant
2552         client_grant=0
2553     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
2554                 client_grant=$((client_grant + $d))
2555         done
2556         server_grant=0
2557         for d in `lctl get_param -n obdfilter.*.tot_granted`; do
2558                 server_grant=$((server_grant + $d))
2559         done
2560
2561         # cleanup the check_grant file
2562         for i in `seq $OSTCOUNT`; do
2563                 rm $DIR1/${tfile}_check_grant_$i
2564         done
2565
2566         #check whether client grant == server grant
2567         if [ $client_grant != $server_grant ]; then
2568                 echo "failed: client:${client_grant} server: ${server_grant}"
2569                 return 1
2570         else
2571                 echo "pass"
2572         fi
2573 }
2574
2575 ########################
2576 # helper functions
2577
2578 osc_to_ost()
2579 {
2580     osc=$1
2581     ost=`echo $1 | awk -F_ '{print $3}'`
2582     if [ -z $ost ]; then
2583         ost=`echo $1 | sed 's/-osc.*//'`
2584     fi
2585     echo $ost
2586 }
2587
2588 remote_node () {
2589     local node=$1
2590     [ "$node" != "$(hostname)" ]
2591 }
2592
2593 remote_mds ()
2594 {
2595     local node
2596     for node in $(mdts_nodes); do
2597         remote_node $node && return 0
2598     done
2599     return 1
2600 }
2601
2602 remote_mds_nodsh()
2603 {
2604     [ "$CLIENTONLY" ] && return 0 || true
2605     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
2606 }
2607
2608 remote_ost ()
2609 {
2610     local node
2611     for node in $(osts_nodes) ; do
2612         remote_node $node && return 0
2613     done
2614     return 1
2615 }
2616
2617 remote_ost_nodsh()
2618 {
2619     [ "$CLIENTONLY" ] && return 0 || true 
2620     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2621 }
2622
2623 remote_mgs_nodsh()
2624 {
2625     local MGS 
2626     MGS=$(facet_host mgs)
2627     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2628 }
2629
2630 mdts_nodes () {
2631     local MDSNODES
2632     local NODES_sort
2633     for num in `seq $MDSCOUNT`; do
2634         MDSNODES="$MDSNODES $(facet_host mds$num)"
2635     done
2636     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
2637
2638     echo $NODES_sort
2639 }
2640
2641 remote_servers () {
2642     remote_ost && remote_mds
2643 }
2644
2645 osts_nodes () {
2646     local OSTNODES=$(facet_host ost1)
2647     local NODES_sort
2648
2649     for num in `seq $OSTCOUNT`; do
2650         local myOST=$(facet_host ost$num)
2651         OSTNODES="$OSTNODES $myOST"
2652     done
2653     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
2654
2655     echo $NODES_sort
2656 }
2657
2658 nodes_list () {
2659     # FIXME. We need a list of clients
2660     local myNODES=$HOSTNAME
2661     local myNODES_sort
2662
2663     # CLIENTS (if specified) contains the local client
2664     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
2665
2666     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
2667         myNODES="$myNODES $(osts_nodes) $(mdts_nodes)"
2668     fi
2669
2670     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
2671
2672     echo $myNODES_sort
2673 }
2674
2675 remote_nodes_list () {
2676     local rnodes=$(nodes_list)
2677     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2678     echo $rnodes
2679 }
2680
2681 init_clients_lists () {
2682     # Sanity check: exclude the local client from RCLIENTS
2683     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2684
2685     # Sanity check: exclude the dup entries
2686     rclients=$(for i in $rclients; do echo $i; done | sort -u)
2687
2688     local clients="$SINGLECLIENT $HOSTNAME $rclients"
2689
2690     # Sanity check: exclude the dup entries from CLIENTS
2691     # for those configs which has SINGLCLIENT set to local client
2692     clients=$(for i in $clients; do echo $i; done | sort -u)
2693
2694     CLIENTS=`comma_list $clients`
2695     local -a remoteclients=($rclients)
2696     for ((i=0; $i<${#remoteclients[@]}; i++)); do
2697             varname=CLIENT$((i + 2))
2698             eval $varname=${remoteclients[i]}
2699     done
2700
2701     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
2702 }
2703
2704 get_random_entry () {
2705     local rnodes=$1
2706
2707     rnodes=${rnodes//,/ }
2708
2709     local -a nodes=($rnodes)
2710     local num=${#nodes[@]} 
2711     local i=$((RANDOM * num * 2 / 65536))
2712
2713     echo ${nodes[i]}
2714 }
2715
2716 client_only () {
2717     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
2718 }
2719
2720 is_patchless ()
2721 {
2722     lctl get_param version | grep -q patchless
2723 }
2724
2725 check_versions () {
2726     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
2727 }
2728
2729 get_node_count() {
2730     local nodes="$@"
2731     echo $nodes | wc -w || true
2732 }
2733
2734 mixed_ost_devs () {
2735     local nodes=$(osts_nodes)
2736     local osscount=$(get_node_count "$nodes")
2737     [ ! "$OSTCOUNT" = "$osscount" ]
2738 }
2739
2740 mixed_mdt_devs () {
2741     local nodes=$(mdts_nodes)
2742     local mdtcount=$(get_node_count "$nodes")
2743     [ ! "$MDSCOUNT" = "$mdtcount" ]
2744 }
2745
2746 generate_machine_file() {
2747     local nodes=${1//,/ }
2748     local machinefile=$2
2749     rm -f $machinefile || error "can't rm $machinefile"
2750     for node in $nodes; do
2751         echo $node >>$machinefile
2752     done
2753 }
2754
2755 get_stripe () {
2756     local file=$1/stripe
2757     touch $file
2758     $LFS getstripe -v $file || error
2759     rm -f $file
2760 }
2761
2762 check_runas_id_ret() {
2763     local myRC=0
2764     local myRUNAS_UID=$1
2765     local myRUNAS_GID=$2
2766     shift 2
2767     local myRUNAS=$@
2768     if [ -z "$myRUNAS" ]; then
2769         error_exit "myRUNAS command must be specified for check_runas_id"
2770     fi
2771     if $GSS_KRB5; then
2772         $myRUNAS krb5_login.sh || \
2773             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
2774     fi
2775     mkdir $DIR/d0_runas_test
2776     chmod 0755 $DIR
2777     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
2778     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
2779     rm -rf $DIR/d0_runas_test
2780     return $myRC
2781 }
2782
2783 check_runas_id() {
2784     local myRUNAS_UID=$1
2785     local myRUNAS_GID=$2
2786     shift 2
2787     local myRUNAS=$@
2788     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
2789         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
2790         Please set RUNAS_ID to some UID which exists on MDS and client or
2791         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
2792 }
2793
2794 # obtain the UID/GID for MPI_USER
2795 get_mpiuser_id() {
2796     local mpi_user=$1
2797
2798     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
2799 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
2800
2801     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
2802 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
2803 }
2804
2805 # obtain and cache Kerberos ticket-granting ticket
2806 refresh_krb5_tgt() {
2807     local myRUNAS_UID=$1
2808     local myRUNAS_GID=$2
2809     shift 2
2810     local myRUNAS=$@
2811     if [ -z "$myRUNAS" ]; then
2812         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
2813     fi
2814
2815     CLIENTS=${CLIENTS:-$HOSTNAME}
2816     do_nodes $CLIENTS "set -x
2817 if ! $myRUNAS krb5_login.sh; then
2818     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
2819     exit 1
2820 fi"
2821 }
2822
2823 # Run multiop in the background, but wait for it to print
2824 # "PAUSING" to its stdout before returning from this function.
2825 multiop_bg_pause() {
2826     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
2827     FILE=$1
2828     ARGS=$2
2829
2830     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
2831     mkfifo $TMPPIPE
2832
2833     echo "$MULTIOP_PROG $FILE v$ARGS"
2834     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
2835
2836     echo "TMPPIPE=${TMPPIPE}"
2837     read -t 60 multiop_output < $TMPPIPE
2838     if [ $? -ne 0 ]; then
2839         rm -f $TMPPIPE
2840         return 1
2841     fi
2842     rm -f $TMPPIPE
2843     if [ "$multiop_output" != "PAUSING" ]; then
2844         echo "Incorrect multiop output: $multiop_output"
2845         kill -9 $PID
2846         return 1
2847     fi
2848
2849     return 0
2850 }
2851
2852 do_and_time () {
2853     local cmd=$1
2854     local rc
2855
2856     SECONDS=0
2857     eval '$cmd'
2858     
2859     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
2860
2861     echo $SECONDS
2862     return $rc
2863 }
2864
2865 inodes_available () {
2866     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
2867     echo $IFree
2868 }
2869
2870 # reset llite stat counters
2871 clear_llite_stats(){
2872         lctl set_param -n llite.*.stats 0
2873 }
2874
2875 # sum llite stat items
2876 calc_llite_stats() {
2877         local res=$(lctl get_param -n llite.*.stats |
2878                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
2879         echo $res
2880 }
2881
2882 # reset osc stat counters
2883 clear_osc_stats(){
2884         lctl set_param -n osc.*.osc_stats 0
2885 }
2886
2887 # sum osc stat items
2888 calc_osc_stats() {
2889         local res=$(lctl get_param -n osc.*.osc_stats |
2890                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
2891         echo $res
2892 }
2893
2894 calc_sum () {
2895         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
2896 }
2897
2898 calc_osc_kbytes () {
2899         df $MOUNT > /dev/null
2900         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
2901 }
2902
2903 # save_lustre_params(node, parameter_mask)
2904 # generate a stream of formatted strings (<node> <param name>=<param value>)
2905 save_lustre_params() {
2906         local s
2907         do_nodes --verbose $1 "lctl get_param $2 | while read s; do echo \\\$s; done"
2908 }
2909
2910 # restore lustre parameters from input stream, produces by save_lustre_params
2911 restore_lustre_params() {
2912         local node
2913         local name
2914         local val
2915         while IFS=" =" read node name val; do
2916                 do_node ${node//:/} "lctl set_param -n $name $val"
2917         done
2918 }
2919
2920 check_catastrophe() {
2921     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
2922     local C=$CATASTROPHE
2923     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
2924
2925     if [ $rnodes ]; then
2926         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
2927 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
2928 exit \\\$rc;"
2929     fi 
2930 }
2931
2932 # $1 node
2933 # $2 file
2934 # $3 $RUNAS
2935 get_stripe_info() {
2936         local tmp_file
2937
2938         stripe_size=0
2939         stripe_count=0
2940         stripe_index=0
2941         tmp_file=$(mktemp)
2942
2943         do_facet $1 $3 lfs getstripe -v $2 > $tmp_file
2944
2945         stripe_size=`awk '$1 ~ /size/ {print $2}' $tmp_file`
2946         stripe_count=`awk '$1 ~ /count/ {print $2}' $tmp_file`
2947         stripe_index=`awk '$1 ~ /stripe_offset/ {print $2}' $tmp_file`
2948         rm -f $tmp_file
2949 }
2950
2951 # CMD: determine mds index where directory inode presents
2952 get_mds_dir () {
2953     local dir=$1
2954     local file=$dir/f0.get_mds_dir_tmpfile
2955
2956     mkdir -p $dir
2957     rm -f $file
2958     sleep 1
2959     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
2960     local -a oldused=($iused)
2961
2962     openfile -f O_CREAT:O_LOV_DELAY_CREATE -m 0644 $file > /dev/null
2963     sleep 1
2964     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
2965     local -a newused=($iused)
2966
2967     local num=0
2968     for ((i=0; i<${#newused[@]}; i++)); do
2969          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
2970              echo $(( i + 1 ))
2971              rm -f $file
2972              return 0
2973          fi
2974     done
2975     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
2976 }
2977
2978 mdsrate_cleanup () {
2979     if [ -d $4 ]; then
2980         mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
2981         rmdir $4
2982     fi
2983 }
2984
2985 delayed_recovery_enabled () {
2986     local var=${SINGLEMDS}_svc
2987     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
2988 }
2989
2990 ########################
2991
2992 convert_facet2label() { 
2993     local facet=$1
2994
2995     if [ x$facet = xost ]; then
2996        facet=ost1
2997     fi
2998
2999     local varsvc=${facet}_svc
3000
3001     if [ -n ${!varsvc} ]; then
3002         echo ${!varsvc}
3003     else  
3004         error "No lablel for $facet!"
3005     fi
3006 }
3007
3008 get_clientosc_proc_path() {
3009     local ost=$1
3010
3011     echo "{$1}-osc-*"
3012 }
3013
3014 get_lustre_version () {
3015     local node=${1:-"mds"}    
3016     do_facet $node $LCTL get_param -n version |  awk '/^lustre:/ {print $2}'
3017 }
3018
3019 get_mds_version_major () {
3020     local version=$(get_lustre_version mds)
3021     echo $version | awk -F. '{print $1}'
3022 }
3023
3024 get_mds_version_minor () {
3025     local version=$(get_lustre_version mds)
3026     echo $version | awk -F. '{print $2}'
3027 }
3028
3029 get_mdtosc_proc_path() {
3030     local ost=$1
3031     local major=$(get_mds_version_major)
3032     local minor=$(get_mds_version_minor)
3033     if [ $major -le 1 -a $minor -le 8 ] ; then
3034         echo "${ost}-osc"
3035     else
3036         echo "${ost}-osc-MDT0000"
3037     fi
3038 }
3039
3040 get_osc_import_name() {
3041     local facet=$1
3042     local ost=$2
3043     local label=$(convert_facet2label $ost)
3044
3045     if [ "$facet" == "mds" ]; then
3046         get_mdtosc_proc_path $label
3047         return 0
3048     fi
3049
3050     get_clientosc_proc_path $label
3051     return 0
3052 }
3053
3054 wait_import_state () {
3055     local expected=$1
3056     local CONN_PROC=$2
3057     local CONN_STATE
3058     local i=0
3059
3060     CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3061     while [ "${CONN_STATE}" != "${expected}" ]; do
3062         if [ "${expected}" == "DISCONN" ]; then
3063             # for disconn we can check after proc entry is removed
3064             [ "x${CONN_STATE}" == "x" ] && return 0
3065             #  with AT we can have connect request timeout ~ reconnect timeout
3066             # and test can't see real disconnect
3067             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
3068         fi
3069         # disconnect rpc should be wait not more obd_timeout
3070         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
3071             error "can't put import for $CONN_PROC into ${expected} state" && return 1
3072         sleep 1
3073         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3074         i=$(($i + 1))
3075     done
3076
3077     log "$CONN_PROC now in ${CONN_STATE} state"
3078     return 0
3079 }
3080
3081 wait_osc_import_state() {
3082     local facet=$1
3083     local ost_facet=$2
3084     local expected=$3
3085     local ost=$(get_osc_import_name $facet $ost_facet)
3086     local CONN_PROC
3087     local CONN_STATE
3088     local i=0
3089
3090     CONN_PROC="osc.${ost}.ost_server_uuid"
3091     CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3092     while [ "${CONN_STATE}" != "${expected}" ]; do
3093         if [ "${expected}" == "DISCONN" ]; then 
3094             # for disconn we can check after proc entry is removed
3095             [ "x${CONN_STATE}" == "x" ] && return 0
3096             #  with AT we can have connect request timeout ~ reconnect timeout
3097             # and test can't see real disconnect
3098             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
3099         fi
3100         # disconnect rpc should be wait not more obd_timeout
3101         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
3102             error "can't put import for ${ost}(${ost_facet}) into ${expected} state" && return 1
3103         sleep 1
3104         CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3105         i=$(($i + 1))
3106     done
3107
3108     log "${ost_facet} now in ${CONN_STATE} state"
3109     return 0
3110 }
3111
3112 get_clientmdc_proc_path() {
3113     echo "${1}-mdc-*"
3114 }
3115
3116 do_rpc_nodes () {
3117     local list=$1
3118     shift
3119
3120     do_nodes --verbose $list "PATH=$LUSTRE/tests/:$PATH sh rpc.sh $@ " 
3121 }
3122
3123 wait_clients_import_state () {
3124     local list=$1
3125     local facet=$2
3126     local expected=$3
3127     shift
3128
3129     local label=$(convert_facet2label $facet)
3130     local proc_path
3131     case $facet in
3132         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
3133         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
3134         *) error "unknown facet!" ;;
3135     esac
3136
3137
3138     if ! do_rpc_nodes $list wait_import_state $expected $proc_path; then
3139         error "import is not in ${expected} state"
3140         return 1
3141     fi
3142 }
3143
3144 oos_full() {
3145         local -a AVAILA
3146         local -a GRANTA
3147         local OSCFULL=1
3148         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
3149                   $LCTL get_param obdfilter.*.kbytesavail))
3150         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
3151                   $LCTL get_param -n obdfilter.*.tot_granted))
3152         for ((i=0; i<${#AVAILA[@]}; i++)); do
3153                 local -a AVAIL1=(${AVAILA[$i]//=/ })
3154                 GRANT=$((${GRANTA[$i]}/1024))
3155                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} grnt=$GRANT diff=$((AVAIL1[1] - GRANT))
3156                 [ $((AVAIL1[1] - GRANT)) -lt 400 ] && OSCFULL=0 && echo " FULL" || echo
3157         done
3158         return $OSCFULL
3159 }
3160
3161 destroy_pool_int() {
3162     local ost
3163     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
3164         awk '$1 !~ /^Pool:/ {print $1}')
3165     for ost in $OSTS; do
3166         do_facet mgs lctl pool_remove $1 $ost
3167     done
3168     do_facet mgs lctl pool_destroy $1
3169 }
3170
3171 destroy_pool() {
3172     local RC
3173
3174     do_facet $SINGLEMDS lctl pool_list $FSNAME.$1
3175     RC=$?
3176     [[ $RC -ne 0 ]] && return $RC
3177
3178     destroy_pool_int $FSNAME.$1
3179     RC=$?
3180     [[ $RC -ne 0 ]] && return $RC
3181
3182     wait_update $HOSTNAME "lctl get_param -n lov.$FSNAME-*.pools.$1 \
3183       2>/dev/null || echo foo" "foo" && return 0
3184 }
3185
3186 gather_logs () {
3187     local list=$1
3188
3189     local ts=$(date +%s)
3190
3191     # bug 20237, comment 11
3192     # It would also be useful to provide the option
3193     # of writing the file to an NFS directory so it doesn't need to be copied.
3194     local tmp=$TMP
3195     local docp=true
3196     [ -d "$SHARED_DIR_LOGS" ] && tmp=$SHARED_DIR_LOGS && docp=false
3197
3198     # dump lustre logs, dmesg
3199     do_nodes $list "log=$tmp/\\\$(hostname)-debug-$ts.log ;
3200 lctl dk \\\$log >/dev/null;
3201 log=$tmp/\\\$(hostname)-dmesg-$ts.log;
3202 dmesg > \\\$log; "
3203
3204     # FIXME: does it make sense to collect the logs for $ts only, but all
3205     # TESTSUITE logs?
3206     # rsync $TMP/*${TESTSUITE}* to gather the logs dumped by error fn
3207     local logs=$TMP/'*'${TESTSUITE}'*'
3208     if $docp; then
3209         logs=$logs' '$tmp/'*'$ts'*'
3210     fi
3211     for node in ${list//,/ }; do
3212         rsync -az $node:"$logs" $TMP 
3213     done
3214
3215     local archive=$TMP/${TESTSUITE}-$ts.tar.bz2
3216     tar -jcf $archive $tmp/*$ts* $TMP/*${TESTSUITE}*
3217
3218     echo $archive
3219 }
3220
3221 cleanup_logs () {
3222     local list=${1:-$(comma_list $(nodes_list))}
3223
3224     [ -n ${TESTSUITE} ] && do_nodes $list "rm -f $TMP/*${TESTSUITE}*" || true
3225 }
3226
3227 do_ls () {
3228     local mntpt_root=$1
3229     local num_mntpts=$2
3230     local dir=$3
3231     local i
3232     local cmd
3233     local pids
3234     local rc=0
3235
3236     for i in $(seq 0 $num_mntpts); do
3237         cmd="ls -laf ${mntpt_root}$i/$dir"
3238         echo + $cmd;
3239         $cmd > /dev/null &
3240         pids="$pids $!"
3241     done
3242     echo pids=$pids
3243     for pid in $pids; do
3244         wait $pid || rc=$?
3245     done
3246
3247     return $rc
3248 }
3249