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