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