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