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