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