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