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