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