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