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