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