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