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