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