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