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