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