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