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