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