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