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