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