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