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