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