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