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