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