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