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