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