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