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