Whamcloud - gitweb
LU-3909 tests: sanity test 129 fix
[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         PREV_RESULT=$(do_node $node "$TEST")
1966         while [ true ]; do
1967                 RESULT=$(do_node $node "$TEST")
1968                 if [[ "$RESULT" == "$FINAL" ]]; then
1969                         [[ -z "$RESULT" || $WAIT -le $sleep ]] ||
1970                                 echo "Updated after ${WAIT}s: wanted '$FINAL'"\
1971                                      "got '$RESULT'"
1972                         return 0
1973                 fi
1974                 if [[ $verbose && "$RESULT" != "$PREV_RESULT" ]]; then
1975                         echo "Changed after ${WAIT}s: from '$PREV_RESULT'"\
1976                              "to '$RESULT'"
1977                         PREV_RESULT=$RESULT
1978                 fi
1979                 [[ $WAIT -ge $MAX ]] && break
1980                 [[ $((WAIT % print)) -eq 0 ]] &&
1981                         echo "Waiting $((MAX - WAIT)) secs for update"
1982                 WAIT=$((WAIT + sleep))
1983                 sleep $sleep
1984         done
1985         echo "Update not seen after ${MAX}s: wanted '$FINAL' got '$RESULT'"
1986         return 3
1987 }
1988
1989 wait_update_facet() {
1990         local facet=$1
1991         shift
1992         wait_update $(facet_active_host $facet) "$@"
1993 }
1994
1995 sync_all_data() {
1996         do_nodes $(comma_list $(mdts_nodes)) \
1997             "lctl set_param -n osd*.*MDT*.force_sync 1"
1998         do_nodes $(comma_list $(osts_nodes)) \
1999             "lctl set_param -n osd*.*OS*.force_sync 1" 2>&1 |
2000                 grep -v 'Found no match'
2001 }
2002
2003 wait_delete_completed_mds() {
2004         local MAX_WAIT=${1:-20}
2005         local mds2sync=""
2006         local stime=`date +%s`
2007         local etime
2008         local node
2009         local changes
2010
2011         # find MDS with pending deletions
2012         for node in $(mdts_nodes); do
2013                 changes=$(do_node $node "lctl get_param -n osc.*MDT*.sync_*" \
2014                         2>/dev/null | calc_sum)
2015                 if [ -z "$changes" ] || [ $changes -eq 0 ]; then
2016                         continue
2017                 fi
2018                 mds2sync="$mds2sync $node"
2019         done
2020         if [ "$mds2sync" == "" ]; then
2021                 return
2022         fi
2023         mds2sync=$(comma_list $mds2sync)
2024
2025         # sync MDS transactions
2026         do_nodes $mds2sync "lctl set_param -n osd*.*MD*.force_sync 1"
2027
2028         # wait till all changes are sent and commmitted by OSTs
2029         # for ldiskfs space is released upon execution, but DMU
2030         # do this upon commit
2031
2032         local WAIT=0
2033         while [ "$WAIT" -ne "$MAX_WAIT" ]; do
2034                 changes=$(do_nodes $mds2sync "lctl get_param -n osc.*MDT*.sync_*" \
2035                         | calc_sum)
2036                 #echo "$node: $changes changes on all"
2037                 if [ "$changes" -eq "0" ]; then
2038                         etime=`date +%s`
2039                         #echo "delete took $((etime - stime)) seconds"
2040                         return
2041                 fi
2042                 sleep 1
2043                 WAIT=$(( WAIT + 1))
2044         done
2045
2046         etime=`date +%s`
2047         echo "Delete is not completed in $((etime - stime)) seconds"
2048         do_nodes $mds2sync "lctl get_param osc.*MDT*.sync_*"
2049 }
2050
2051 wait_for_host() {
2052     local hostlist=$1
2053
2054     # we can use "for" here because we are waiting the slowest
2055     for host in ${hostlist//,/ }; do
2056         check_network "$host" 900
2057     done
2058     while ! do_nodes $hostlist hostname  > /dev/null; do sleep 5; done
2059 }
2060
2061 wait_for_facet() {
2062     local facetlist=$1
2063     local hostlist
2064
2065     for facet in ${facetlist//,/ }; do
2066         hostlist=$(expand_list $hostlist $(facet_active_host $facet))
2067     done
2068     wait_for_host $hostlist
2069 }
2070
2071 _wait_recovery_complete () {
2072     local param=$1
2073
2074     # Use default policy if $2 is not passed by caller.
2075     local MAX=${2:-$(max_recovery_time)}
2076
2077     local WAIT=0
2078     local STATUS=
2079
2080     while [ $WAIT -lt $MAX ]; do
2081         STATUS=$(lctl get_param -n $param | grep status)
2082         echo $param $STATUS
2083         [[ $STATUS = "status: COMPLETE" || $STATUS = "status: INACTIVE" ]] && return 0
2084         sleep 5
2085         WAIT=$((WAIT + 5))
2086         echo "Waiting $((MAX - WAIT)) secs for $param recovery done. $STATUS"
2087     done
2088     echo "$param recovery not done in $MAX sec. $STATUS"
2089     return 1
2090 }
2091
2092 wait_recovery_complete () {
2093     local facet=$1
2094
2095     # with an assumption that at_max is the same on all nodes
2096     local MAX=${2:-$(max_recovery_time)}
2097
2098     local facets=$facet
2099     if [ "$FAILURE_MODE" = HARD ]; then
2100         facets=$(facets_on_host $(facet_active_host $facet))
2101     fi
2102     echo affected facets: $facets
2103
2104         # we can use "for" here because we are waiting the slowest
2105         for facet in ${facets//,/ }; do
2106                 local var_svc=${facet}_svc
2107                 local param="*.${!var_svc}.recovery_status"
2108
2109                 local host=$(facet_active_host $facet)
2110                 do_rpc_nodes "$host" _wait_recovery_complete $param $MAX
2111         done
2112 }
2113
2114 wait_mds_ost_sync () {
2115         # just because recovery is done doesn't mean we've finished
2116         # orphan cleanup. Wait for llogs to get synchronized.
2117         echo "Waiting for orphan cleanup..."
2118         # MAX value includes time needed for MDS-OST reconnection
2119         local MAX=$(( TIMEOUT * 2 ))
2120         local WAIT_TIMEOUT=${1:-$MAX}
2121         local WAIT=0
2122         local new_wait=true
2123         local list=$(comma_list $(mdts_nodes))
2124         local cmd="$LCTL get_param -n osp.*osc*.old_sync_processed"
2125         if ! do_facet $SINGLEMDS \
2126                 "$LCTL list_param osp.*osc*.old_sync_processed 2> /dev/null"
2127         then
2128                 # old way, use mds_sync
2129                 new_wait=false
2130                 list=$(comma_list $(osts_nodes))
2131                 cmd="$LCTL get_param -n obdfilter.*.mds_sync"
2132         fi
2133
2134         echo "wait $WAIT_TIMEOUT secs maximumly for $list mds-ost sync done."
2135         while [ $WAIT -lt $WAIT_TIMEOUT ]; do
2136                 local -a sync=($(do_nodes $list "$cmd"))
2137                 local con=1
2138                 local i
2139                 for ((i=0; i<${#sync[@]}; i++)); do
2140                         if $new_wait; then
2141                                 [ ${sync[$i]} -eq 1 ] && continue
2142                         else
2143                                 [ ${sync[$i]} -eq 0 ] && continue
2144                         fi
2145                         # there is a not finished MDS-OST synchronization
2146                         con=0
2147                         break;
2148                 done
2149                 sleep 2 # increase waiting time and cover statfs cache
2150                 [ ${con} -eq 1 ] && return 0
2151                 echo "Waiting $WAIT secs for $list $i mds-ost sync done."
2152                 WAIT=$((WAIT + 2))
2153         done
2154
2155         # show which nodes are not finished.
2156         do_nodes $list "$cmd"
2157         echo "$facet recovery node $i not done in $WAIT_TIMEOUT sec. $STATUS"
2158         return 1
2159 }
2160
2161 wait_destroy_complete () {
2162         echo "Waiting for local destroys to complete"
2163         # MAX value shouldn't be big as this mean server responsiveness
2164         # never increase this just to make test pass but investigate
2165         # why it takes so long time
2166         local MAX=5
2167         local WAIT=0
2168         while [ $WAIT -lt $MAX ]; do
2169                 local -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))
2170                 local con=1
2171                 local i
2172
2173                 for ((i=0; i<${#RPCs[@]}; i++)); do
2174                         [ ${RPCs[$i]} -eq 0 ] && continue
2175                         # there are still some destroy RPCs in flight
2176                         con=0
2177                         break;
2178                 done
2179                 sleep 1
2180                 [ ${con} -eq 1 ] && return 0 # done waiting
2181                 echo "Waiting ${WAIT}s for local destroys to complete"
2182                 WAIT=$((WAIT + 1))
2183         done
2184         echo "Local destroys weren't done in $MAX sec."
2185         return 1
2186 }
2187
2188 wait_delete_completed() {
2189         wait_delete_completed_mds $1 || return $?
2190         wait_destroy_complete
2191 }
2192
2193 wait_exit_ST () {
2194     local facet=$1
2195
2196     local WAIT=0
2197     local INTERVAL=1
2198     local running
2199     # conf-sanity 31 takes a long time cleanup
2200     while [ $WAIT -lt 300 ]; do
2201         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
2202         [ -z "${running}" ] && return 0
2203         echo "waited $WAIT for${running}"
2204         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
2205         sleep $INTERVAL
2206         WAIT=$((WAIT + INTERVAL))
2207     done
2208     echo "service didn't stop after $WAIT seconds.  Still running:"
2209     echo ${running}
2210     return 1
2211 }
2212
2213 wait_remote_prog () {
2214    local prog=$1
2215    local WAIT=0
2216    local INTERVAL=5
2217    local rc=0
2218
2219    [ "$PDSH" = "no_dsh" ] && return 0
2220
2221    while [ $WAIT -lt $2 ]; do
2222         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
2223         [ -z "${running}" ] && return 0 || true
2224         echo "waited $WAIT for: "
2225         echo "$running"
2226         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
2227         sleep $INTERVAL
2228         WAIT=$((WAIT + INTERVAL))
2229     done
2230     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
2231     [ -z "$pids" ] && return 0
2232     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
2233     # FIXME: not portable
2234     for pid in $pids; do
2235         cat /proc/${pid}/status || true
2236         cat /proc/${pid}/wchan || true
2237         echo "Killing $pid"
2238         kill -9 $pid || true
2239         sleep 1
2240         ps -P $pid && rc=1
2241     done
2242
2243     return $rc
2244 }
2245
2246 clients_up() {
2247     # not every config has many clients
2248     sleep 1
2249     if [ ! -z "$CLIENTS" ]; then
2250         $PDSH $CLIENTS "stat -f $MOUNT" > /dev/null
2251     else
2252         stat -f $MOUNT > /dev/null
2253     fi
2254 }
2255
2256 client_up() {
2257     local client=$1
2258     # usually checked on particular client or locally
2259     sleep 1
2260     if [ ! -z "$client" ]; then
2261         $PDSH $client "stat -f $MOUNT" > /dev/null
2262     else
2263         stat -f $MOUNT > /dev/null
2264     fi
2265 }
2266
2267 client_evicted() {
2268     ! client_up $1
2269 }
2270
2271 client_reconnect() {
2272     uname -n >> $MOUNT/recon
2273     if [ -z "$CLIENTS" ]; then
2274         df $MOUNT; uname -n >> $MOUNT/recon
2275     else
2276         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
2277     fi
2278     echo Connected clients:
2279     cat $MOUNT/recon
2280     ls -l $MOUNT/recon > /dev/null
2281     rm $MOUNT/recon
2282 }
2283
2284 affected_facets () {
2285     local facet=$1
2286
2287     local host=$(facet_active_host $facet)
2288     local affected=$facet
2289
2290     if [ "$FAILURE_MODE" = HARD ]; then
2291         affected=$(facets_up_on_host $host)
2292     fi
2293     echo $affected
2294 }
2295
2296 facet_failover() {
2297         local facets=$1
2298         local sleep_time=$2
2299         local -a affecteds
2300         local facet
2301         local total=0
2302         local index=0
2303         local skip
2304
2305         #Because it will only get up facets, we need get affected
2306         #facets before shutdown
2307         #For HARD Failure mode, it needs make sure facets on the same
2308         #HOST will only be shutdown and reboot once
2309         for facet in ${facets//,/ }; do
2310                 local affected_facet
2311                 skip=0
2312                 #check whether facet has been included in other affected facets
2313                 for ((index=0; index<$total; index++)); do
2314                         [[ *,$facet,* == ,${affecteds[index]}, ]] && skip=1
2315                 done
2316
2317                 if [ $skip -eq 0 ]; then
2318                         affecteds[$total]=$(affected_facets $facet)
2319                         total=$((total+1))
2320                 fi
2321         done
2322
2323         for ((index=0; index<$total; index++)); do
2324                 facet=$(echo ${affecteds[index]} | tr -s " " | cut -d"," -f 1)
2325                 local host=$(facet_active_host $facet)
2326                 echo "Failing ${affecteds[index]} on $host"
2327                 shutdown_facet $facet
2328         done
2329
2330         for ((index=0; index<$total; index++)); do
2331                 facet=$(echo ${affecteds[index]} | tr -s " " | cut -d"," -f 1)
2332                 echo reboot facets: ${affecteds[index]}
2333
2334                 reboot_facet $facet
2335
2336                 change_active ${affecteds[index]}
2337
2338                 wait_for_facet ${affecteds[index]}
2339                 # start mgs first if it is affected
2340                 if ! combined_mgs_mds &&
2341                         list_member ${affecteds[index]} mgs; then
2342                         mount_facet mgs || error "Restart of mgs failed"
2343                 fi
2344                 # FIXME; has to be changed to mount all facets concurrently
2345                 affected=$(exclude_items_from_list ${affecteds[index]} mgs)
2346                 echo mount facets: ${affecteds[index]}
2347                 mount_facets ${affecteds[index]}
2348         done
2349 }
2350
2351 obd_name() {
2352     local facet=$1
2353 }
2354
2355 replay_barrier() {
2356         local facet=$1
2357         do_facet $facet "sync; sync; sync"
2358         df $MOUNT
2359
2360         # make sure there will be no seq change
2361         local clients=${CLIENTS:-$HOSTNAME}
2362         local f=fsa-\\\$\(hostname\)
2363         do_nodes $clients "mcreate $MOUNT/$f; rm $MOUNT/$f"
2364         do_nodes $clients "if [ -d $MOUNT2 ]; then mcreate $MOUNT2/$f; rm $MOUNT2/$f; fi"
2365
2366         local svc=${facet}_svc
2367         do_facet $facet $LCTL --device ${!svc} notransno
2368         #
2369         # If a ZFS OSD is made read-only here, its pool is "freezed". This
2370         # in-memory state has to be cleared by either rebooting the host or
2371         # exporting and reimporting the pool.
2372         #
2373         # Although the uberblocks are not updated when a pool is freezed,
2374         # transactions are still written to the disks. Modified blocks may be
2375         # cached in memory when tests try reading them back. The
2376         # export-and-reimport process also evicts any cached pool data from
2377         # memory to provide the correct "data loss" semantics.
2378         #
2379         # In the test framework, the exporting and importing operations are
2380         # handled by stop() and mount_facet() separately, which are used
2381         # inside fail() and fail_abort().
2382         #
2383         do_facet $facet $LCTL --device ${!svc} readonly
2384         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
2385         $LCTL mark "local REPLAY BARRIER on ${!svc}"
2386 }
2387
2388 replay_barrier_nodf() {
2389         local facet=$1    echo running=${running}
2390         do_facet $facet "sync; sync; sync"
2391         local svc=${facet}_svc
2392         echo Replay barrier on ${!svc}
2393         do_facet $facet $LCTL --device ${!svc} notransno
2394         do_facet $facet $LCTL --device ${!svc} readonly
2395         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
2396         $LCTL mark "local REPLAY BARRIER on ${!svc}"
2397 }
2398
2399 replay_barrier_nosync() {
2400         local facet=$1    echo running=${running}
2401         local svc=${facet}_svc
2402         echo Replay barrier on ${!svc}
2403         do_facet $facet $LCTL --device ${!svc} notransno
2404         do_facet $facet $LCTL --device ${!svc} readonly
2405         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
2406         $LCTL mark "local REPLAY BARRIER on ${!svc}"
2407 }
2408
2409 #
2410 # Get Lustre client uuid for a given Lustre mount point.
2411 #
2412 get_client_uuid() {
2413         local mntpnt=${1:-$MOUNT}
2414
2415         local name=$($LFS getname $mntpnt | cut -d' ' -f1)
2416         local uuid=$($LCTL get_param -n llite.$name.uuid)
2417
2418         echo -n $uuid
2419 }
2420
2421 mds_evict_client() {
2422         local mntpnt=${1:-$MOUNT}
2423         local uuid=$(get_client_uuid $mntpnt)
2424
2425         do_facet $SINGLEMDS \
2426                 "$LCTL set_param -n mdt.${mds1_svc}.evict_client $uuid"
2427 }
2428
2429 ost_evict_client() {
2430         local mntpnt=${1:-$MOUNT}
2431         local uuid=$(get_client_uuid $mntpnt)
2432
2433         do_facet ost1 \
2434                 "$LCTL set_param -n obdfilter.${ost1_svc}.evict_client $uuid"
2435 }
2436
2437 fail() {
2438         local facets=$1
2439         local clients=${CLIENTS:-$HOSTNAME}
2440
2441         facet_failover $* || error "failover: $?"
2442         wait_clients_import_state "$clients" "$facets" FULL
2443         clients_up || error "post-failover df: $?"
2444 }
2445
2446 fail_nodf() {
2447         local facet=$1
2448         facet_failover $facet
2449 }
2450
2451 fail_abort() {
2452         local facet=$1
2453         stop $facet
2454         change_active $facet
2455         wait_for_facet $facet
2456         mount_facet $facet -o abort_recovery
2457         clients_up || echo "first df failed: $?"
2458         clients_up || error "post-failover df: $?"
2459 }
2460
2461 do_lmc() {
2462     echo There is no lmc.  This is mountconf, baby.
2463     exit 1
2464 }
2465
2466 host_nids_address() {
2467     local nodes=$1
2468     local kind=$2
2469
2470     if [ -n "$kind" ]; then
2471         nids=$(do_nodes $nodes "$LCTL list_nids | grep $kind | cut -f 1 -d '@'")
2472     else
2473         nids=$(do_nodes $nodes "$LCTL list_nids all | cut -f 1 -d '@'")
2474     fi
2475     echo $nids
2476 }
2477
2478 h2name_or_ip() {
2479         if [ "$1" = "'*'" ]; then echo \'*\'; else
2480                 echo $1"@$2"
2481         fi
2482 }
2483
2484 h2ptl() {
2485         if [ "$1" = "'*'" ]; then echo \'*\'; else
2486                 ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | \
2487                                                         awk '{print $1}'`
2488                 if [ -z "$ID" ]; then
2489                         echo "Could not get a ptl id for $1..."
2490                         exit 1
2491                 fi
2492                 echo $ID"@ptl"
2493         fi
2494 }
2495 declare -fx h2ptl
2496
2497 h2tcp() {
2498         h2name_or_ip "$1" "tcp"
2499 }
2500 declare -fx h2tcp
2501
2502 h2elan() {
2503         if [ "$1" = "'*'" ]; then echo \'*\'; else
2504                 if type __h2elan >/dev/null 2>&1; then
2505                         ID=$(__h2elan $1)
2506                 else
2507                         ID=`echo $1 | sed 's/[^0-9]*//g'`
2508                 fi
2509                 echo $ID"@elan"
2510         fi
2511 }
2512 declare -fx h2elan
2513
2514 h2o2ib() {
2515         h2name_or_ip "$1" "o2ib"
2516 }
2517 declare -fx h2o2ib
2518
2519 # This enables variables in cfg/"setup".sh files to support the pdsh HOSTLIST
2520 # expressions format. As a bonus we can then just pass in those variables
2521 # to pdsh. What this function does is take a HOSTLIST type string and
2522 # expand it into a space deliminated list for us.
2523 hostlist_expand() {
2524     local hostlist=$1
2525     local offset=$2
2526     local myList
2527     local item
2528     local list
2529
2530     [ -z "$hostlist" ] && return
2531
2532     # Translate the case of [..],..,[..] to [..] .. [..]
2533     list="${hostlist/],/] }"
2534     front=${list%%[*}
2535     [[ "$front" == *,* ]] && {
2536         new="${list%,*} "
2537         old="${list%,*},"
2538         list=${list/${old}/${new}}
2539     }
2540
2541     for item in $list; do
2542         # Test if we have any []'s at all
2543         if [ "$item" != "${item/\[/}" ]; then {
2544             # Expand the [*] into list
2545             name=${item%%[*}
2546             back=${item#*]}
2547
2548             if [ "$name" != "$item" ]; then
2549                 group=${item#$name[*}
2550                 group=${group%%]*}
2551
2552                 for range in ${group//,/ }; do
2553                     begin=${range%-*}
2554                     end=${range#*-}
2555
2556                     # Number of leading zeros
2557                     padlen=${#begin}
2558                     padlen2=${#end}
2559                     end=$(echo $end | sed 's/0*//')
2560                     [[ -z "$end" ]] && end=0
2561                     [[ $padlen2 -gt $padlen ]] && {
2562                         [[ $padlen2 -eq ${#end} ]] && padlen2=0
2563                         padlen=$padlen2
2564                     }
2565                     begin=$(echo $begin | sed 's/0*//')
2566                     [ -z $begin ] && begin=0
2567
2568                     for num in $(seq -f "%0${padlen}g" $begin $end); do
2569                         value="${name#*,}${num}${back}"
2570                         [ "$value" != "${value/\[/}" ] && {
2571                             value=$(hostlist_expand "$value")
2572                         }
2573                         myList="$myList $value"
2574                     done
2575                 done
2576             fi
2577         } else {
2578             myList="$myList $item"
2579         } fi
2580     done
2581     myList=${myList//,/ }
2582     myList=${myList:1} # Remove first character which is a space
2583
2584     # Filter any duplicates without sorting
2585     list="$myList "
2586     myList="${list%% *}"
2587
2588     while [[ "$list" != ${myList##* } ]]; do
2589         list=${list//${list%% *} /}
2590         myList="$myList ${list%% *}"
2591     done
2592     myList="${myList%* }";
2593
2594     # We can select an object at a offset in the list
2595     [ $# -eq 2 ] && {
2596         cnt=0
2597         for item in $myList; do
2598             let cnt=cnt+1
2599             [ $cnt -eq $offset ] && {
2600                 myList=$item
2601             }
2602         done
2603         [ $(get_node_count $myList) -ne 1 ] && myList=""
2604     }
2605     echo $myList
2606 }
2607
2608 facet_host() {
2609         local facet=$1
2610         local varname
2611
2612         [ "$facet" == client ] && echo -n $HOSTNAME && return
2613         varname=${facet}_HOST
2614         if [ -z "${!varname}" ]; then
2615                 if [ "${facet:0:3}" == "ost" ]; then
2616                         eval export ${facet}_HOST=${ost_HOST}
2617                 elif [ "${facet:0:3}" == "mdt" -o \
2618                         "${facet:0:3}" == "mds" -o \
2619                         "${facet:0:3}" == "mgs" ]; then
2620                         eval export ${facet}_HOST=${mds_HOST}
2621                 fi
2622         fi
2623         echo -n ${!varname}
2624 }
2625
2626 facet_failover_host() {
2627         local facet=$1
2628         local varname
2629
2630         var=${facet}failover_HOST
2631         if [ -n "${!var}" ]; then
2632                 echo ${!var}
2633                 return
2634         fi
2635
2636         if [ "${facet:0:3}" == "mdt" -o "${facet:0:3}" == "mds" -o \
2637              "${facet:0:3}" == "mgs" ]; then
2638
2639                 eval export ${facet}failover_host=${mds_HOST}
2640                 echo ${mds_HOST}
2641                 return
2642         fi
2643
2644         if [[ $facet == ost* ]]; then
2645                 eval export ${facet}failover_host=${ost_HOST}
2646                 echo ${ost_HOST}
2647                 return
2648         fi
2649 }
2650
2651 facet_active() {
2652     local facet=$1
2653     local activevar=${facet}active
2654
2655     if [ -f $TMP/${facet}active ] ; then
2656         source $TMP/${facet}active
2657     fi
2658
2659     active=${!activevar}
2660     if [ -z "$active" ] ; then
2661         echo -n ${facet}
2662     else
2663         echo -n ${active}
2664     fi
2665 }
2666
2667 facet_active_host() {
2668     local facet=$1
2669     local active=`facet_active $facet`
2670     if [ "$facet" == client ]; then
2671         echo $HOSTNAME
2672     else
2673         echo `facet_host $active`
2674     fi
2675 }
2676
2677 # Get the passive failover partner host of facet.
2678 facet_passive_host() {
2679         local facet=$1
2680         [[ $facet = client ]] && return
2681
2682         local host=${facet}_HOST
2683         local failover_host=${facet}failover_HOST
2684         local active_host=$(facet_active_host $facet)
2685
2686         [[ -z ${!failover_host} || ${!failover_host} = ${!host} ]] && return
2687
2688         if [[ $active_host = ${!host} ]]; then
2689                 echo -n ${!failover_host}
2690         else
2691                 echo -n ${!host}
2692         fi
2693 }
2694
2695 change_active() {
2696     local facetlist=$1
2697     local facet
2698
2699     facetlist=$(exclude_items_from_list $facetlist mgs)
2700
2701     for facet in ${facetlist//,/ }; do
2702     local failover=${facet}failover
2703     local host=`facet_host $failover`
2704     [ -z "$host" ] && return
2705
2706     local curactive=`facet_active $facet`
2707     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
2708         eval export ${facet}active=$facet
2709     else
2710         eval export ${facet}active=$failover
2711     fi
2712     # save the active host for this facet
2713     local activevar=${facet}active
2714     echo "$activevar=${!activevar}" > $TMP/$activevar
2715     [[ $facet = mds1 ]] && combined_mgs_mds && \
2716         echo "mgsactive=${!activevar}" > $TMP/mgsactive
2717     local TO=`facet_active_host $facet`
2718     echo "Failover $facet to $TO"
2719     done
2720 }
2721
2722 do_node() {
2723     local verbose=false
2724     # do not stripe off hostname if verbose, bug 19215
2725     if [ x$1 = x--verbose ]; then
2726         shift
2727         verbose=true
2728     fi
2729
2730     local HOST=$1
2731     shift
2732     local myPDSH=$PDSH
2733     if [ "$HOST" = "$HOSTNAME" ]; then
2734         myPDSH="no_dsh"
2735     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
2736         echo "cannot run remote command on $HOST with $myPDSH"
2737         return 128
2738     fi
2739     if $VERBOSE; then
2740         echo "CMD: $HOST $@" >&2
2741         $myPDSH $HOST "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
2742     fi
2743
2744     if [ "$myPDSH" = "rsh" ]; then
2745 # we need this because rsh does not return exit code of an executed command
2746         local command_status="$TMP/cs"
2747         rsh $HOST ":> $command_status"
2748         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
2749                     cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
2750                     echo command failed >$command_status"
2751         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
2752         return 0
2753     fi
2754
2755     if $verbose ; then
2756         # print HOSTNAME for myPDSH="no_dsh"
2757         if [[ $myPDSH = no_dsh ]]; then
2758             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
2759         else
2760             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
2761         fi
2762     else
2763         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
2764     fi
2765     return ${PIPESTATUS[0]}
2766 }
2767
2768 do_nodev() {
2769     do_node --verbose "$@"
2770 }
2771
2772 single_local_node () {
2773    [ "$1" = "$HOSTNAME" ]
2774 }
2775
2776 # Outputs environment variable assignments that should be passed to remote nodes
2777 get_env_vars() {
2778         local var
2779         local value
2780         local facets=$(get_facets)
2781         local facet
2782
2783         for var in ${!MODOPTS_*}; do
2784                 value=${!var}
2785                 echo -n " ${var}=\"$value\""
2786         done
2787
2788         for facet in ${facets//,/ }; do
2789                 var=${facet}_FSTYPE
2790                 if [ -n "${!var}" ]; then
2791                         echo -n " $var=${!var}"
2792                 fi
2793         done
2794
2795         for var in MGSFSTYPE MDSFSTYPE OSTFSTYPE; do
2796                 if [ -n "${!var}" ]; then
2797                         echo -n " $var=${!var}"
2798                 fi
2799         done
2800
2801         if [ -n "$FSTYPE" ]; then
2802                 echo -n " FSTYPE=$FSTYPE"
2803         fi
2804 }
2805
2806 do_nodes() {
2807     local verbose=false
2808     # do not stripe off hostname if verbose, bug 19215
2809     if [ x$1 = x--verbose ]; then
2810         shift
2811         verbose=true
2812     fi
2813
2814     local rnodes=$1
2815     shift
2816
2817     if single_local_node $rnodes; then
2818         if $verbose; then
2819            do_nodev $rnodes "$@"
2820         else
2821            do_node $rnodes "$@"
2822         fi
2823         return $?
2824     fi
2825
2826     # This is part from do_node
2827     local myPDSH=$PDSH
2828
2829     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
2830         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
2831
2832     export FANOUT=$(get_node_count "${rnodes//,/ }")
2833     if $VERBOSE; then
2834         echo "CMD: $rnodes $@" >&2
2835         $myPDSH $rnodes "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
2836     fi
2837
2838     # do not replace anything from pdsh output if -N is used
2839     # -N     Disable hostname: prefix on lines of output.
2840     if $verbose || [[ $myPDSH = *-N* ]]; then
2841         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")"
2842     else
2843         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")" | sed -re "s/^[^:]*: //g"
2844     fi
2845     return ${PIPESTATUS[0]}
2846 }
2847
2848 do_facet() {
2849     local facet=$1
2850     shift
2851     local HOST=`facet_active_host $facet`
2852     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
2853     do_node $HOST "$@"
2854 }
2855
2856 # Function: do_facet_random_file $FACET $FILE $SIZE
2857 # Creates FILE with random content on the given FACET of given SIZE
2858
2859 do_facet_random_file() {
2860         local facet="$1"
2861         local fpath="$2"
2862         local fsize="$3"
2863         local cmd="dd if=/dev/urandom of='$fpath' bs=$fsize count=1"
2864         do_facet $facet "$cmd 2>/dev/null"
2865 }
2866
2867 do_facet_create_file() {
2868         local facet="$1"
2869         local fpath="$2"
2870         local fsize="$3"
2871         local cmd="dd if=/dev/zero of='$fpath' bs=$fsize count=1"
2872         do_facet $facet "$cmd 2>/dev/null"
2873 }
2874
2875 do_nodesv() {
2876     do_nodes --verbose "$@"
2877 }
2878
2879 add() {
2880         local facet=$1
2881         shift
2882         # make sure its not already running
2883         stop ${facet} -f
2884         rm -f $TMP/${facet}active
2885         [[ $facet = mds1 ]] && combined_mgs_mds && rm -f $TMP/mgsactive
2886         do_facet ${facet} $MKFS $* || return ${PIPESTATUS[0]}
2887
2888         if [[ $(facet_fstype $facet) == zfs ]]; then
2889                 #
2890                 # After formatting a ZFS target, "cachefile=none" property will
2891                 # be set on the ZFS storage pool so that the pool is not
2892                 # automatically imported on system startup. And then the pool
2893                 # will be exported so as to leave the importing and exporting
2894                 # operations handled by mount_facet() and stop() separately.
2895                 #
2896                 refresh_partition_table $facet $(facet_vdevice $facet)
2897                 disable_zpool_cache $facet
2898                 export_zpool $facet
2899         fi
2900 }
2901
2902 # Device formatted as ost
2903 ostdevname() {
2904         local num=$1
2905         local DEVNAME=OSTDEV$num
2906
2907         local fstype=$(facet_fstype ost$num)
2908
2909         case $fstype in
2910                 ldiskfs )
2911                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
2912                         eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
2913                 zfs )
2914                         #try $OSTZFSDEVn - independent of vdev
2915                         DEVNAME=OSTZFSDEV$num
2916                         eval DEVPTR=${!DEVNAME:=${FSNAME}-ost${num}/ost${num}};;
2917                 * )
2918                         error "unknown fstype!";;
2919         esac
2920
2921     echo -n $DEVPTR
2922 }
2923
2924 # Physical device location of data
2925 ostvdevname() {
2926         local num=$1
2927         local DEVNAME
2928         local VDEVPTR
2929
2930         local fstype=$(facet_fstype ost$num)
2931
2932         case $fstype in
2933                 ldiskfs )
2934                         # vdevs are not supported by ldiskfs
2935                         eval VDEVPTR="";;
2936                 zfs )
2937                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE{n}
2938                         # Device formated by zfs
2939                         DEVNAME=OSTDEV$num
2940                         eval VDEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
2941                 * )
2942                         error "unknown fstype!";;
2943         esac
2944
2945         echo -n $VDEVPTR
2946 }
2947
2948 # Logical device formated for lustre
2949 mdsdevname() {
2950         local num=$1
2951         local DEVNAME=MDSDEV$num
2952
2953         local fstype=$(facet_fstype mds$num)
2954
2955         case $fstype in
2956                 ldiskfs )
2957                         #if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
2958                         eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
2959                 zfs )
2960                         # try $MDSZFSDEVn - independent of vdev
2961                         DEVNAME=MDSZFSDEV$num
2962                         eval DEVPTR=${!DEVNAME:=${FSNAME}-mdt${num}/mdt${num}};;
2963                 * )
2964                         error "unknown fstype!";;
2965         esac
2966
2967         echo -n $DEVPTR
2968 }
2969
2970 # Physical location of data
2971 mdsvdevname() {
2972         local VDEVPTR=""
2973         local num=$1
2974         local fstype=$(facet_fstype mds$num)
2975
2976         case $fstype in
2977                 ldiskfs )
2978                         # vdevs are not supported by ldiskfs
2979                         eval VDEVPTR="";;
2980                 zfs )
2981                         # if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
2982                         # Device formated by ZFS
2983                         local DEVNAME=MDSDEV$num
2984                         eval VDEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
2985                 * )
2986                         error "unknown fstype!";;
2987         esac
2988
2989         echo -n $VDEVPTR
2990 }
2991
2992 mgsdevname() {
2993         local DEVPTR
2994         local fstype=$(facet_fstype mgs)
2995
2996         case $fstype in
2997         ldiskfs )
2998                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
2999                    ( [ -z "$MGSDEV" ] || [ $MGSDEV = $(mdsdevname 1) ] ); then
3000                         DEVPTR=$(mdsdevname 1)
3001                 else
3002                         DEVPTR=$MGSDEV
3003                 fi;;
3004         zfs )
3005                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3006                     ( [ -z "$MGSZFSDEV" ] &&
3007                         [ -z "$MGSDEV" -o "$MGSDEV" = $(mdsvdevname 1) ] ); then
3008                         DEVPTR=$(mdsdevname 1)
3009                 else
3010                         DEVPTR=${MGSZFSDEV:-${FSNAME}-mgs/mgs}
3011                 fi;;
3012         * )
3013                 error "unknown fstype!";;
3014         esac
3015
3016         echo -n $DEVPTR
3017 }
3018
3019 mgsvdevname() {
3020         local VDEVPTR=""
3021
3022         local fstype=$(facet_fstype mgs)
3023
3024         case $fstype in
3025         ldiskfs )
3026                 # vdevs are not supported by ldiskfs
3027                 ;;
3028         zfs )
3029                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
3030                    ( [ -z "$MGSDEV" ] &&
3031                        [ -z "$MGSZFSDEV" -o "$MGSZFSDEV" = $(mdsdevname 1) ]); then
3032                         VDEVPTR=$(mdsvdevname 1)
3033                 elif [ -n "$MGSDEV" ]; then
3034                         VDEVPTR=$MGSDEV
3035                 fi;;
3036         * )
3037                 error "unknown fstype!";;
3038         esac
3039
3040         echo -n $VDEVPTR
3041 }
3042
3043 facet_mntpt () {
3044     local facet=$1
3045     [[ $facet = mgs ]] && combined_mgs_mds && facet="mds1"
3046
3047     local var=${facet}_MOUNT
3048     eval mntpt=${!var:-${MOUNT%/*}/$facet}
3049
3050     echo -n $mntpt
3051 }
3052
3053 mount_ldiskfs() {
3054         local facet=$1
3055         local dev=$(facet_device $facet)
3056         local mnt=$(facet_mntpt $facet)
3057         local opts
3058
3059         if ! do_facet $facet test -b $dev; then
3060                 opts="-o loop"
3061         fi
3062         do_facet $facet mount -t ldiskfs $opts $dev $mnt
3063 }
3064
3065 unmount_ldiskfs() {
3066         local facet=$1
3067         local dev=$(facet_device $facet)
3068         local mnt=$(facet_mntpt $facet)
3069
3070         do_facet $facet umount -d $mnt
3071 }
3072
3073 var_name() {
3074         echo -n "$1" | tr -c '[:alnum:]\n' '_'
3075 }
3076
3077 mount_zfs() {
3078         local facet=$1
3079         local ds=$(facet_device $facet)
3080         local mnt=$(facet_mntpt $facet)
3081         local canmnt
3082         local mntpt
3083
3084         import_zpool $facet
3085         canmnt=$(do_facet $facet $ZFS get -H -o value canmount $ds)
3086         mntpt=$(do_facet $facet $ZFS get -H -o value mountpoint $ds)
3087         do_facet $facet $ZFS set canmount=noauto $ds
3088         #
3089         # The "legacy" mount method is used here because "zfs unmount $mnt"
3090         # calls stat(2) on $mnt/../*, which may include $MOUNT.  If certain
3091         # targets are not available at the time, the stat(2) on $MOUNT will
3092         # hang.
3093         #
3094         do_facet $facet $ZFS set mountpoint=legacy $ds
3095         do_facet $facet mount -t zfs $ds $mnt
3096         eval export mz_$(var_name ${facet}_$ds)_canmount=$canmnt
3097         eval export mz_$(var_name ${facet}_$ds)_mountpoint=$mntpt
3098 }
3099
3100 unmount_zfs() {
3101         local facet=$1
3102         local ds=$(facet_device $facet)
3103         local mnt=$(facet_mntpt $facet)
3104         local var_mntpt=mz_$(var_name ${facet}_$ds)_mountpoint
3105         local var_canmnt=mz_$(var_name ${facet}_$ds)_canmount
3106         local mntpt=${!var_mntpt}
3107         local canmnt=${!var_canmnt}
3108
3109         unset $var_mntpt
3110         unset $var_canmnt
3111         do_facet $facet umount $mnt
3112         do_facet $facet $ZFS set mountpoint=$mntpt $ds
3113         do_facet $facet $ZFS set canmount=$canmnt $ds
3114         export_zpool $facet
3115 }
3116
3117 mount_fstype() {
3118         local facet=$1
3119         local fstype=$(facet_fstype $facet)
3120
3121         mount_$fstype $facet
3122 }
3123
3124 unmount_fstype() {
3125         local facet=$1
3126         local fstype=$(facet_fstype $facet)
3127
3128         unmount_$fstype $facet
3129 }
3130
3131 ########
3132 ## MountConf setup
3133
3134 stopall() {
3135     # make sure we are using the primary server, so test-framework will
3136     # be able to clean up properly.
3137     activemds=`facet_active mds1`
3138     if [ $activemds != "mds1" ]; then
3139         fail mds1
3140     fi
3141
3142     local clients=$CLIENTS
3143     [ -z $clients ] && clients=$(hostname)
3144
3145     zconf_umount_clients $clients $MOUNT "$*" || true
3146     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
3147
3148     [ "$CLIENTONLY" ] && return
3149     # The add fn does rm ${facet}active file, this would be enough
3150     # if we use do_facet <facet> only after the facet added, but
3151     # currently we use do_facet mds in local.sh
3152     for num in `seq $MDSCOUNT`; do
3153         stop mds$num -f
3154         rm -f ${TMP}/mds${num}active
3155     done
3156     combined_mgs_mds && rm -f $TMP/mgsactive
3157
3158     for num in `seq $OSTCOUNT`; do
3159         stop ost$num -f
3160         rm -f $TMP/ost${num}active
3161     done
3162
3163     if ! combined_mgs_mds ; then
3164         stop mgs
3165     fi
3166
3167     return 0
3168 }
3169
3170 cleanup_echo_devs () {
3171     local devs=$($LCTL dl | grep echo | awk '{print $4}')
3172
3173     for dev in $devs; do
3174         $LCTL --device $dev cleanup
3175         $LCTL --device $dev detach
3176     done
3177 }
3178
3179 cleanupall() {
3180     nfs_client_mode && return
3181
3182     stopall $*
3183     cleanup_echo_devs
3184
3185     unload_modules
3186     cleanup_gss
3187 }
3188
3189 combined_mgs_mds () {
3190         [[ "$(mdsdevname 1)" = "$(mgsdevname)" ]] &&
3191                 [[ "$(facet_host mds1)" = "$(facet_host mgs)" ]]
3192 }
3193
3194 lower() {
3195         echo -n "$1" | tr '[:upper:]' '[:lower:]'
3196 }
3197
3198 upper() {
3199         echo -n "$1" | tr '[:lower:]' '[:upper:]'
3200 }
3201
3202 mkfs_opts() {
3203         local facet=$1
3204         local dev=$2
3205         local fsname=${3:-"$FSNAME"}
3206         local type=$(facet_type $facet)
3207         local index=$(($(facet_number $facet) - 1))
3208         local fstype=$(facet_fstype $facet)
3209         local host=$(facet_host $facet)
3210         local opts
3211         local fs_mkfs_opts
3212         local var
3213
3214         if [ $type == MGS ] && combined_mgs_mds; then
3215                 return 1
3216         fi
3217
3218         if [ $type == MGS ] || ( [ $type == MDS ] &&
3219                                  [ "$dev" == $(mgsdevname) ] &&
3220                                  [ "$host" == "$(facet_host mgs)" ] ); then
3221                 opts="--mgs"
3222         else
3223                 opts="--mgsnode=$MGSNID"
3224         fi
3225
3226         if [ $type != MGS ]; then
3227                 opts+=" --fsname=$fsname --$(lower ${type/MDS/MDT}) \
3228                         --index=$index"
3229         fi
3230
3231         var=${facet}failover_HOST
3232         if [ -n "${!var}" ] && [ ${!var} != $(facet_host $facet) ]; then
3233                 opts+=" --failnode=$(h2$NETTYPE ${!var})"
3234         fi
3235
3236         opts+=${TIMEOUT:+" --param=sys.timeout=$TIMEOUT"}
3237         opts+=${LDLM_TIMEOUT:+" --param=sys.ldlm_timeout=$LDLM_TIMEOUT"}
3238
3239         if [ $type == MDS ]; then
3240                 opts+=${SECLEVEL:+" --param=mdt.sec_level"}
3241                 opts+=${MDSCAPA:+" --param-mdt.capa=$MDSCAPA"}
3242                 opts+=${STRIPE_BYTES:+" --param=lov.stripesize=$STRIPE_BYTES"}
3243                 opts+=${STRIPES_PER_OBJ:+" --param=lov.stripecount=$STRIPES_PER_OBJ"}
3244                 opts+=${L_GETIDENTITY:+" --param=mdt.identity_upcall=$L_GETIDENTITY"}
3245
3246                 if [ $fstype == ldiskfs ]; then
3247                         fs_mkfs_opts+=${MDSJOURNALSIZE:+" -J size=$MDSJOURNALSIZE"}
3248                         if [ ! -z $EJOURNAL ]; then
3249                                 fs_mkfs_opts+=${MDSJOURNALSIZE:+" device=$EJOURNAL"}
3250                         fi
3251                         fs_mkfs_opts+=${MDSISIZE:+" -i $MDSISIZE"}
3252                 fi
3253         fi
3254
3255         if [ $type == OST ]; then
3256                 opts+=${SECLEVEL:+" --param=ost.sec_level"}
3257                 opts+=${OSSCAPA:+" --param=ost.capa=$OSSCAPA"}
3258
3259                 if [ $fstype == ldiskfs ]; then
3260                         fs_mkfs_opts+=${OSTJOURNALSIZE:+" -J size=$OSTJOURNALSIZE"}
3261                 fi
3262         fi
3263
3264         opts+=" --backfstype=$fstype"
3265
3266         var=${type}SIZE
3267         if [ -n "${!var}" ]; then
3268                 opts+=" --device-size=${!var}"
3269         fi
3270
3271         var=$(upper $fstype)_MKFS_OPTS
3272         fs_mkfs_opts+=${!var:+" ${!var}"}
3273
3274         var=${type}_FS_MKFS_OPTS
3275         fs_mkfs_opts+=${!var:+" ${!var}"}
3276
3277         if [ -n "${fs_mkfs_opts## }" ]; then
3278                 opts+=" --mkfsoptions=\\\"${fs_mkfs_opts## }\\\""
3279         fi
3280
3281         var=${type}OPT
3282         opts+=${!var:+" ${!var}"}
3283
3284         echo -n "$opts"
3285 }
3286
3287 formatall() {
3288         local quiet
3289
3290         if ! $VERBOSE; then
3291                 quiet=yes
3292         fi
3293
3294         stopall
3295         # We need ldiskfs here, may as well load them all
3296         load_modules
3297         [ "$CLIENTONLY" ] && return
3298         echo Formatting mgs, mds, osts
3299         if ! combined_mgs_mds ; then
3300                 echo "Format mgs: $(mgsdevname)"
3301                 add mgs $(mkfs_opts mgs $(mgsdevname)) --reformat \
3302                         $(mgsdevname) $(mgsvdevname) ${quiet:+>/dev/null} ||
3303                         exit 10
3304         fi
3305
3306         for num in $(seq $MDSCOUNT); do
3307                 echo "Format mds$num: $(mdsdevname $num)"
3308                 add mds$num $(mkfs_opts mds$num $(mdsdevname ${num})) \
3309                         --reformat $(mdsdevname $num) $(mdsvdevname $num) \
3310                         ${quiet:+>/dev/null} || exit 10
3311         done
3312
3313         for num in $(seq $OSTCOUNT); do
3314                 echo "Format ost$num: $(ostdevname $num)"
3315                 add ost$num $(mkfs_opts ost$num $(ostdevname ${num})) \
3316                         --reformat $(ostdevname $num) $(ostvdevname ${num}) \
3317                         ${quiet:+>/dev/null} || exit 10
3318         done
3319 }
3320
3321 mount_client() {
3322     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
3323 }
3324
3325 umount_client() {
3326     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
3327 }
3328
3329 # return value:
3330 # 0: success, the old identity set already.
3331 # 1: success, the old identity does not set.
3332 # 2: fail.
3333 switch_identity() {
3334     local num=$1
3335     local switch=$2
3336     local j=`expr $num - 1`
3337     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
3338
3339     if [ -z "$MDT" ]; then
3340         return 2
3341     fi
3342
3343     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
3344
3345     if $switch; then
3346         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
3347     else
3348         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
3349     fi
3350
3351     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush=-1"
3352
3353     if [ $old = "NONE" ]; then
3354         return 1
3355     else
3356         return 0
3357     fi
3358 }
3359
3360 remount_client()
3361 {
3362         zconf_umount `hostname` $1 || error "umount failed"
3363         zconf_mount `hostname` $1 || error "mount failed"
3364 }
3365
3366 writeconf_facet() {
3367         local facet=$1
3368         local dev=$2
3369
3370         stop ${facet} -f
3371         rm -f $TMP/${facet}active
3372         do_facet ${facet} "$TUNEFS --quiet --writeconf $dev" || return 1
3373         return 0
3374 }
3375
3376 writeconf_all () {
3377         local mdt_count=${1:-$MDSCOUNT}
3378         local ost_count=${2:-$OSTCOUNT}
3379         local rc=0
3380
3381         for num in $(seq $mdt_count); do
3382                 DEVNAME=$(mdsdevname $num)
3383                 writeconf_facet mds$num $DEVNAME || rc=$?
3384         done
3385
3386         for num in $(seq $ost_count); do
3387                 DEVNAME=$(ostdevname $num)
3388                 writeconf_facet ost$num $DEVNAME || rc=$?
3389         done
3390         return $rc
3391 }
3392
3393 setupall() {
3394     nfs_client_mode && return
3395
3396     sanity_mount_check ||
3397         error "environments are insane!"
3398
3399     load_modules
3400
3401     if [ -z "$CLIENTONLY" ]; then
3402         echo Setup mgs, mdt, osts
3403         echo $WRITECONF | grep -q "writeconf" && \
3404             writeconf_all
3405         if ! combined_mgs_mds ; then
3406                         start mgs $(mgsdevname) $MGS_MOUNT_OPTS
3407         fi
3408
3409         for num in `seq $MDSCOUNT`; do
3410             DEVNAME=$(mdsdevname $num)
3411             start mds$num $DEVNAME $MDS_MOUNT_OPTS
3412
3413             # We started mds, now we should set failover variables properly.
3414             # Set mds${num}failover_HOST if it is not set (the default failnode).
3415             local varname=mds${num}failover_HOST
3416             if [ -z "${!varname}" ]; then
3417                 eval mds${num}failover_HOST=$(facet_host mds$num)
3418             fi
3419
3420             if [ $IDENTITY_UPCALL != "default" ]; then
3421                 switch_identity $num $IDENTITY_UPCALL
3422             fi
3423         done
3424         for num in `seq $OSTCOUNT`; do
3425             DEVNAME=$(ostdevname $num)
3426             start ost$num $DEVNAME $OST_MOUNT_OPTS
3427
3428             # We started ost$num, now we should set ost${num}failover variable properly.
3429             # Set ost${num}failover_HOST if it is not set (the default failnode).
3430             varname=ost${num}failover_HOST
3431             if [ -z "${!varname}" ]; then
3432                 eval ost${num}failover_HOST=$(facet_host ost${num})
3433             fi
3434
3435         done
3436     fi
3437
3438     init_gss
3439
3440     # wait a while to allow sptlrpc configuration be propogated to targets,
3441     # only needed when mounting new target devices.
3442     if $GSS; then
3443         sleep 10
3444     fi
3445
3446     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
3447     mount_client $MOUNT
3448     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
3449     clients_up
3450
3451     if [ "$MOUNT_2" ]; then
3452         mount_client $MOUNT2
3453         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
3454     fi
3455
3456     init_param_vars
3457
3458     # by remounting mdt before ost, initial connect from mdt to ost might
3459     # timeout because ost is not ready yet. wait some time to its fully
3460     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
3461     # by a context negotiation rpc with $TIMEOUT.
3462     # FIXME better by monitoring import status.
3463     if $GSS; then
3464         set_flavor_all $SEC
3465         sleep $((TIMEOUT + 5))
3466     else
3467         sleep 5
3468     fi
3469 }
3470
3471 mounted_lustre_filesystems() {
3472         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
3473 }
3474
3475 init_facet_vars () {
3476         [ "$CLIENTONLY" ] && return 0
3477         local facet=$1
3478         shift
3479         local device=$1
3480
3481         shift
3482
3483         eval export ${facet}_dev=${device}
3484         eval export ${facet}_opt=\"$@\"
3485
3486         local dev=${facet}_dev
3487
3488         # We need to loop for the label
3489         # in case its not initialized yet.
3490         for wait_time in {0,1,3,5,10}; do
3491
3492                 if [ $wait_time -gt 0 ]; then
3493                         echo "${!dev} not yet initialized,"\
3494                                 "waiting ${wait_time} seconds."
3495                         sleep $wait_time
3496                 fi
3497
3498                 local label=$(devicelabel ${facet} ${!dev})
3499
3500                 # Check to make sure the label does
3501                 # not include ffff at the end of the label.
3502                 # This indicates it has not been initialized yet.
3503
3504                 if [[ $label =~ [f|F]{4}$ ]]; then
3505                         # label is not initialized, unset the result
3506                         # and either try again or fail
3507                         unset label
3508                 else
3509                         break
3510                 fi
3511         done
3512
3513         [ -z "$label" ] && echo no label for ${!dev} && exit 1
3514
3515         eval export ${facet}_svc=${label}
3516
3517         local varname=${facet}failover_HOST
3518         if [ -z "${!varname}" ]; then
3519                 eval export $varname=$(facet_host $facet)
3520         fi
3521
3522         varname=${facet}_HOST
3523         if [ -z "${!varname}" ]; then
3524                 eval export $varname=$(facet_host $facet)
3525         fi
3526
3527         # ${facet}failover_dev is set in cfg file
3528         varname=${facet}failover_dev
3529         if [ -n "${!varname}" ] ; then
3530                 eval export ${facet}failover_dev=${!varname}
3531         else
3532                 eval export ${facet}failover_dev=$device
3533         fi
3534
3535         # get mount point of already mounted device
3536         # is facet_dev is already mounted then use the real
3537         #  mount point of this facet; otherwise use $(facet_mntpt $facet)
3538         # i.e. ${facet}_MOUNT if specified by user or default
3539         local mntpt=$(do_facet ${facet} cat /proc/mounts | \
3540                         awk '"'${!dev}'" == $1 && $3 == "lustre" { print $2 }')
3541         if [ -z $mntpt ]; then
3542                 mntpt=$(facet_mntpt $facet)
3543         fi
3544         eval export ${facet}_MOUNT=$mntpt
3545 }
3546
3547 init_facets_vars () {
3548         local DEVNAME
3549
3550         if ! remote_mds_nodsh; then
3551                 for num in $(seq $MDSCOUNT); do
3552                         DEVNAME=`mdsdevname $num`
3553                         init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
3554                 done
3555         fi
3556
3557         combined_mgs_mds || init_facet_vars mgs $(mgsdevname) $MGS_MOUNT_OPTS
3558
3559         if ! remote_ost_nodsh; then
3560                 for num in $(seq $OSTCOUNT); do
3561                         DEVNAME=$(ostdevname $num)
3562                         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
3563                 done
3564         fi
3565 }
3566
3567 osc_ensure_active () {
3568     local facet=$1
3569     local timeout=$2
3570     local period=0
3571
3572     while [ $period -lt $timeout ]; do
3573         count=$(do_facet $facet "lctl dl | grep ' IN osc ' 2>/dev/null | wc -l")
3574         if [ $count -eq 0 ]; then
3575             break
3576         fi
3577
3578         echo "There are $count OST are inactive, wait $period seconds, and try again"
3579         sleep 3
3580         period=$((period+3))
3581     done
3582
3583     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
3584 }
3585
3586 set_conf_param_and_check() {
3587         local myfacet=$1
3588         local TEST=$2
3589         local PARAM=$3
3590         local ORIG=$(do_facet $myfacet "$TEST")
3591         if [ $# -gt 3 ]; then
3592                 local FINAL=$4
3593         else
3594                 local -i FINAL
3595                 FINAL=$((ORIG + 5))
3596         fi
3597         echo "Setting $PARAM from $ORIG to $FINAL"
3598         do_facet mgs "$LCTL conf_param $PARAM='$FINAL'" ||
3599                 error "conf_param $PARAM failed"
3600
3601         wait_update $(facet_host $myfacet) "$TEST" "$FINAL" ||
3602                 error "check $PARAM failed!"
3603 }
3604
3605 init_param_vars () {
3606         remote_mds_nodsh ||
3607                 TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
3608
3609         log "Using TIMEOUT=$TIMEOUT"
3610
3611         osc_ensure_active $SINGLEMDS $TIMEOUT
3612         osc_ensure_active client $TIMEOUT
3613
3614         if [ -n "$(lctl get_param -n mdc.*.connect_flags|grep jobstats)" ]; then
3615                 local current_jobid_var=$($LCTL get_param -n jobid_var)
3616
3617                 if [ $JOBID_VAR = "existing" ]; then
3618                         echo "keeping jobstats as $current_jobid_var"
3619                 elif [ $current_jobid_var != $JOBID_VAR ]; then
3620                         echo "seting jobstats to $JOBID_VAR"
3621
3622                         set_conf_param_and_check client                 \
3623                                 "$LCTL get_param -n jobid_var"          \
3624                                 "$FSNAME.sys.jobid_var" $JOBID_VAR
3625                 fi
3626         else
3627                 echo "jobstats not supported by server"
3628         fi
3629
3630         if [ $QUOTA_AUTO -ne 0 ]; then
3631                 if [ "$ENABLE_QUOTA" ]; then
3632                         echo "enable quota as required"
3633                         setup_quota $MOUNT || return 2
3634                 else
3635                         echo "disable quota as required"
3636                         # $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
3637                 fi
3638         fi
3639         return 0
3640 }
3641
3642 nfs_client_mode () {
3643     if [ "$NFSCLIENT" ]; then
3644         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
3645         local clients=$CLIENTS
3646         [ -z $clients ] && clients=$(hostname)
3647
3648         # FIXME: remove hostname when 19215 fixed
3649         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
3650         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
3651         if [[ ${#nfsexport[@]} -eq 0 ]]; then
3652                 error_exit NFSCLIENT=$NFSCLIENT mode, but no NFS export found!
3653         fi
3654         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
3655         return
3656     fi
3657     return 1
3658 }
3659
3660 check_config_client () {
3661     local mntpt=$1
3662
3663     local mounted=$(mount | grep " $mntpt ")
3664     if [ "$CLIENTONLY" ]; then
3665         # bug 18021
3666         # CLIENTONLY should not depend on *_HOST settings
3667         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
3668         # in theory someone could create a new,
3669         # client-only config file that assumed lustre was already
3670         # configured and didn't set the MGSNID. If MGSNID is not set,
3671         # then we should use the mgs nid currently being used 
3672         # as the default value. bug 18021
3673         [[ x$MGSNID = x ]] &&
3674             MGSNID=${mgc//MGC/}
3675
3676         if [[ x$mgc != xMGC$MGSNID ]]; then
3677             if [ "$mgs_HOST" ]; then
3678                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
3679 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
3680 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
3681             fi
3682         fi
3683         return 0
3684     fi
3685
3686     local myMGS_host=$mgs_HOST   
3687     if [ "$NETTYPE" = "ptl" ]; then
3688         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
3689     fi
3690
3691     echo Checking config lustre mounted on $mntpt
3692     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
3693     mgshost=$(echo $mgshost | awk -F: '{print $1}')
3694
3695 #    if [ "$mgshost" != "$myMGS_host" ]; then
3696 #            log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
3697 #                   Please use correct config or set mds_HOST correctly!"
3698 #    fi
3699
3700 }
3701
3702 check_config_clients () {
3703         local clients=${CLIENTS:-$HOSTNAME}
3704         local mntpt=$1
3705
3706         nfs_client_mode && return
3707
3708         do_rpc_nodes "$clients" check_config_client $mntpt
3709
3710         sanity_mount_check || error "environments are insane!"
3711 }
3712
3713 check_timeout () {
3714     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
3715     local cltimeout=$(lctl get_param -n timeout)
3716     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
3717         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
3718         return 1
3719     fi
3720 }
3721
3722 is_mounted () {
3723     local mntpt=$1
3724     [ -z $mntpt ] && return 1
3725     local mounted=$(mounted_lustre_filesystems)
3726
3727     echo $mounted' ' | grep -w -q $mntpt' '
3728 }
3729
3730 is_empty_dir() {
3731         [ $(find $1 -maxdepth 1 -print | wc -l) = 1 ] && return 0
3732         return 1
3733 }
3734
3735 # empty lustre filesystem may have empty directories lost+found and .lustre
3736 is_empty_fs() {
3737         # exclude .lustre & lost+found
3738         [ $(find $1 -maxdepth 1 -name lost+found -o -name .lustre -prune -o \
3739                 -print | wc -l) = 1 ] || return 1
3740         [ ! -d $1/lost+found ] || is_empty_dir $1/lost+found || return 1
3741         if [ $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.4.0) ]; then
3742                 # exclude .lustre/fid (LU-2780)
3743                 [ $(find $1/.lustre -maxdepth 1 -name fid -prune -o \
3744                         -print | wc -l) = 1 ] || return 1
3745         else
3746                 [ ! -d $1/.lustre ] || is_empty_dir $1/.lustre || return 1
3747         fi
3748         return 0
3749 }
3750
3751 check_and_setup_lustre() {
3752     nfs_client_mode && return
3753
3754     local MOUNTED=$(mounted_lustre_filesystems)
3755
3756     local do_check=true
3757     # 1.
3758     # both MOUNT and MOUNT2 are not mounted
3759     if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
3760         [ "$REFORMAT" ] && formatall
3761         # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
3762         setupall
3763         is_mounted $MOUNT || error "NAME=$NAME not mounted"
3764         export I_MOUNTED=yes
3765         do_check=false
3766     # 2.
3767     # MOUNT2 is mounted
3768     elif is_mounted $MOUNT2; then
3769             # 3.
3770             # MOUNT2 is mounted, while MOUNT_2 is not set
3771             if ! [ "$MOUNT_2" ]; then
3772                 cleanup_mount $MOUNT2
3773                 export I_UMOUNTED2=yes
3774
3775             # 4.
3776             # MOUNT2 is mounted, MOUNT_2 is set
3777             else
3778                 # FIXME: what to do if check_config failed?
3779                 # i.e. if:
3780                 # 1) remote client has mounted other Lustre fs ?
3781                 # 2) it has insane env ?
3782                 # let's try umount MOUNT2 on all clients and mount it again:
3783                 if ! check_config_clients $MOUNT2; then
3784                     cleanup_mount $MOUNT2
3785                     restore_mount $MOUNT2
3786                     export I_MOUNTED2=yes
3787                 fi
3788             fi 
3789
3790     # 5.
3791     # MOUNT is mounted MOUNT2 is not mounted
3792     elif [ "$MOUNT_2" ]; then
3793         restore_mount $MOUNT2
3794         export I_MOUNTED2=yes
3795     fi
3796
3797     if $do_check; then
3798         # FIXME: what to do if check_config failed?
3799         # i.e. if:
3800         # 1) remote client has mounted other Lustre fs?
3801         # 2) lustre is mounted on remote_clients atall ?
3802         check_config_clients $MOUNT
3803         init_facets_vars
3804         init_param_vars
3805
3806         set_default_debug_nodes $(comma_list $(nodes_list))
3807     fi
3808
3809         if [ $(lower $OSD_TRACK_DECLARES_LBUG) == 'yes' ] ; then
3810                 local facets=""
3811                 [ "$(facet_fstype ost1)" = "ldiskfs" ] &&
3812                         facets="$(get_facets OST)"
3813                 [ "$(facet_fstype mds1)" = "ldiskfs" ] &&
3814                         facets="$facets,$(get_facets MDS)"
3815                 [ "$(facet_fstype mgs)" = "ldiskfs" ] &&
3816                         facets="$facets,mgs"
3817                 local nodes="$(facets_hosts ${facets})"
3818                 if [ -n "$nodes" ] ; then
3819                         do_nodes $nodes "$LCTL set_param \
3820                                  osd-ldiskfs.track_declares_assert=1 || true"
3821                 fi
3822         fi
3823
3824         init_gss
3825         if $GSS; then
3826                 set_flavor_all $SEC
3827         fi
3828
3829         if [ "$ONLY" == "setup" ]; then
3830                 exit 0
3831         fi
3832 }
3833
3834 restore_mount () {
3835    local clients=${CLIENTS:-$HOSTNAME}
3836    local mntpt=$1
3837
3838    zconf_mount_clients $clients $mntpt
3839 }
3840
3841 cleanup_mount () {
3842     local clients=${CLIENTS:-$HOSTNAME}
3843     local mntpt=$1
3844
3845     zconf_umount_clients $clients $mntpt    
3846 }
3847
3848 cleanup_and_setup_lustre() {
3849     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
3850         lctl set_param debug=0 || true
3851         cleanupall
3852         if [ "$ONLY" == "cleanup" ]; then
3853             exit 0
3854         fi
3855     fi
3856     check_and_setup_lustre
3857 }
3858
3859 # Get all of the server target devices from a given server node and type.
3860 get_mnt_devs() {
3861         local node=$1
3862         local type=$2
3863         local devs
3864         local dev
3865
3866         if [ "$type" == ost ]; then
3867                 devs=$(get_osd_param $node "" mntdev)
3868         else
3869                 devs=$(do_node $node \
3870                        "lctl get_param -n osd-*.$FSNAME-M*.mntdev")
3871         fi
3872         for dev in $devs; do
3873                 case $dev in
3874                 *loop*) do_node $node "losetup $dev" | \
3875                                 sed -e "s/.*(//" -e "s/).*//" ;;
3876                 *) echo $dev ;;
3877                 esac
3878         done
3879 }
3880
3881 # Get all of the server target devices.
3882 get_svr_devs() {
3883     local i
3884
3885     # MDT device
3886     MDTDEV=$(get_mnt_devs $(mdts_nodes) mdt)
3887
3888     # OST devices
3889     i=0
3890     for node in $(osts_nodes); do
3891         OSTDEVS[i]=$(get_mnt_devs $node ost)
3892         i=$((i + 1))
3893     done
3894 }
3895
3896 # Run e2fsck on MDT or OST device.
3897 run_e2fsck() {
3898     local node=$1
3899     local target_dev=$2
3900     local extra_opts=$3
3901
3902     df > /dev/null      # update statfs data on disk
3903     local cmd="$E2FSCK -d -v -t -t -f $extra_opts $target_dev"
3904     echo $cmd
3905     local rc=0
3906     do_node $node $cmd || rc=$?
3907     [ $rc -le $FSCK_MAX_ERR ] || \
3908         error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
3909     return 0
3910 }
3911
3912 #
3913 # Run resize2fs on MDT or OST device.
3914 #
3915 run_resize2fs() {
3916         local facet=$1
3917         local device=$2
3918         local size=$3
3919         shift 3
3920         local opts="$@"
3921
3922         do_facet $facet "$RESIZE2FS $opts $device $size"
3923 }
3924
3925 # verify a directory is shared among nodes.
3926 check_shared_dir() {
3927         local dir=$1
3928         local list=${2:-$(comma_list $(nodes_list))}
3929
3930         [ -z "$dir" ] && return 1
3931         do_rpc_nodes "$list" check_logdir $dir
3932         check_write_access $dir "$list" || return 1
3933         return 0
3934 }
3935
3936 # Run e2fsck on MDT and OST(s) to generate databases used for lfsck.
3937 generate_db() {
3938     local i
3939     local ostidx
3940     local dev
3941
3942         [[ $(lustre_version_code $SINGLEMDS) -ne $(version_code 2.2.0) ]] ||
3943                 { skip "Lustre 2.2.0 lacks the patch for LU-1255"; exit 0; }
3944
3945     check_shared_dir $SHARED_DIRECTORY ||
3946         error "$SHARED_DIRECTORY isn't a shared directory"
3947
3948     export MDSDB=$SHARED_DIRECTORY/mdsdb
3949     export OSTDB=$SHARED_DIRECTORY/ostdb
3950
3951     [ $MDSCOUNT -eq 1 ] || error "CMD is not supported"
3952
3953     run_e2fsck $(mdts_nodes) $MDTDEV "-n --mdsdb $MDSDB"
3954
3955     i=0
3956     ostidx=0
3957     OSTDB_LIST=""
3958     for node in $(osts_nodes); do
3959         for dev in ${OSTDEVS[i]}; do
3960             run_e2fsck $node $dev "-n --mdsdb $MDSDB --ostdb $OSTDB-$ostidx"
3961             OSTDB_LIST="$OSTDB_LIST $OSTDB-$ostidx"
3962             ostidx=$((ostidx + 1))
3963         done
3964         i=$((i + 1))
3965     done
3966 }
3967
3968 # Run lfsck on server node if lfsck can't be found on client (LU-2571)
3969 run_lfsck_remote() {
3970         local cmd="$LFSCK_BIN -c -l --mdsdb $MDSDB --ostdb $OSTDB_LIST $MOUNT"
3971         local client=$1
3972         local mounted=true
3973         local rc=0
3974
3975         #Check if lustre is already mounted
3976         do_rpc_nodes $client is_mounted $MOUNT || mounted=false
3977         if ! $mounted; then
3978                 zconf_mount $client $MOUNT ||
3979                         error "failed to mount Lustre on $client"
3980         fi
3981         #Run lfsck
3982         echo $cmd
3983         do_node $node $cmd || rc=$?
3984         #Umount if necessary
3985         if ! $mounted; then
3986                 zconf_umount $client $MOUNT ||
3987                         error "failed to unmount Lustre on $client"
3988         fi
3989
3990         [ $rc -le $FSCK_MAX_ERR ] ||
3991                 error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
3992         echo "lfsck finished with rc=$rc"
3993
3994         return $rc
3995 }
3996
3997 run_lfsck() {
3998         local facets="client $SINGLEMDS"
3999         local found=false
4000         local facet
4001         local node
4002         local rc=0
4003
4004         for facet in $facets; do
4005                 node=$(facet_active_host $facet)
4006                 if check_progs_installed $node $LFSCK_BIN; then
4007                         found=true
4008                         break
4009                 fi
4010         done
4011         ! $found && error "None of \"$facets\" supports lfsck"
4012
4013         run_lfsck_remote $node || rc=$?
4014
4015         rm -rvf $MDSDB* $OSTDB* || true
4016         return $rc
4017 }
4018
4019 check_and_cleanup_lustre() {
4020     if [ "$LFSCK_ALWAYS" = "yes" -a "$TESTSUITE" != "lfsck" ]; then
4021         get_svr_devs
4022         generate_db
4023         run_lfsck
4024     fi
4025
4026         if is_mounted $MOUNT; then
4027                 [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]* ||
4028                         error "remove sub-test dirs failed"
4029                 [ "$ENABLE_QUOTA" ] && restore_quota || true
4030         fi
4031
4032     if [ "$I_UMOUNTED2" = "yes" ]; then
4033         restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
4034     fi
4035
4036     if [ "$I_MOUNTED2" = "yes" ]; then
4037         cleanup_mount $MOUNT2
4038     fi
4039
4040     if [ "$I_MOUNTED" = "yes" ]; then
4041         cleanupall -f || error "cleanup failed"
4042         unset I_MOUNTED
4043     fi
4044 }
4045
4046 #######
4047 # General functions
4048
4049 wait_for_function () {
4050     local quiet=""
4051
4052     # suppress fn both stderr and stdout
4053     if [ "$1" = "--quiet" ]; then
4054         shift
4055         quiet=" > /dev/null 2>&1"
4056
4057     fi
4058
4059     local fn=$1
4060     local max=${2:-900}
4061     local sleep=${3:-5}
4062
4063     local wait=0
4064
4065     while true; do
4066
4067         eval $fn $quiet && return 0
4068
4069         wait=$((wait + sleep))
4070         [ $wait -lt $max ] || return 1
4071         echo waiting $fn, $((max - wait)) secs left ...
4072         sleep $sleep
4073     done
4074 }
4075
4076 check_network() {
4077     local host=$1
4078     local max=$2
4079     local sleep=${3:-5}
4080
4081     echo `date +"%H:%M:%S (%s)"` waiting for $host network $max secs ...
4082     if ! wait_for_function --quiet "ping -c 1 -w 3 $host" $max $sleep ; then
4083         echo "Network not available!"
4084         exit 1
4085     fi
4086
4087     echo `date +"%H:%M:%S (%s)"` network interface is UP
4088 }
4089
4090 no_dsh() {
4091     shift
4092     eval $@
4093 }
4094
4095 # Convert a space-delimited list to a comma-delimited list.  If the input is
4096 # only whitespace, ensure the output is empty (i.e. "") so [ -n $list ] works
4097 comma_list() {
4098         # echo is used to convert newlines to spaces, since it doesn't
4099         # introduce a trailing space as using "tr '\n' ' '" does
4100         echo $(tr -s " " "\n" <<< $* | sort -b -u) | tr ' ' ','
4101 }
4102
4103 list_member () {
4104     local list=$1
4105     local item=$2
4106     echo $list | grep -qw $item
4107 }
4108
4109 # list, excluded are the comma separated lists
4110 exclude_items_from_list () {
4111     local list=$1
4112     local excluded=$2
4113     local item
4114
4115     list=${list//,/ }
4116     for item in ${excluded//,/ }; do
4117         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
4118     done
4119     echo $(comma_list $list)
4120 }
4121
4122 # list, expand  are the comma separated lists
4123 expand_list () {
4124     local list=${1//,/ }
4125     local expand=${2//,/ }
4126     local expanded=
4127
4128     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
4129     echo $(comma_list $expanded)
4130 }
4131
4132 testslist_filter () {
4133     local script=$LUSTRE/tests/${TESTSUITE}.sh
4134
4135     [ -f $script ] || return 0
4136
4137     local start_at=$START_AT
4138     local stop_at=$STOP_AT
4139
4140     local var=${TESTSUITE//-/_}_START_AT
4141     [ x"${!var}" != x ] && start_at=${!var}
4142     var=${TESTSUITE//-/_}_STOP_AT
4143     [ x"${!var}" != x ] && stop_at=${!var}
4144
4145     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
4146         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
4147             /^'${start_at}'$/ {flag = 0}
4148             {if (flag == 1) print $0}
4149             /^'${stop_at}'$/ { flag = 1 }'
4150 }
4151
4152 absolute_path() {
4153     (cd `dirname $1`; echo $PWD/`basename $1`)
4154 }
4155
4156 get_facets () {
4157     local types=${1:-"OST MDS MGS"}
4158
4159     local list=""
4160
4161     for entry in $types; do
4162         local name=$(echo $entry | tr "[:upper:]" "[:lower:]")
4163         local type=$(echo $entry | tr "[:lower:]" "[:upper:]")
4164
4165         case $type in
4166                 MGS ) list="$list $name";;
4167             MDS|OST|AGT ) local count=${type}COUNT
4168                        for ((i=1; i<=${!count}; i++)) do
4169                           list="$list ${name}$i"
4170                       done;;
4171                   * ) error "Invalid facet type"
4172                  exit 1;;
4173         esac
4174     done
4175     echo $(comma_list $list)
4176 }
4177
4178 ##################################
4179 # Adaptive Timeouts funcs
4180
4181 at_is_enabled() {
4182     # only check mds, we assume at_max is the same on all nodes
4183     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
4184     if [ $at_max -eq 0 ]; then
4185         return 1
4186     else
4187         return 0
4188     fi
4189 }
4190
4191 at_get() {
4192     local facet=$1
4193     local at=$2
4194
4195     # suppose that all ost-s have the same $at value set
4196     [ $facet != "ost" ] || facet=ost1
4197
4198     do_facet $facet "lctl get_param -n $at"
4199 }
4200
4201 at_max_get() {
4202     at_get $1 at_max
4203 }
4204
4205 at_min_get() {
4206         at_get $1 at_min
4207 }
4208
4209 at_max_set() {
4210     local at_max=$1
4211     shift
4212
4213     local facet
4214     local hosts
4215     for facet in $@; do
4216         if [ $facet == "ost" ]; then
4217             facet=$(get_facets OST)
4218         elif [ $facet == "mds" ]; then
4219             facet=$(get_facets MDS)
4220         fi
4221         hosts=$(expand_list $hosts $(facets_hosts $facet))
4222     done
4223
4224     do_nodes $hosts lctl set_param at_max=$at_max
4225 }
4226
4227 ##################################
4228 # OBD_FAIL funcs
4229
4230 drop_request() {
4231 # OBD_FAIL_MDS_ALL_REQUEST_NET
4232     RC=0
4233     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
4234     do_facet client "$1" || RC=$?
4235     do_facet $SINGLEMDS lctl set_param fail_loc=0
4236     return $RC
4237 }
4238
4239 drop_reply() {
4240 # OBD_FAIL_MDS_ALL_REPLY_NET
4241     RC=0
4242     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
4243     do_facet client "$@" || RC=$?
4244     do_facet $SINGLEMDS lctl set_param fail_loc=0
4245     return $RC
4246 }
4247
4248 drop_reint_reply() {
4249 # OBD_FAIL_MDS_REINT_NET_REP
4250     RC=0
4251     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
4252     do_facet client "$@" || RC=$?
4253     do_facet $SINGLEMDS lctl set_param fail_loc=0
4254     return $RC
4255 }
4256
4257 drop_update_reply() {
4258 # OBD_FAIL_UPDATE_OBJ_NET_REP
4259         local index=$1
4260         shift 1
4261         RC=0
4262         do_facet mds${index} lctl set_param fail_loc=0x1701
4263         do_facet client "$@" || RC=$?
4264         do_facet mds${index} lctl set_param fail_loc=0
4265         return $RC
4266 }
4267
4268 pause_bulk() {
4269 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
4270         RC=0
4271
4272         local timeout=${2:-0}
4273         # default is (obd_timeout / 4) if unspecified
4274         echo "timeout is $timeout/$2"
4275         do_facet ost1 lctl set_param fail_val=$timeout fail_loc=0x80000214
4276         do_facet client "$1" || RC=$?
4277         do_facet client "sync"
4278         do_facet ost1 lctl set_param fail_loc=0
4279         return $RC
4280 }
4281
4282 drop_ldlm_cancel() {
4283 #define OBD_FAIL_LDLM_CANCEL_NET                        0x304
4284         local RC=0
4285         local list=$(comma_list $(mdts_nodes) $(osts_nodes))
4286         do_nodes $list lctl set_param fail_loc=0x304
4287
4288         do_facet client "$@" || RC=$?
4289
4290         do_nodes $list lctl set_param fail_loc=0
4291         return $RC
4292 }
4293
4294 drop_bl_callback() {
4295 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
4296         RC=0
4297         do_facet client lctl set_param fail_loc=0x80000305
4298         do_facet client "$@" || RC=$?
4299         do_facet client lctl set_param fail_loc=0
4300         return $RC
4301 }
4302
4303 drop_ldlm_reply() {
4304 #define OBD_FAIL_LDLM_REPLY              0x30c
4305     RC=0
4306     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
4307     do_facet client "$@" || RC=$?
4308     do_facet $SINGLEMDS lctl set_param fail_loc=0
4309     return $RC
4310 }
4311
4312 clear_failloc() {
4313     facet=$1
4314     pause=$2
4315     sleep $pause
4316     echo "clearing fail_loc on $facet"
4317     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
4318 }
4319
4320 set_nodes_failloc () {
4321         do_nodes $(comma_list $1)  lctl set_param fail_val=0 fail_loc=$2
4322 }
4323
4324 cancel_lru_locks() {
4325     $LCTL mark "cancel_lru_locks $1 start"
4326     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
4327         $LCTL set_param -n $d=clear
4328     done
4329     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
4330     $LCTL mark "cancel_lru_locks $1 stop"
4331 }
4332
4333 default_lru_size()
4334 {
4335         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
4336         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
4337         echo "$DEFAULT_LRU_SIZE"
4338 }
4339
4340 lru_resize_enable()
4341 {
4342     lctl set_param ldlm.namespaces.*$1*.lru_size=0
4343 }
4344
4345 lru_resize_disable()
4346 {
4347     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
4348 }
4349
4350 pgcache_empty() {
4351     local FILE
4352     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
4353         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
4354             echo there is still data in page cache $FILE ?
4355             lctl get_param -n $FILE
4356             return 1
4357         fi
4358     done
4359     return 0
4360 }
4361
4362 debugsave() {
4363     DEBUGSAVE="$(lctl get_param -n debug)"
4364 }
4365
4366 debugrestore() {
4367     [ -n "$DEBUGSAVE" ] && \
4368         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
4369     DEBUGSAVE=""
4370 }
4371
4372 debug_size_save() {
4373     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
4374 }
4375
4376 debug_size_restore() {
4377     [ -n "$DEBUG_SIZE_SAVED" ] && \
4378         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
4379     DEBUG_SIZE_SAVED=""
4380 }
4381
4382 start_full_debug_logging() {
4383     debugsave
4384     debug_size_save
4385
4386     local FULLDEBUG=-1
4387     local DEBUG_SIZE=150
4388
4389     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
4390     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
4391 }
4392
4393 stop_full_debug_logging() {
4394     debug_size_restore
4395     debugrestore
4396 }
4397
4398 # prints bash call stack
4399 log_trace_dump() {
4400         echo "  Trace dump:"
4401         for (( i=1; i < ${#BASH_LINENO[*]} ; i++ )) ; do
4402                 local s=${BASH_SOURCE[$i]}
4403                 local l=${BASH_LINENO[$i-1]}
4404                 local f=${FUNCNAME[$i]}
4405                 echo "  = $s:$l:$f()"
4406         done
4407 }
4408
4409 ##################################
4410 # Test interface
4411 ##################################
4412
4413 error_noexit() {
4414         local TYPE=${TYPE:-"FAIL"}
4415
4416         local dump=true
4417         # do not dump logs if $1=false
4418         if [ "x$1" = "xfalse" ]; then
4419                 shift
4420                 dump=false
4421         fi
4422
4423
4424         log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
4425         log_trace_dump
4426
4427         mkdir -p $LOGDIR
4428         # We need to dump the logs on all nodes
4429         if $dump; then
4430                 gather_logs $(comma_list $(nodes_list))
4431         fi
4432
4433         debugrestore
4434         [ "$TESTSUITELOG" ] &&
4435                 echo "$TESTSUITE: $TYPE: $TESTNAME $@" >> $TESTSUITELOG
4436         if [ -z "$*" ]; then
4437                 echo "error() without useful message, please fix" > $LOGDIR/err
4438         else
4439                 if [[ `echo $TYPE | grep ^IGNORE` ]]; then
4440                         echo "$@" > $LOGDIR/ignore
4441                 else
4442                         echo "$@" > $LOGDIR/err
4443                 fi
4444         fi
4445 }
4446
4447 exit_status () {
4448         local status=0
4449         local log=$TESTSUITELOG
4450
4451         [ -f "$log" ] && grep -q FAIL $log && status=1
4452         exit $status
4453 }
4454
4455 error() {
4456         error_noexit "$@"
4457         exit 1
4458 }
4459
4460 error_exit() {
4461         error "$@"
4462 }
4463
4464 # use only if we are ignoring failures for this test, bugno required.
4465 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
4466 # e.g. error_ignore bz5494 "your message" or
4467 # error_ignore LU-5494 "your message"
4468 error_ignore() {
4469         local TYPE="IGNORE ($1)"
4470         shift
4471         error_noexit "$@"
4472 }
4473
4474 error_and_remount() {
4475         error_noexit "$@"
4476         remount_client $MOUNT
4477         exit 1
4478 }
4479
4480 skip_env () {
4481         $FAIL_ON_SKIP_ENV && error false $@ || skip $@
4482 }
4483
4484 skip() {
4485         echo
4486         log " SKIP: $TESTSUITE $TESTNAME $@"
4487
4488         if [[ -n "$ALWAYS_SKIPPED" ]]; then
4489                 skip_logged $TESTNAME "$@"
4490         else
4491                 mkdir -p $LOGDIR
4492                 echo "$@" > $LOGDIR/skip
4493         fi
4494
4495         [[ -n "$TESTSUITELOG" ]] &&
4496                 echo "$TESTSUITE: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
4497 }
4498
4499 build_test_filter() {
4500     EXCEPT="$EXCEPT $(testslist_filter)"
4501
4502     [ "$ONLY" ] && log "only running test `echo $ONLY`"
4503     for O in $ONLY; do
4504         eval ONLY_${O}=true
4505     done
4506     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
4507         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
4508     [ "$EXCEPT_SLOW" ] && \
4509         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
4510     for E in $EXCEPT; do
4511         eval EXCEPT_${E}=true
4512     done
4513     for E in $ALWAYS_EXCEPT; do
4514         eval EXCEPT_ALWAYS_${E}=true
4515     done
4516     for E in $EXCEPT_SLOW; do
4517         eval EXCEPT_SLOW_${E}=true
4518     done
4519     for G in $GRANT_CHECK_LIST; do
4520         eval GCHECK_ONLY_${G}=true
4521         done
4522 }
4523
4524 basetest() {
4525     if [[ $1 = [a-z]* ]]; then
4526         echo $1
4527     else
4528         echo ${1%%[a-z]*}
4529     fi
4530 }
4531
4532 # print a newline if the last test was skipped
4533 export LAST_SKIPPED=
4534 export ALWAYS_SKIPPED=
4535 #
4536 # Main entry into test-framework. This is called with the name and
4537 # description of a test. The name is used to find the function to run
4538 # the test using "test_$name".
4539 #
4540 # This supports a variety of methods of specifying specific test to
4541 # run or not run.  These need to be documented...
4542 #
4543 run_test() {
4544     assert_DIR
4545
4546     export base=`basetest $1`
4547     if [ ! -z "$ONLY" ]; then
4548         testname=ONLY_$1
4549         if [ ${!testname}x != x ]; then
4550             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
4551             run_one_logged $1 "$2"
4552             return $?
4553         fi
4554         testname=ONLY_$base
4555         if [ ${!testname}x != x ]; then
4556             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
4557             run_one_logged $1 "$2"
4558             return $?
4559         fi
4560         LAST_SKIPPED="y"
4561         return 0
4562     fi
4563
4564         LAST_SKIPPED="y"
4565         ALWAYS_SKIPPED="y"
4566     testname=EXCEPT_$1
4567     if [ ${!testname}x != x ]; then
4568         TESTNAME=test_$1 skip "skipping excluded test $1"
4569         return 0
4570     fi
4571     testname=EXCEPT_$base
4572     if [ ${!testname}x != x ]; then
4573         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
4574         return 0
4575     fi
4576     testname=EXCEPT_ALWAYS_$1
4577     if [ ${!testname}x != x ]; then
4578         TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1"
4579         return 0
4580     fi
4581     testname=EXCEPT_ALWAYS_$base
4582     if [ ${!testname}x != x ]; then
4583         TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1 (base $base)"
4584         return 0
4585     fi
4586     testname=EXCEPT_SLOW_$1
4587     if [ ${!testname}x != x ]; then
4588         TESTNAME=test_$1 skip "skipping SLOW test $1"
4589         return 0
4590     fi
4591     testname=EXCEPT_SLOW_$base
4592     if [ ${!testname}x != x ]; then
4593         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
4594         return 0
4595     fi
4596
4597     LAST_SKIPPED=
4598     ALWAYS_SKIPPED=
4599     run_one_logged $1 "$2"
4600
4601     return $?
4602 }
4603
4604 log() {
4605     echo "$*"
4606     module_loaded lnet || load_modules
4607
4608     local MSG="$*"
4609     # Get rid of '
4610     MSG=${MSG//\'/\\\'}
4611     MSG=${MSG//\(/\\\(}
4612     MSG=${MSG//\)/\\\)}
4613     MSG=${MSG//\;/\\\;}
4614     MSG=${MSG//\|/\\\|}
4615     MSG=${MSG//\>/\\\>}
4616     MSG=${MSG//\</\\\<}
4617     MSG=${MSG//\//\\\/}
4618     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
4619 }
4620
4621 trace() {
4622         log "STARTING: $*"
4623         strace -o $TMP/$1.strace -ttt $*
4624         RC=$?
4625         log "FINISHED: $*: rc $RC"
4626         return 1
4627 }
4628
4629 complete () {
4630     local duration=$1
4631
4632     banner test complete, duration $duration sec
4633     [ -f "$TESTSUITELOG" ] && egrep .FAIL $TESTSUITELOG || true
4634     echo duration $duration >>$TESTSUITELOG
4635 }
4636
4637 pass() {
4638         # Set TEST_STATUS here. It will be used for logging the result.
4639         TEST_STATUS="PASS"
4640
4641         if [[ -f $LOGDIR/err ]]; then
4642                 TEST_STATUS="FAIL"
4643         elif [[ -f $LOGDIR/skip ]]; then
4644                 TEST_STATUS="SKIP"
4645         fi
4646         echo "$TEST_STATUS $@" 2>&1 | tee -a $TESTSUITELOG
4647 }
4648
4649 check_mds() {
4650     local FFREE=$(do_node $SINGLEMDS \
4651         lctl get_param -n osd*.*MDT*.filesfree | calc_sum)
4652     local FTOTAL=$(do_node $SINGLEMDS \
4653         lctl get_param -n osd*.*MDT*.filestotal | calc_sum)
4654
4655     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
4656 }
4657
4658 reset_fail_loc () {
4659     echo -n "Resetting fail_loc on all nodes..."
4660     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
4661     echo done.
4662 }
4663
4664
4665 #
4666 # Log a message (on all nodes) padded with "=" before and after. 
4667 # Also appends a timestamp and prepends the testsuite name.
4668
4669
4670 EQUALS="===================================================================================================="
4671 banner() {
4672     msg="== ${TESTSUITE} $*"
4673     last=${msg: -1:1}
4674     [[ $last != "=" && $last != " " ]] && msg="$msg "
4675     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
4676     # always include at least == after the message
4677     log "$msg== $(date +"%H:%M:%S (%s)")"
4678 }
4679
4680 #
4681 # Run a single test function and cleanup after it.  
4682 #
4683 # This function should be run in a subshell so the test func can
4684 # exit() without stopping the whole script.
4685 #
4686 run_one() {
4687     local testnum=$1
4688     local message=$2
4689     tfile=f.${TESTSUITE}.${testnum}
4690     export tdir=d0.${TESTSUITE}/d${base}
4691     export TESTNAME=test_$testnum
4692     local SAVE_UMASK=`umask`
4693     umask 0022
4694
4695     banner "test $testnum: $message"
4696     test_${testnum} || error "test_$testnum failed with $?"
4697     cd $SAVE_PWD
4698     reset_fail_loc
4699     check_grant ${testnum} || error "check_grant $testnum failed with $?"
4700     check_catastrophe || error "LBUG/LASSERT detected"
4701         if [ "$PARALLEL" != "yes" ]; then
4702                 ps auxww | grep -v grep | grep -q multiop &&
4703                                         error "multiop still running"
4704         fi
4705     unset TESTNAME
4706     unset tdir
4707     umask $SAVE_UMASK
4708     return 0
4709 }
4710
4711 #
4712 # Wrapper around run_one to ensure:
4713 #  - test runs in subshell
4714 #  - output of test is saved to separate log file for error reporting
4715 #  - test result is saved to data file
4716 #
4717 run_one_logged() {
4718         local BEFORE=`date +%s`
4719         local TEST_ERROR
4720         local name=${TESTSUITE}.test_${1}.test_log.$(hostname -s).log
4721         local test_log=$LOGDIR/$name
4722         rm -rf $LOGDIR/err
4723         rm -rf $LOGDIR/ignore
4724         rm -rf $LOGDIR/skip
4725         local SAVE_UMASK=`umask`
4726         umask 0022
4727
4728         echo
4729         log_sub_test_begin test_${1}
4730         (run_one $1 "$2") 2>&1 | tee -i $test_log
4731         local RC=${PIPESTATUS[0]}
4732
4733         [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] &&
4734                 echo "test_$1 returned $RC" | tee $LOGDIR/err
4735
4736         duration=$((`date +%s` - $BEFORE))
4737         pass "$1" "(${duration}s)"
4738
4739         if [[ -f $LOGDIR/err ]]; then
4740                 TEST_ERROR=$(cat $LOGDIR/err)
4741         elif [[ -f $LOGDIR/ignore ]]; then
4742                 TEST_ERROR=$(cat $LOGDIR/ignore)
4743         elif [[ -f $LOGDIR/skip ]]; then
4744                 TEST_ERROR=$(cat $LOGDIR/skip)
4745         fi
4746         log_sub_test_end $TEST_STATUS $duration "$RC" "$TEST_ERROR"
4747
4748         if [ -f $LOGDIR/err ]; then
4749                 $FAIL_ON_ERROR && exit $RC
4750         fi
4751
4752         umask $SAVE_UMASK
4753
4754         return 0
4755 }
4756
4757 #
4758 # Print information of skipped tests to result.yml
4759 #
4760 skip_logged(){
4761         log_sub_test_begin $1
4762         shift
4763         log_sub_test_end "SKIP" "0" "0" "$@"
4764 }
4765
4766 canonical_path() {
4767     (cd `dirname $1`; echo $PWD/`basename $1`)
4768 }
4769
4770
4771 check_grant() {
4772     export base=`basetest $1`
4773     [ "$CHECK_GRANT" == "no" ] && return 0
4774
4775         testname=GCHECK_ONLY_${base}
4776         [ ${!testname}x == x ] && return 0
4777
4778     echo -n "checking grant......"
4779
4780         local clients=$CLIENTS
4781         [ -z $clients ] && clients=$(hostname)
4782
4783     # sync all the data and make sure no pending data on server
4784     do_nodes $clients sync
4785
4786     # get client grant
4787     client_grant=`do_nodes $clients \
4788                     "$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes" | \
4789                     awk '{total += $1} END{print total}'`
4790
4791     # get server grant
4792     server_grant=`do_nodes $(comma_list $(osts_nodes)) \
4793                     "$LCTL get_param -n obdfilter.${FSNAME}-OST*.tot_granted" |
4794                     awk '{total += $1} END{print total}'`
4795
4796     # check whether client grant == server grant
4797     if [ $client_grant -ne $server_grant ]; then
4798         echo "failed: client:${client_grant} server: ${server_grant}."
4799         do_nodes $(comma_list $(osts_nodes)) \
4800                    "$LCTL get_param obdfilter.${FSNAME}-OST*.tot*"
4801         do_nodes $clients "$LCTL get_param osc.${FSNAME}-*.cur_*_bytes"
4802         return 1
4803     else
4804         echo "pass: client:${client_grant} server: ${server_grant}"
4805     fi
4806
4807 }
4808
4809 ########################
4810 # helper functions
4811
4812 osc_to_ost()
4813 {
4814     osc=$1
4815     ost=`echo $1 | awk -F_ '{print $3}'`
4816     if [ -z $ost ]; then
4817         ost=`echo $1 | sed 's/-osc.*//'`
4818     fi
4819     echo $ost
4820 }
4821
4822 ostuuid_from_index()
4823 {
4824     $LFS osts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
4825 }
4826
4827 ostname_from_index() {
4828     local uuid=$(ostuuid_from_index $1)
4829     echo ${uuid/_UUID/}
4830 }
4831
4832 index_from_ostuuid()
4833 {
4834     $LFS osts $2 | sed -ne "/${1}/s/\(.*\): .* .*$/\1/p"
4835 }
4836
4837 mdtuuid_from_index()
4838 {
4839     $LFS mdts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
4840 }
4841
4842 # Description:
4843 #   Return unique identifier for given hostname
4844 host_id() {
4845         local host_name=$1
4846         echo $host_name | md5sum | cut -d' ' -f1
4847 }
4848
4849 # Description:
4850 #   Returns list of ip addresses for each interface
4851 local_addr_list() {
4852         ip addr | awk '/inet\ / {print $2}' | awk -F\/ '{print $1}'
4853 }
4854
4855 is_local_addr() {
4856         local addr=$1
4857         # Cache address list to avoid mutiple execution of local_addr_list
4858         LOCAL_ADDR_LIST=${LOCAL_ADDR_LIST:-$(local_addr_list)}
4859         local i
4860         for i in $LOCAL_ADDR_LIST ; do
4861                 [[ "$i" == "$addr" ]] && return 0
4862         done
4863         return 1
4864 }
4865
4866 local_node() {
4867         local host_name=$1
4868         local is_local="IS_LOCAL_$(host_id $host_name)"
4869         if [ -z "${!is_local-}" ] ; then
4870                 eval $is_local=0
4871                 local host_ip=$($LUSTRE/tests/resolveip $host_name)
4872                 is_local_addr "$host_ip" && eval $is_local=1
4873         fi
4874         [[ "${!is_local}" == "1" ]]
4875 }
4876
4877 remote_node () {
4878         local node=$1
4879         local_node $node && return 1
4880         return 0
4881 }
4882
4883 remote_mds ()
4884 {
4885     local node
4886     for node in $(mdts_nodes); do
4887         remote_node $node && return 0
4888     done
4889     return 1
4890 }
4891
4892 remote_mds_nodsh()
4893 {
4894     [ "$CLIENTONLY" ] && return 0 || true
4895     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
4896 }
4897
4898 require_dsh_mds()
4899 {
4900         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
4901             MSKIPPED=1 && return 1
4902         return 0
4903 }
4904
4905 remote_ost ()
4906 {
4907     local node
4908     for node in $(osts_nodes) ; do
4909         remote_node $node && return 0
4910     done
4911     return 1
4912 }
4913
4914 remote_ost_nodsh()
4915 {
4916     [ "$CLIENTONLY" ] && return 0 || true 
4917     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
4918 }
4919
4920 require_dsh_ost()
4921 {
4922         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
4923             OSKIPPED=1 && return 1
4924         return 0
4925 }
4926
4927 remote_mgs_nodsh()
4928 {
4929     local MGS 
4930     MGS=$(facet_host mgs)
4931     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
4932 }
4933
4934 local_mode ()
4935 {
4936     remote_mds_nodsh || remote_ost_nodsh || \
4937         $(single_local_node $(comma_list $(nodes_list)))
4938 }
4939
4940 remote_servers () {
4941     remote_ost && remote_mds
4942 }
4943
4944 # Get the active nodes for facets.
4945 facets_nodes () {
4946         local facets=$1
4947         local facet
4948         local nodes
4949         local nodes_sort
4950         local i
4951
4952         for facet in ${facets//,/ }; do
4953                 nodes="$nodes $(facet_active_host $facet)"
4954         done
4955
4956         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
4957         echo -n $nodes_sort
4958 }
4959
4960 # Get all of the active MDS nodes.
4961 mdts_nodes () {
4962         echo -n $(facets_nodes $(get_facets MDS))
4963 }
4964
4965 # Get all of the active OSS nodes.
4966 osts_nodes () {
4967         echo -n $(facets_nodes $(get_facets OST))
4968 }
4969
4970 # Get all of the active AGT (HSM agent) nodes.
4971 agts_nodes () {
4972         echo -n $(facets_nodes $(get_facets AGT))
4973 }
4974
4975 # Get all of the client nodes and active server nodes.
4976 nodes_list () {
4977         local nodes=$HOSTNAME
4978         local nodes_sort
4979         local i
4980
4981         # CLIENTS (if specified) contains the local client
4982         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
4983
4984         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
4985                 nodes="$nodes $(facets_nodes $(get_facets))"
4986         fi
4987
4988         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
4989         echo -n $nodes_sort
4990 }
4991
4992 # Get all of the remote client nodes and remote active server nodes.
4993 remote_nodes_list () {
4994         echo -n $(nodes_list) | sed -re "s/\<$HOSTNAME\>//g"
4995 }
4996
4997 # Get all of the MDS nodes, including active and passive nodes.
4998 all_mdts_nodes () {
4999         local host
5000         local failover_host
5001         local nodes
5002         local nodes_sort
5003         local i
5004
5005         for i in $(seq $MDSCOUNT); do
5006                 host=mds${i}_HOST
5007                 failover_host=mds${i}failover_HOST
5008                 nodes="$nodes ${!host} ${!failover_host}"
5009         done
5010
5011         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5012         echo -n $nodes_sort
5013 }
5014
5015 # Get all of the OSS nodes, including active and passive nodes.
5016 all_osts_nodes () {
5017         local host
5018         local failover_host
5019         local nodes
5020         local nodes_sort
5021         local i
5022
5023         for i in $(seq $OSTCOUNT); do
5024                 host=ost${i}_HOST
5025                 failover_host=ost${i}failover_HOST
5026                 nodes="$nodes ${!host} ${!failover_host}"
5027         done
5028
5029         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5030         echo -n $nodes_sort
5031 }
5032
5033 # Get all of the server nodes, including active and passive nodes.
5034 all_server_nodes () {
5035         local nodes
5036         local nodes_sort
5037         local i
5038
5039         nodes="$mgs_HOST $mgsfailover_HOST $(all_mdts_nodes) $(all_osts_nodes)"
5040
5041         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5042         echo -n $nodes_sort
5043 }
5044
5045 # Get all of the client and server nodes, including active and passive nodes.
5046 all_nodes () {
5047         local nodes=$HOSTNAME
5048         local nodes_sort
5049         local i
5050
5051         # CLIENTS (if specified) contains the local client
5052         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
5053
5054         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
5055                 nodes="$nodes $(all_server_nodes)"
5056         fi
5057
5058         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
5059         echo -n $nodes_sort
5060 }
5061
5062 init_clients_lists () {
5063     # Sanity check: exclude the local client from RCLIENTS
5064     local clients=$(hostlist_expand "$RCLIENTS")
5065     local rclients=$(exclude_items_from_list "$clients" $HOSTNAME)
5066
5067     # Sanity check: exclude the dup entries
5068     RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)
5069
5070     clients="$SINGLECLIENT $HOSTNAME $RCLIENTS"
5071
5072     # Sanity check: exclude the dup entries from CLIENTS
5073     # for those configs which has SINGLCLIENT set to local client
5074     clients=$(for i in $clients; do echo $i; done | sort -u)
5075
5076     CLIENTS=$(comma_list $clients)
5077     local -a remoteclients=($RCLIENTS)
5078     for ((i=0; $i<${#remoteclients[@]}; i++)); do
5079             varname=CLIENT$((i + 2))
5080             eval $varname=${remoteclients[i]}
5081     done
5082
5083     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
5084 }
5085
5086 get_random_entry () {
5087     local rnodes=$1
5088
5089     rnodes=${rnodes//,/ }
5090
5091     local -a nodes=($rnodes)
5092     local num=${#nodes[@]} 
5093     local i=$((RANDOM * num * 2 / 65536))
5094
5095     echo ${nodes[i]}
5096 }
5097
5098 client_only () {
5099     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
5100 }
5101
5102 is_patchless ()
5103 {
5104     lctl get_param version | grep -q patchless
5105 }
5106
5107 check_versions () {
5108     [ "$(lustre_version_code client)" = "$(lustre_version_code $SINGLEMDS)" -a \
5109       "$(lustre_version_code client)" = "$(lustre_version_code ost1)" ]
5110 }
5111
5112 get_node_count() {
5113     local nodes="$@"
5114     echo $nodes | wc -w || true
5115 }
5116
5117 mixed_ost_devs () {
5118     local nodes=$(osts_nodes)
5119     local osscount=$(get_node_count "$nodes")
5120     [ ! "$OSTCOUNT" = "$osscount" ]
5121 }
5122
5123 mixed_mdt_devs () {
5124     local nodes=$(mdts_nodes)
5125     local mdtcount=$(get_node_count "$nodes")
5126     [ ! "$MDSCOUNT" = "$mdtcount" ]
5127 }
5128
5129 generate_machine_file() {
5130     local nodes=${1//,/ }
5131     local machinefile=$2
5132     rm -f $machinefile
5133     for node in $nodes; do
5134         echo $node >>$machinefile || \
5135             { echo "can not generate machinefile $machinefile" && return 1; }
5136     done
5137 }
5138
5139 get_stripe () {
5140         local file=$1/stripe
5141
5142         touch $file
5143         $LFS getstripe -v $file || error "getstripe $file failed"
5144         rm -f $file
5145 }
5146
5147 setstripe_nfsserver () {
5148     local dir=$1
5149
5150     local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
5151                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -1)
5152
5153     [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
5154
5155     do_nodev $nfsserver lfs setstripe "$@"
5156 }
5157
5158 # Check and add a test group.
5159 add_group() {
5160         local group_id=$1
5161         local group_name=$2
5162         local rc=0
5163
5164         local gid=$(getent group $group_name | cut -d: -f3)
5165         if [[ -n "$gid" ]]; then
5166                 [[ "$gid" -eq "$group_id" ]] || {
5167                         error_noexit "inconsistent group ID:" \
5168                                      "new: $group_id, old: $gid"
5169                         rc=1
5170                 }
5171         else
5172                 groupadd -g $group_id $group_name
5173                 rc=${PIPESTATUS[0]}
5174         fi
5175
5176         return $rc
5177 }
5178
5179 # Check and add a test user.
5180 add_user() {
5181         local user_id=$1
5182         shift
5183         local user_name=$1
5184         shift
5185         local group_name=$1
5186         shift
5187         local home=$1
5188         shift
5189         local opts="$@"
5190         local rc=0
5191
5192         local uid=$(getent passwd $user_name | cut -d: -f3)
5193         if [[ -n "$uid" ]]; then
5194                 if [[ "$uid" -eq "$user_id" ]]; then
5195                         local dir=$(getent passwd $user_name | cut -d: -f6)
5196                         if [[ "$dir" != "$home" ]]; then
5197                                 mkdir -p $home
5198                                 usermod -d $home $user_name
5199                                 rc=${PIPESTATUS[0]}
5200                         fi
5201                 else
5202                         error_noexit "inconsistent user ID:" \
5203                                      "new: $user_id, old: $uid"
5204                         rc=1
5205                 fi
5206         else
5207                 mkdir -p $home
5208                 useradd -M -u $user_id -d $home -g $group_name $opts $user_name
5209                 rc=${PIPESTATUS[0]}
5210         fi
5211
5212         return $rc
5213 }
5214
5215 check_runas_id_ret() {
5216     local myRC=0
5217     local myRUNAS_UID=$1
5218     local myRUNAS_GID=$2
5219     shift 2
5220     local myRUNAS=$@
5221     if [ -z "$myRUNAS" ]; then
5222         error_exit "myRUNAS command must be specified for check_runas_id"
5223     fi
5224     if $GSS_KRB5; then
5225         $myRUNAS krb5_login.sh || \
5226             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
5227     fi
5228     mkdir $DIR/d0_runas_test
5229     chmod 0755 $DIR
5230     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
5231     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
5232     rm -rf $DIR/d0_runas_test
5233     return $myRC
5234 }
5235
5236 check_runas_id() {
5237     local myRUNAS_UID=$1
5238     local myRUNAS_GID=$2
5239     shift 2
5240     local myRUNAS=$@
5241     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
5242         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
5243         Please set RUNAS_ID to some UID which exists on MDS and client or
5244         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
5245 }
5246
5247 # obtain the UID/GID for MPI_USER
5248 get_mpiuser_id() {
5249     local mpi_user=$1
5250
5251     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
5252 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
5253
5254     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
5255 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
5256 }
5257
5258 # obtain and cache Kerberos ticket-granting ticket
5259 refresh_krb5_tgt() {
5260     local myRUNAS_UID=$1
5261     local myRUNAS_GID=$2
5262     shift 2
5263     local myRUNAS=$@
5264     if [ -z "$myRUNAS" ]; then
5265         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
5266     fi
5267
5268     CLIENTS=${CLIENTS:-$HOSTNAME}
5269     do_nodes $CLIENTS "set -x
5270 if ! $myRUNAS krb5_login.sh; then
5271     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
5272     exit 1
5273 fi"
5274 }
5275
5276 # Run multiop in the background, but wait for it to print
5277 # "PAUSING" to its stdout before returning from this function.
5278 multiop_bg_pause() {
5279     MULTIOP_PROG=${MULTIOP_PROG:-$MULTIOP}
5280     FILE=$1
5281     ARGS=$2
5282
5283     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
5284     mkfifo $TMPPIPE
5285
5286     echo "$MULTIOP_PROG $FILE v$ARGS"
5287     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
5288
5289     echo "TMPPIPE=${TMPPIPE}"
5290     read -t 60 multiop_output < $TMPPIPE
5291     if [ $? -ne 0 ]; then
5292         rm -f $TMPPIPE
5293         return 1
5294     fi
5295     rm -f $TMPPIPE
5296     if [ "$multiop_output" != "PAUSING" ]; then
5297         echo "Incorrect multiop output: $multiop_output"
5298         kill -9 $PID
5299         return 1
5300     fi
5301
5302     return 0
5303 }
5304
5305 do_and_time () {
5306     local cmd=$1
5307     local rc
5308
5309     SECONDS=0
5310     eval '$cmd'
5311     
5312     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
5313
5314     echo $SECONDS
5315     return $rc
5316 }
5317
5318 inodes_available () {
5319     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
5320     echo $IFree
5321 }
5322
5323 mdsrate_inodes_available () {
5324     local min_inodes=$(inodes_available)
5325     echo $((min_inodes * 99 / 100))
5326 }
5327
5328 # reset llite stat counters
5329 clear_llite_stats(){
5330         lctl set_param -n llite.*.stats 0
5331 }
5332
5333 # sum llite stat items
5334 calc_llite_stats() {
5335         local res=$(lctl get_param -n llite.*.stats |
5336                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
5337         echo $res
5338 }
5339
5340 # reset osc stat counters
5341 clear_osc_stats(){
5342         lctl set_param -n osc.*.osc_stats 0
5343 }
5344
5345 # sum osc stat items
5346 calc_osc_stats() {
5347         local res=$(lctl get_param -n osc.*.osc_stats |
5348                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
5349         echo $res
5350 }
5351
5352 calc_sum () {
5353         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
5354 }
5355
5356 calc_osc_kbytes () {
5357         df $MOUNT > /dev/null
5358         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
5359 }
5360
5361 # save_lustre_params(comma separated facet list, parameter_mask)
5362 # generate a stream of formatted strings (<facet> <param name>=<param value>)
5363 save_lustre_params() {
5364         local facets=$1
5365         local facet
5366         local nodes
5367         local node
5368
5369         for facet in ${facets//,/ }; do
5370                 node=$(facet_active_host $facet)
5371                 [[ *\ $node\ * = " $nodes " ]] && continue
5372                 nodes="$nodes $node"
5373
5374                 do_node $node "$LCTL get_param $2 |
5375                         while read s; do echo $facet \\\$s; done"
5376         done
5377 }
5378
5379 # restore lustre parameters from input stream, produces by save_lustre_params
5380 restore_lustre_params() {
5381         local facet
5382         local name
5383         local val
5384
5385         while IFS=" =" read facet name val; do
5386                 do_facet $facet "$LCTL set_param -n $name $val"
5387         done
5388 }
5389
5390 check_catastrophe() {
5391         local rnodes=${1:-$(comma_list $(remote_nodes_list))}
5392         local C=$CATASTROPHE
5393         [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
5394
5395         [ -z "$rnodes" ] && return 0
5396
5397         local data
5398         data=$(do_nodes "$rnodes" "rc=\\\$([ -f $C ] &&
5399                 echo \\\$(< $C) || echo 0);
5400                 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
5401                 exit \\\$rc")
5402         local rc=$?
5403         if [ -n "$data" ]; then
5404             echo $data
5405             return $rc
5406         fi
5407         return 0
5408 }
5409
5410 # CMD: determine mds index where directory inode presents
5411 get_mds_dir () {
5412     local dir=$1
5413     local file=$dir/f0.get_mds_dir_tmpfile
5414
5415     mkdir -p $dir
5416     rm -f $file
5417     sleep 1
5418     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
5419     local -a oldused=($iused)
5420
5421     openfile -f O_CREAT:O_LOV_DELAY_CREATE -m 0644 $file > /dev/null
5422     sleep 1
5423     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
5424     local -a newused=($iused)
5425
5426     local num=0
5427     for ((i=0; i<${#newused[@]}; i++)); do
5428          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
5429              echo $(( i + 1 ))
5430              rm -f $file
5431              return 0
5432          fi
5433     done
5434     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
5435 }
5436
5437 mdsrate_cleanup () {
5438         if [ -d $4 ]; then
5439                 mpi_run ${MACHINEFILE_OPTION} $2 -np $1 ${MDSRATE} --unlink \
5440                         --nfiles $3 --dir $4 --filefmt $5 $6
5441                 rmdir $4
5442         fi
5443 }
5444
5445 delayed_recovery_enabled () {
5446     local var=${SINGLEMDS}_svc
5447     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
5448 }
5449
5450 ########################
5451
5452 convert_facet2label() {
5453     local facet=$1
5454
5455     if [ x$facet = xost ]; then
5456        facet=ost1
5457     fi
5458
5459     local varsvc=${facet}_svc
5460
5461     if [ -n ${!varsvc} ]; then
5462         echo ${!varsvc}
5463     else
5464         error "No lablel for $facet!"
5465     fi
5466 }
5467
5468 get_clientosc_proc_path() {
5469     echo "${1}-osc-*"
5470 }
5471
5472 get_lustre_version () {
5473     local facet=${1:-"$SINGLEMDS"}    
5474     do_facet $facet $LCTL get_param -n version | awk '/^lustre:/ {print $2}'
5475 }
5476
5477 lustre_version_code() {
5478     local facet=${1:-"$SINGLEMDS"}
5479     version_code $(get_lustre_version $1)
5480 }
5481
5482 # If the 2.0 MDS was mounted on 1.8 device, then the OSC and LOV names
5483 # used by MDT would not be changed.
5484 # mdt lov: fsname-mdtlov
5485 # mdt osc: fsname-OSTXXXX-osc
5486 mds_on_old_device() {
5487     local mds=${1:-"$SINGLEMDS"}
5488
5489     if [ $(lustre_version_code $mds) -gt $(version_code 1.9.0) ]; then
5490         do_facet $mds "lctl list_param osc.$FSNAME-OST*-osc \
5491             > /dev/null 2>&1" && return 0
5492     fi
5493     return 1
5494 }
5495
5496 get_mdtosc_proc_path() {
5497     local mds_facet=$1
5498     local ost_label=${2:-"*OST*"}
5499
5500     [ "$mds_facet" = "mds" ] && mds_facet=$SINGLEMDS
5501     local mdt_label=$(convert_facet2label $mds_facet)
5502     local mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')
5503
5504     if [ $(lustre_version_code $mds_facet) -le $(version_code 1.8.0) ] ||
5505        mds_on_old_device $mds_facet; then
5506         echo "${ost_label}-osc"
5507     else
5508         echo "${ost_label}-osc-${mdt_index}"
5509     fi
5510 }
5511
5512 get_osc_import_name() {
5513     local facet=$1
5514     local ost=$2
5515     local label=$(convert_facet2label $ost)
5516
5517     if [ "${facet:0:3}" = "mds" ]; then
5518         get_mdtosc_proc_path $facet $label
5519         return 0
5520     fi
5521
5522     get_clientosc_proc_path $label
5523     return 0
5524 }
5525
5526 _wait_import_state () {
5527     local expected=$1
5528     local CONN_PROC=$2
5529     local maxtime=${3:-$(max_recovery_time)}
5530     local CONN_STATE
5531     local i=0
5532
5533         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
5534     while [ "${CONN_STATE}" != "${expected}" ]; do
5535         if [ "${expected}" == "DISCONN" ]; then
5536             # for disconn we can check after proc entry is removed
5537             [ "x${CONN_STATE}" == "x" ] && return 0
5538             #  with AT enabled, we can have connect request timeout near of
5539             # reconnect timeout and test can't see real disconnect
5540             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
5541         fi
5542         [ $i -ge $maxtime ] && \
5543             error "can't put import for $CONN_PROC into ${expected} state after $i sec, have ${CONN_STATE}" && \
5544             return 1
5545         sleep 1
5546         # Add uniq for multi-mount case
5547         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
5548         i=$(($i + 1))
5549     done
5550
5551     log "$CONN_PROC in ${CONN_STATE} state after $i sec"
5552     return 0
5553 }
5554
5555 wait_import_state() {
5556     local state=$1
5557     local params=$2
5558     local maxtime=${3:-$(max_recovery_time)}
5559     local param
5560
5561     for param in ${params//,/ }; do
5562         _wait_import_state $state $param $maxtime || return
5563     done
5564 }
5565
5566 wait_import_state_mount() {
5567         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
5568                 return 0
5569         fi
5570
5571         wait_import_state $*
5572 }
5573
5574 # One client request could be timed out because server was not ready
5575 # when request was sent by client.
5576 # The request timeout calculation details :
5577 # ptl_send_rpc ()
5578 #      /* We give the server rq_timeout secs to process the req, and
5579 #      add the network latency for our local timeout. */
5580 #      request->rq_deadline = request->rq_sent + request->rq_timeout +
5581 #           ptlrpc_at_get_net_latency(request) ;
5582 #
5583 # ptlrpc_connect_import ()
5584 #      request->rq_timeout = INITIAL_CONNECT_TIMEOUT
5585 #
5586 # init_imp_at () ->
5587 #   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0
5588 # ptlrpc_at_get_net_latency(request) ->
5589 #       at_get (max (iat_net_latency=0, at_min)) = at_min
5590 #
5591 # i.e.:
5592 # request->rq_timeout + ptlrpc_at_get_net_latency(request) =
5593 # INITIAL_CONNECT_TIMEOUT + at_min
5594 #
5595 # We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT
5596 # because we can not get this value in runtime,
5597 # the value depends on configure options, and it is not stored in /proc.
5598 # obd_support.h:
5599 # #define CONNECTION_SWITCH_MIN 5U
5600 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
5601
5602 request_timeout () {
5603     local facet=$1
5604
5605     # request->rq_timeout = INITIAL_CONNECT_TIMEOUT
5606     local init_connect_timeout=$TIMEOUT
5607     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
5608
5609     local at_min=$(at_get $facet at_min)
5610
5611     echo $(( init_connect_timeout + at_min ))
5612 }
5613
5614 _wait_osc_import_state() {
5615     local facet=$1
5616     local ost_facet=$2
5617     local expected=$3
5618     local ost=$(get_osc_import_name $facet $ost_facet)
5619
5620         local param="osc.${ost}.ost_server_uuid"
5621         local i=0
5622
5623     # 1. wait the deadline of client 1st request (it could be skipped)
5624     # 2. wait the deadline of client 2nd request
5625     local maxtime=$(( 2 * $(request_timeout $facet)))
5626
5627         #During setup time, the osc might not be setup, it need wait
5628         #until list_param can return valid value. And also if there
5629         #are mulitple osc entries we should list all of them before
5630         #go to wait.
5631         local params=$($LCTL list_param $param 2>/dev/null || true)
5632         while [ -z "$params" ]; do
5633                 if [ $i -ge $maxtime ]; then
5634                         echo "can't get $param by list_param in $maxtime secs"
5635                         if [[ $facet != client* ]]; then
5636                                 echo "Go with $param directly"
5637                                 params=$param
5638                                 break
5639                         else
5640                                 return 1
5641                         fi
5642                 fi
5643                 sleep 1
5644                 i=$((i + 1))
5645                 params=$($LCTL list_param $param 2>/dev/null || true)
5646         done
5647
5648         if ! do_rpc_nodes "$(facet_active_host $facet)" \
5649                         wait_import_state $expected "$params" $maxtime; then
5650                 error "import is not in ${expected} state"
5651                 return 1
5652         fi
5653
5654         return 0
5655 }
5656
5657 wait_osc_import_state() {
5658         local facet=$1
5659         local ost_facet=$2
5660         local expected=$3
5661         local num
5662
5663         if [[ $facet = mds ]]; then
5664                 for num in $(seq $MDSCOUNT); do
5665                         _wait_osc_import_state mds$num "$ost_facet" "$expected"
5666                 done
5667         else
5668                 _wait_osc_import_state "$facet" "$ost_facet" "$expected"
5669         fi
5670 }
5671
5672 get_clientmdc_proc_path() {
5673     echo "${1}-mdc-*"
5674 }
5675
5676 do_rpc_nodes () {
5677         local list=$1
5678         shift
5679
5680         [ -z "$list" ] && return 0
5681
5682         # Add paths to lustre tests for 32 and 64 bit systems.
5683         local LIBPATH="/usr/lib/lustre/tests:/usr/lib64/lustre/tests:"
5684         local TESTPATH="$RLUSTRE/tests:"
5685         local RPATH="PATH=${TESTPATH}${LIBPATH}${PATH}:/sbin:/bin:/usr/sbin:"
5686         do_nodesv $list "${RPATH} NAME=${NAME} sh rpc.sh $@ "
5687 }
5688
5689 wait_clients_import_state () {
5690     local list=$1
5691     local facet=$2
5692     local expected=$3
5693
5694     local facets=$facet
5695
5696     if [ "$FAILURE_MODE" = HARD ]; then
5697         facets=$(facets_on_host $(facet_active_host $facet))
5698     fi
5699
5700     for facet in ${facets//,/ }; do
5701     local label=$(convert_facet2label $facet)
5702     local proc_path
5703     case $facet in
5704         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
5705         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
5706         *) error "unknown facet!" ;;
5707     esac
5708     local params=$(expand_list $params $proc_path)
5709     done
5710
5711         if ! do_rpc_nodes "$list" wait_import_state_mount $expected $params; then
5712                 error "import is not in ${expected} state"
5713                 return 1
5714         fi
5715 }
5716
5717 oos_full() {
5718         local -a AVAILA
5719         local -a GRANTA
5720         local -a TOTALA
5721         local OSCFULL=1
5722         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
5723                   $LCTL get_param obdfilter.*.kbytesavail))
5724         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
5725                   $LCTL get_param -n obdfilter.*.tot_granted))
5726         TOTALA=($(do_nodes $(comma_list $(osts_nodes)) \
5727                   $LCTL get_param -n obdfilter.*.kbytestotal))
5728         for ((i=0; i<${#AVAILA[@]}; i++)); do
5729                 local -a AVAIL1=(${AVAILA[$i]//=/ })
5730                 local -a TOTAL=(${TOTALA[$i]//=/ })
5731                 GRANT=$((${GRANTA[$i]}/1024))
5732                 # allow 1% of total space in bavail because of delayed
5733                 # allocation with ZFS which might release some free space after
5734                 # txg commit.  For small devices, we set a mininum of 8MB
5735                 local LIMIT=$((${TOTAL} / 100 + 8000))
5736                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} \
5737                         grnt=$GRANT diff=$((AVAIL1[1] - GRANT)) limit=${LIMIT}
5738                 [ $((AVAIL1[1] - GRANT)) -lt $LIMIT ] && OSCFULL=0 && \
5739                         echo " FULL" || echo
5740         done
5741         return $OSCFULL
5742 }
5743
5744 pool_list () {
5745    do_facet mgs lctl pool_list $1
5746 }
5747
5748 create_pool() {
5749     local fsname=${1%%.*}
5750     local poolname=${1##$fsname.}
5751
5752     do_facet mgs lctl pool_new $1
5753     local RC=$?
5754     # get param should return err unless pool is created
5755     [[ $RC -ne 0 ]] && return $RC
5756
5757     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
5758         2>/dev/null || echo foo" "" || RC=1
5759     if [[ $RC -eq 0 ]]; then
5760         add_pool_to_list $1
5761     else
5762         error "pool_new failed $1"
5763     fi
5764     return $RC
5765 }
5766
5767 add_pool_to_list () {
5768     local fsname=${1%%.*}
5769     local poolname=${1##$fsname.}
5770
5771     local listvar=${fsname}_CREATED_POOLS
5772     eval export ${listvar}=$(expand_list ${!listvar} $poolname)
5773 }
5774
5775 remove_pool_from_list () {
5776     local fsname=${1%%.*}
5777     local poolname=${1##$fsname.}
5778
5779     local listvar=${fsname}_CREATED_POOLS
5780     eval export ${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
5781 }
5782
5783 destroy_pool_int() {
5784     local ost
5785     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
5786         awk '$1 !~ /^Pool:/ {print $1}')
5787     for ost in $OSTS; do
5788         do_facet mgs lctl pool_remove $1 $ost
5789     done
5790     do_facet mgs lctl pool_destroy $1
5791 }
5792
5793 # <fsname>.<poolname> or <poolname>
5794 destroy_pool() {
5795     local fsname=${1%%.*}
5796     local poolname=${1##$fsname.}
5797
5798     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
5799
5800     local RC
5801
5802     pool_list $fsname.$poolname || return $?
5803
5804     destroy_pool_int $fsname.$poolname
5805     RC=$?
5806     [[ $RC -ne 0 ]] && return $RC
5807
5808     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
5809       2>/dev/null || echo foo" "foo" || RC=1
5810
5811     if [[ $RC -eq 0 ]]; then
5812         remove_pool_from_list $fsname.$poolname
5813     else
5814         error "destroy pool failed $1"
5815     fi
5816     return $RC
5817 }
5818
5819 destroy_pools () {
5820     local fsname=${1:-$FSNAME}
5821     local poolname
5822     local listvar=${fsname}_CREATED_POOLS
5823
5824     pool_list $fsname
5825
5826     [ x${!listvar} = x ] && return 0
5827
5828     echo destroy the created pools: ${!listvar}
5829     for poolname in ${!listvar//,/ }; do
5830         destroy_pool $fsname.$poolname
5831     done
5832 }
5833
5834 cleanup_pools () {
5835     local fsname=${1:-$FSNAME}
5836     trap 0
5837     destroy_pools $fsname
5838 }
5839
5840 gather_logs () {
5841     local list=$1
5842
5843     local ts=$(date +%s)
5844     local docp=true
5845
5846     if [[ ! -f "$YAML_LOG" ]]; then
5847         # init_logging is not performed before gather_logs,
5848         # so the $LOGDIR needs to be checked here
5849         check_shared_dir $LOGDIR && touch $LOGDIR/shared
5850     fi
5851
5852     [ -f $LOGDIR/shared ] && docp=false
5853
5854     # dump lustre logs, dmesg
5855
5856     prefix="$TESTLOG_PREFIX.$TESTNAME"
5857     suffix="$ts.log"
5858     echo "Dumping lctl log to ${prefix}.*.${suffix}"
5859
5860     if [ "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
5861         echo "Dumping logs only on local client."
5862         $LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}
5863         dmesg > ${prefix}.dmesg.$(hostname -s).${suffix}
5864         return
5865     fi
5866
5867     do_nodesv $list \
5868         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname -s).${suffix};
5869          dmesg > ${prefix}.dmesg.\\\$(hostname -s).${suffix}"
5870     if [ ! -f $LOGDIR/shared ]; then
5871         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
5872     fi
5873 }
5874
5875 do_ls () {
5876     local mntpt_root=$1
5877     local num_mntpts=$2
5878     local dir=$3
5879     local i
5880     local cmd
5881     local pids
5882     local rc=0
5883
5884     for i in $(seq 0 $num_mntpts); do
5885         cmd="ls -laf ${mntpt_root}$i/$dir"
5886         echo + $cmd;
5887         $cmd > /dev/null &
5888         pids="$pids $!"
5889     done
5890     echo pids=$pids
5891     for pid in $pids; do
5892         wait $pid || rc=$?
5893     done
5894
5895     return $rc
5896 }
5897
5898 # target_start_and_reset_recovery_timer()
5899 #        service_time = at_est2timeout(service_time);
5900 #        service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC +
5901 #                             INITIAL_CONNECT_TIMEOUT);
5902 # CONNECTION_SWITCH_MAX : min(25U, max(CONNECTION_SWITCH_MIN,obd_timeout))
5903 #define CONNECTION_SWITCH_INC 1
5904 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
5905 #define CONNECTION_SWITCH_MIN 5U
5906
5907 max_recovery_time () {
5908     local init_connect_timeout=$(( TIMEOUT / 20 ))
5909     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
5910
5911     local service_time=$(( $(at_max_get client) + $(( 2 * $(( 25 + 1  + init_connect_timeout)) )) ))
5912
5913     echo $service_time 
5914 }
5915
5916 get_clients_mount_count () {
5917     local clients=${CLIENTS:-`hostname`}
5918
5919     # we need to take into account the clients mounts and
5920     # exclude mds/ost mounts if any;
5921     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
5922 }
5923
5924 # gss functions
5925 PROC_CLI="srpc_info"
5926
5927 combination()
5928 {
5929     local M=$1
5930     local N=$2
5931     local R=1
5932
5933     if [ $M -lt $N ]; then
5934         R=0
5935     else
5936         N=$((N + 1))
5937         while [ $N -lt $M ]; do
5938             R=$((R * N))
5939             N=$((N + 1))
5940         done
5941     fi
5942
5943     echo $R
5944     return 0
5945 }
5946
5947 calc_connection_cnt() {
5948     local dir=$1
5949
5950     # MDT->MDT = 2 * C(M, 2)
5951     # MDT->OST = M * O
5952     # CLI->OST = C * O
5953     # CLI->MDT = C * M
5954     comb_m2=$(combination $MDSCOUNT 2)
5955
5956     local num_clients=$(get_clients_mount_count)
5957
5958     local cnt_mdt2mdt=$((comb_m2 * 2))
5959     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
5960     local cnt_cli2ost=$((num_clients * OSTCOUNT))
5961     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
5962     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
5963     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
5964     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
5965
5966     local var=cnt_$dir
5967     local res=${!var}
5968
5969     echo $res
5970 }
5971
5972 set_rule()
5973 {
5974     local tgt=$1
5975     local net=$2
5976     local dir=$3
5977     local flavor=$4
5978     local cmd="$tgt.srpc.flavor"
5979
5980     if [ $net == "any" ]; then
5981         net="default"
5982     fi
5983     cmd="$cmd.$net"
5984
5985     if [ $dir != "any" ]; then
5986         cmd="$cmd.$dir"
5987     fi
5988
5989     cmd="$cmd=$flavor"
5990     log "Setting sptlrpc rule: $cmd"
5991     do_facet mgs "$LCTL conf_param $cmd"
5992 }
5993
5994 count_flvr()
5995 {
5996     local output=$1
5997     local flavor=$2
5998     local count=0
5999
6000     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
6001     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
6002
6003     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
6004
6005     if [ "x$bulkspec" != "x" ]; then
6006         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
6007
6008         if [ "x$algs" != "x" ]; then
6009             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
6010         else
6011             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
6012             if [ $bulk == "bulkn" ]; then
6013                 bulk_count=`echo "$output" | grep "bulk flavor" \
6014                             | grep "null/null" | wc -l`
6015             elif [ $bulk == "bulki" ]; then
6016                 bulk_count=`echo "$output" | grep "bulk flavor" \
6017                             | grep "/null" | grep -v "null/" | wc -l`
6018             else
6019                 bulk_count=`echo "$output" | grep "bulk flavor" \
6020                             | grep -v "/null" | grep -v "null/" | wc -l`
6021             fi
6022         fi
6023
6024         [ $bulk_count -lt $count ] && count=$bulk_count
6025     fi
6026
6027     echo $count
6028 }
6029
6030 flvr_cnt_cli2mdt()
6031 {
6032     local flavor=$1
6033     local cnt
6034
6035     local clients=${CLIENTS:-`hostname`}
6036
6037     for c in ${clients//,/ }; do
6038         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
6039         tmpcnt=`count_flvr "$output" $flavor`
6040         cnt=$((cnt + tmpcnt))
6041     done
6042     echo $cnt
6043 }
6044
6045 flvr_cnt_cli2ost()
6046 {
6047     local flavor=$1
6048     local cnt
6049
6050     local clients=${CLIENTS:-`hostname`}
6051
6052     for c in ${clients//,/ }; do
6053         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
6054         tmpcnt=`count_flvr "$output" $flavor`
6055         cnt=$((cnt + tmpcnt))
6056     done
6057     echo $cnt
6058 }
6059
6060 flvr_cnt_mdt2mdt()
6061 {
6062     local flavor=$1
6063     local cnt=0
6064
6065     if [ $MDSCOUNT -le 1 ]; then
6066         echo 0
6067         return
6068     fi
6069
6070     for num in `seq $MDSCOUNT`; do
6071         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
6072         tmpcnt=`count_flvr "$output" $flavor`
6073         cnt=$((cnt + tmpcnt))
6074     done
6075     echo $cnt;
6076 }
6077
6078 flvr_cnt_mdt2ost()
6079 {
6080     local flavor=$1
6081     local cnt=0
6082     local mdtosc
6083
6084     for num in `seq $MDSCOUNT`; do
6085         mdtosc=$(get_mdtosc_proc_path mds$num)
6086         mdtosc=${mdtosc/-MDT*/-MDT\*}
6087         output=$(do_facet mds$num lctl get_param -n \
6088             osc.$mdtosc.$PROC_CLI 2>/dev/null)
6089         tmpcnt=`count_flvr "$output" $flavor`
6090         cnt=$((cnt + tmpcnt))
6091     done
6092     echo $cnt;
6093 }
6094
6095 flvr_cnt_mgc2mgs()
6096 {
6097     local flavor=$1
6098
6099     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
6100     count_flvr "$output" $flavor
6101 }
6102
6103 do_check_flavor()
6104 {
6105     local dir=$1        # from to
6106     local flavor=$2     # flavor expected
6107     local res=0
6108
6109     if [ $dir == "cli2mdt" ]; then
6110         res=`flvr_cnt_cli2mdt $flavor`
6111     elif [ $dir == "cli2ost" ]; then
6112         res=`flvr_cnt_cli2ost $flavor`
6113     elif [ $dir == "mdt2mdt" ]; then
6114         res=`flvr_cnt_mdt2mdt $flavor`
6115     elif [ $dir == "mdt2ost" ]; then
6116         res=`flvr_cnt_mdt2ost $flavor`
6117     elif [ $dir == "all2ost" ]; then
6118         res1=`flvr_cnt_mdt2ost $flavor`
6119         res2=`flvr_cnt_cli2ost $flavor`
6120         res=$((res1 + res2))
6121     elif [ $dir == "all2mdt" ]; then
6122         res1=`flvr_cnt_mdt2mdt $flavor`
6123         res2=`flvr_cnt_cli2mdt $flavor`
6124         res=$((res1 + res2))
6125     elif [ $dir == "all2all" ]; then
6126         res1=`flvr_cnt_mdt2ost $flavor`
6127         res2=`flvr_cnt_cli2ost $flavor`
6128         res3=`flvr_cnt_mdt2mdt $flavor`
6129         res4=`flvr_cnt_cli2mdt $flavor`
6130         res=$((res1 + res2 + res3 + res4))
6131     fi
6132
6133     echo $res
6134 }
6135
6136 wait_flavor()
6137 {
6138     local dir=$1        # from to
6139     local flavor=$2     # flavor expected
6140     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
6141
6142     local res=0
6143
6144     for ((i=0;i<20;i++)); do
6145         echo -n "checking $dir..."
6146         res=$(do_check_flavor $dir $flavor)
6147         echo "found $res/$expect $flavor connections"
6148         [ $res -ge $expect ] && return 0
6149         sleep 4
6150     done
6151
6152     echo "Error checking $flavor of $dir: expect $expect, actual $res"
6153     return 1
6154 }
6155
6156 restore_to_default_flavor()
6157 {
6158     local proc="mgs.MGS.live.$FSNAME"
6159
6160     echo "restoring to default flavor..."
6161
6162     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
6163
6164     # remove all existing rules if any
6165     if [ $nrule -ne 0 ]; then
6166         echo "$nrule existing rules"
6167         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
6168             echo "remove rule: $rule"
6169             spec=`echo $rule | awk -F = '{print $1}'`
6170             do_facet mgs "$LCTL conf_param -d $spec"
6171         done
6172     fi
6173
6174     # verify no rules left
6175     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
6176     [ $nrule -ne 0 ] && error "still $nrule rules left"
6177
6178     # wait for default flavor to be applied
6179     # currently default flavor for all connections are 'null'
6180     wait_flavor all2all null
6181     echo "now at default flavor settings"
6182 }
6183
6184 set_flavor_all()
6185 {
6186     local flavor=${1:-null}
6187
6188     echo "setting all flavor to $flavor"
6189
6190     # FIXME need parameter to this fn
6191     # and remove global vars
6192     local cnt_all2all=$(calc_connection_cnt all2all)
6193
6194     local res=$(do_check_flavor all2all $flavor)
6195     if [ $res -eq $cnt_all2all ]; then
6196         echo "already have total $res $flavor connections"
6197         return
6198     fi
6199
6200     echo "found $res $flavor out of total $cnt_all2all connections"
6201     restore_to_default_flavor
6202
6203     [[ $flavor = null ]] && return 0
6204
6205     set_rule $FSNAME any any $flavor
6206     wait_flavor all2all $flavor
6207 }
6208
6209
6210 check_logdir() {
6211     local dir=$1
6212     # Checking for shared logdir
6213     if [ ! -d $dir ]; then
6214         # Not found. Create local logdir
6215         mkdir -p $dir
6216     else
6217         touch $dir/check_file.$(hostname -s)
6218     fi
6219     return 0
6220 }
6221
6222 check_write_access() {
6223         local dir=$1
6224         local list=${2:-$(comma_list $(nodes_list))}
6225         local node
6226         local file
6227
6228         for node in ${list//,/ }; do
6229                 file=$dir/check_file.$(short_nodename $node)
6230                 if [[ ! -f "$file" ]]; then
6231                         # Logdir not accessible/writable from this node.
6232                         return 1
6233                 fi
6234                 rm -f $file || return 1
6235         done
6236         return 0
6237 }
6238
6239 init_logging() {
6240     if [[ -n $YAML_LOG ]]; then
6241         return
6242     fi
6243     local SAVE_UMASK=`umask`
6244     umask 0000
6245
6246     export YAML_LOG=${LOGDIR}/results.yml
6247     mkdir -p $LOGDIR
6248     init_clients_lists
6249
6250     if [ ! -f $YAML_LOG ]; then       # If the yaml log already exists then we will just append to it
6251       if check_shared_dir $LOGDIR; then
6252           touch $LOGDIR/shared
6253           echo "Logging to shared log directory: $LOGDIR"
6254       else
6255           echo "Logging to local directory: $LOGDIR"
6256       fi
6257
6258       yml_nodes_file $LOGDIR >> $YAML_LOG
6259       yml_results_file >> $YAML_LOG
6260     fi
6261
6262     umask $SAVE_UMASK
6263 }
6264
6265 log_test() {
6266     yml_log_test $1 >> $YAML_LOG
6267 }
6268
6269 log_test_status() {
6270      yml_log_test_status $@ >> $YAML_LOG
6271 }
6272
6273 log_sub_test_begin() {
6274     yml_log_sub_test_begin "$@" >> $YAML_LOG
6275 }
6276
6277 log_sub_test_end() {
6278     yml_log_sub_test_end "$@" >> $YAML_LOG
6279 }
6280
6281 run_llverdev()
6282 {
6283         local dev=$1
6284         local llverdev_opts=$2
6285         local devname=$(basename $1)
6286         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
6287         # loop devices aren't in /proc/partitions
6288         [ "x$size" == "x" ] && local size=$(ls -l $dev | awk '{print $5}')
6289
6290         size=$(($size / 1024 / 1024)) # Gb
6291
6292         local partial_arg=""
6293         # Run in partial (fast) mode if the size
6294         # of a partition > 1 GB
6295         [ $size -gt 1 ] && partial_arg="-p"
6296
6297         llverdev --force $partial_arg $llverdev_opts $dev
6298 }
6299
6300 run_llverfs()
6301 {
6302         local dir=$1
6303         local llverfs_opts=$2
6304         local use_partial_arg=$3
6305         local partial_arg=""
6306         local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB
6307
6308         # Run in partial (fast) mode if the size
6309         # of a partition > 1 GB
6310         [ "x$use_partial_arg" != "xno" ] && [ $size -gt 1 ] && partial_arg="-p"
6311
6312         llverfs $partial_arg $llverfs_opts $dir
6313 }
6314
6315 #Remove objects from OST
6316 remove_ost_objects() {
6317         local facet=$1
6318         local ostdev=$2
6319         local group=$3
6320         shift 3
6321         local objids="$@"
6322         local mntpt=$(facet_mntpt $facet)
6323         local opts=$OST_MOUNT_OPTS
6324         local i
6325         local rc
6326
6327         echo "removing objects from $ostdev on $facet: $objids"
6328         if ! test -b $ostdev; then
6329                 opts=$(csa_add "$opts" -o loop)
6330         fi
6331         mount -t $(facet_fstype $facet) $opts $ostdev $mntpt ||
6332                 return $?
6333         rc=0
6334         for i in $objids; do
6335                 rm $mntpt/O/$group/d$((i % 32))/$i || { rc=$?; break; }
6336         done
6337         umount -f $mntpt || return $?
6338         return $rc
6339 }
6340
6341 #Remove files from MDT
6342 remove_mdt_files() {
6343         local facet=$1
6344         local mdtdev=$2
6345         shift 2
6346         local files="$@"
6347         local mntpt=$(facet_mntpt $facet)
6348         local opts=$MDS_MOUNT_OPTS
6349
6350         echo "removing files from $mdtdev on $facet: $files"
6351         if [ $(facet_fstype $facet) == ldiskfs ] &&
6352            ! do_facet $facet test -b $mdtdev; then
6353                 opts=$(csa_add "$opts" -o loop)
6354         fi
6355         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
6356                 return $?
6357         rc=0
6358         for f in $files; do
6359                 rm $mntpt/ROOT/$f || { rc=$?; break; }
6360         done
6361         umount -f $mntpt || return $?
6362         return $rc
6363 }
6364
6365 duplicate_mdt_files() {
6366         local facet=$1
6367         local mdtdev=$2
6368         shift 2
6369         local files="$@"
6370         local mntpt=$(facet_mntpt $facet)
6371         local opts=$MDS_MOUNT_OPTS
6372
6373         echo "duplicating files on $mdtdev on $facet: $files"
6374         mkdir -p $mntpt || return $?
6375         if [ $(facet_fstype $facet) == ldiskfs ] &&
6376            ! do_facet $facet test -b $mdtdev; then
6377                 opts=$(csa_add "$opts" -o loop)
6378         fi
6379         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
6380                 return $?
6381
6382     do_umount() {
6383         trap 0
6384         popd > /dev/null
6385         rm $tmp
6386         umount -f $mntpt
6387     }
6388     trap do_umount EXIT
6389
6390     tmp=$(mktemp $TMP/setfattr.XXXXXXXXXX)
6391     pushd $mntpt/ROOT > /dev/null || return $?
6392     rc=0
6393     for f in $files; do
6394         touch $f.bad || return $?
6395         getfattr -n trusted.lov $f | sed "s#$f#&.bad#" > $tmp
6396         rc=${PIPESTATUS[0]}
6397         [ $rc -eq 0 ] || return $rc
6398         setfattr --restore $tmp || return $?
6399     done
6400     do_umount
6401 }
6402
6403 run_sgpdd () {
6404     local devs=${1//,/ }
6405     shift
6406     local params=$@
6407     local rslt=$TMP/sgpdd_survey
6408
6409     # sgpdd-survey cleanups ${rslt}.* files
6410
6411     local cmd="rslt=$rslt $params scsidevs=\"$devs\" $SGPDDSURVEY"
6412     echo + $cmd
6413     eval $cmd
6414     cat ${rslt}.detail
6415 }
6416
6417 # returns the canonical name for an ldiskfs device
6418 ldiskfs_canon() {
6419         local dev="$1"
6420         local facet="$2"
6421
6422         do_facet $facet "dv=\\\$(lctl get_param -n $dev);
6423 if foo=\\\$(lvdisplay -c \\\$dv 2>/dev/null); then
6424     echo dm-\\\${foo##*:};
6425 else
6426     echo \\\$(basename \\\$dv);
6427 fi;"
6428 }
6429
6430 is_sanity_benchmark() {
6431     local benchmarks="dbench bonnie iozone fsx"
6432     local suite=$1
6433     for b in $benchmarks; do
6434         if [ "$b" == "$suite" ]; then
6435             return 0
6436         fi
6437     done
6438     return 1
6439 }
6440
6441 min_ost_size () {
6442     $LCTL get_param -n osc.*.kbytesavail | sort -n | head -n1
6443 }
6444
6445 #
6446 # Get the available size (KB) of a given obd target.
6447 #
6448 get_obd_size() {
6449         local facet=$1
6450         local obd=$2
6451         local size
6452
6453         [[ $facet != client ]] || return 0
6454
6455         size=$(do_facet $facet $LCTL get_param -n *.$obd.kbytesavail | head -n1)
6456         echo -n $size
6457 }
6458
6459 #
6460 # Get the page size (bytes) on a given facet node.
6461 #
6462 get_page_size() {
6463         local facet=$1
6464         local size
6465
6466         size=$(do_facet $facet getconf PAGE_SIZE)
6467         [[ ${PIPESTATUS[0]} = 0 && -n "$size" ]] || size=4096
6468         echo -n $size
6469 }
6470
6471 #
6472 # Get the block count of the filesystem.
6473 #
6474 get_block_count() {
6475         local facet=$1
6476         local device=$2
6477         local count
6478
6479         count=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
6480                 awk '/^Block count:/ {print $3}')
6481         echo -n $count
6482 }
6483
6484 # Get the block size of the filesystem.
6485 get_block_size() {
6486     local facet=$1
6487     local device=$2
6488     local size
6489
6490     size=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
6491            awk '/^Block size:/ {print $3}')
6492     echo $size
6493 }
6494
6495 # Check whether the "large_xattr" feature is enabled or not.
6496 large_xattr_enabled() {
6497         [[ $(facet_fstype $SINGLEMDS) == zfs ]] && return 0
6498
6499         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
6500
6501         do_facet $SINGLEMDS "$DUMPE2FS -h $mds_dev 2>&1 |
6502                 grep -E -q '(ea_inode|large_xattr)'"
6503         return ${PIPESTATUS[0]}
6504 }
6505
6506 # Get the maximum xattr size supported by the filesystem.
6507 max_xattr_size() {
6508     local size
6509
6510     if large_xattr_enabled; then
6511         # include/linux/limits.h: #define XATTR_SIZE_MAX 65536
6512         size=65536
6513     else
6514         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
6515         local block_size=$(get_block_size $SINGLEMDS $mds_dev)
6516
6517         # maximum xattr size = size of block - size of header -
6518         #                      size of 1 entry - 4 null bytes
6519         size=$((block_size - 32 - 32 - 4))
6520     fi
6521
6522     echo $size
6523 }
6524
6525 # Dump the value of the named xattr from a file.
6526 get_xattr_value() {
6527     local xattr_name=$1
6528     local file=$2
6529
6530     echo "$(getfattr -n $xattr_name --absolute-names --only-values $file)"
6531 }
6532
6533 # Generate a string with size of $size bytes.
6534 generate_string() {
6535     local size=${1:-1024} # in bytes
6536
6537     echo "$(head -c $size < /dev/zero | tr '\0' y)"
6538 }
6539
6540 reformat_external_journal() {
6541         local facet=$1
6542
6543         if [ ! -z ${EJOURNAL} ]; then
6544                 local rcmd="do_facet $facet"
6545
6546                 echo "reformat external journal on $facet:${EJOURNAL}"
6547                 ${rcmd} mke2fs -O journal_dev ${EJOURNAL} || return 1
6548         fi
6549 }
6550
6551 # MDT file-level backup/restore
6552 mds_backup_restore() {
6553         local facet=$1
6554         local igif=$2
6555         local devname=$(mdsdevname $(facet_number $facet))
6556         local mntpt=$(facet_mntpt brpt)
6557         local rcmd="do_facet $facet"
6558         local metaea=${TMP}/backup_restore.ea
6559         local metadata=${TMP}/backup_restore.tgz
6560         local opts=${MDS_MOUNT_OPTS}
6561         local svc=${facet}_svc
6562
6563         if ! ${rcmd} test -b ${devname}; then
6564                 opts=$(csa_add "$opts" -o loop)
6565         fi
6566
6567         echo "file-level backup/restore on $facet:${devname}"
6568
6569         # step 1: build mount point
6570         ${rcmd} mkdir -p $mntpt
6571         # step 2: cleanup old backup
6572         ${rcmd} rm -f $metaea $metadata
6573         # step 3: mount dev
6574         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
6575         if [ ! -z $igif ]; then
6576                 # step 3.5: rm .lustre
6577                 ${rcmd} rm -rf $mntpt/ROOT/.lustre || return 1
6578         fi
6579         # step 4: backup metaea
6580         echo "backup EA"
6581         ${rcmd} "cd $mntpt && getfattr -R -d -m '.*' -P . > $metaea && cd -" ||
6582                 return 2
6583         # step 5: backup metadata
6584         echo "backup data"
6585         ${rcmd} tar zcf $metadata -C $mntpt/ . > /dev/null 2>&1 || return 3
6586         # step 6: umount
6587         ${rcmd} umount -d $mntpt || return 4
6588         # step 7: reformat external journal if needed
6589         reformat_external_journal $facet || return 5
6590         # step 8: reformat dev
6591         echo "reformat new device"
6592         add $facet $(mkfs_opts $facet ${devname}) --backfstype ldiskfs \
6593                 --reformat ${devname} $(mdsvdevname $(facet_number $facet)) \
6594                 > /dev/null || exit 6
6595         # step 9: mount dev
6596         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 7
6597         # step 10: restore metadata
6598         echo "restore data"
6599         ${rcmd} tar zxfp $metadata -C $mntpt > /dev/null 2>&1 || return 8
6600         # step 11: restore metaea
6601         echo "restore EA"
6602         ${rcmd} "cd $mntpt && setfattr --restore=$metaea && cd - " || return 9
6603         # step 12: remove recovery logs
6604         echo "remove recovery logs"
6605         ${rcmd} rm -fv $mntpt/OBJECTS/* $mntpt/CATALOGS
6606         # step 13: umount dev
6607         ${rcmd} umount -d $mntpt || return 10
6608         # step 14: cleanup tmp backup
6609         ${rcmd} rm -f $metaea $metadata
6610         # step 15: reset device label - it's not virgin on
6611         ${rcmd} e2label $devname ${!svc}
6612 }
6613
6614 # remove OI files
6615 mds_remove_ois() {
6616         local facet=$1
6617         local idx=$2
6618         local devname=$(mdsdevname $(facet_number $facet))
6619         local mntpt=$(facet_mntpt brpt)
6620         local rcmd="do_facet $facet"
6621         local opts=${MDS_MOUNT_OPTS}
6622
6623         if ! ${rcmd} test -b ${devname}; then
6624                 opts=$(csa_add "$opts" -o loop)
6625         fi
6626
6627         echo "removing OI files on $facet: idx=${idx}"
6628
6629         # step 1: build mount point
6630         ${rcmd} mkdir -p $mntpt
6631         # step 2: mount dev
6632         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
6633         if [ -z $idx ]; then
6634                 # step 3: remove all OI files
6635                 ${rcmd} rm -fv $mntpt/oi.16*
6636         elif [ $idx -lt 2 ]; then
6637                 ${rcmd} rm -fv $mntpt/oi.16.${idx}
6638         else
6639                 local i
6640
6641                 # others, rm oi.16.[idx, idx * idx, idx ** ...]
6642                 for ((i=${idx}; i<64; i=$((i * idx)))); do
6643                         ${rcmd} rm -fv $mntpt/oi.16.${i}
6644                 done
6645         fi
6646         # step 4: umount
6647         ${rcmd} umount -d $mntpt || return 2
6648         # OI files will be recreated when mounted as lustre next time.
6649 }
6650
6651 # generate maloo upload-able log file name
6652 # \param logname specify unique part of file name
6653 generate_logname() {
6654         local logname=${1:-"default_logname"}
6655
6656         echo "$TESTLOG_PREFIX.$TESTNAME.$logname.$(hostname -s).log"
6657 }
6658
6659 # make directory on different MDTs
6660 test_mkdir() {
6661         local option
6662         local parent
6663         local child
6664         local path
6665         local rc=0
6666
6667         case $# in
6668                 1) path=$1;;
6669                 2) option=$1
6670                    path=$2;;
6671                 *) error "Only creating single directory is supported";;
6672         esac
6673
6674         child=$(basename $path)
6675         parent=$(dirname $path)
6676
6677         if [ "$option" == "-p" -a -d $parent/$child ]; then
6678                 return $rc
6679         fi
6680
6681         if [ ! -d ${parent} ]; then
6682                 if [ "$option" == "-p" ]; then
6683                         mkdir -p ${parent}
6684                 else
6685                         return 1
6686                 fi
6687         fi
6688
6689         if [ $MDSCOUNT -le 1 ]; then
6690                 mkdir $option $parent/$child || rc=$?
6691         else
6692                 local mdt_idx=$($LFS getstripe -M $parent)
6693                 local test_num=$(echo $testnum | sed -e 's/[^0-9]*//g')
6694
6695                 if [ "$mdt_idx" -ne 0 ]; then
6696                         mkdir $option $parent/$child || rc=$?
6697                 else
6698                         mdt_idx=$((test_num % MDSCOUNT))
6699                         echo "mkdir $mdt_idx for $parent/$child"
6700                         $LFS setdirstripe -i $mdt_idx $parent/$child || rc=$?
6701                 fi
6702         fi
6703         return $rc
6704 }
6705
6706 # find the smallest and not in use file descriptor
6707 free_fd()
6708 {
6709         local max_fd=$(ulimit -n)
6710         local fd=3
6711         while [[ $fd -le $max_fd && -e /proc/self/fd/$fd ]]; do
6712                 ((++fd))
6713         done
6714         [ $fd -lt $max_fd ] || error "finding free file descriptor failed"
6715         echo $fd
6716 }