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