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