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