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