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