Whamcloud - gitweb
9146697644458e82d8fcdd9c607935b1b62f8168
[fs/lustre-release.git] / lustre / tests / test-framework.sh
1 #!/bin/bash
2 # vim:expandtab:shiftwidth=4:softtabstop=4:tabstop=4:
3
4 trap 'print_summary && touch $TF_FAIL && \
5     echo "test-framework exiting on error"' ERR
6 set -e
7 #set -x
8
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
19 # LOAD_LLOOP: LU-409: only load llite_lloop module if kernel < 2.6.32 or
20 #             LOAD_LLOOP is true. LOAD_LLOOP is false by default.
21 export LOAD_LLOOP=${LOAD_LLOOP:-false}
22
23 #export PDSH="pdsh -S -Rssh -w"
24
25 # function used by scripts run on remote nodes
26 LUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}
27 . $LUSTRE/tests/functions.sh
28 . $LUSTRE/tests/yaml.sh
29
30 LUSTRE_TESTS_CFG_DIR=${LUSTRE_TESTS_CFG_DIR:-${LUSTRE}/tests/cfg}
31
32 EXCEPT_LIST_FILE=${EXCEPT_LIST_FILE:-${LUSTRE_TESTS_CFG_DIR}/tests-to-skip.sh}
33
34 if [ -f "$EXCEPT_LIST_FILE" ]; then
35     echo "Reading test skip list from $EXCEPT_LIST_FILE"
36     cat $EXCEPT_LIST_FILE
37     . $EXCEPT_LIST_FILE
38 fi
39
40 # check config files for options in decreasing order of preference
41 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/lustre.conf ] &&
42     MODPROBECONF=/etc/modprobe.d/lustre.conf
43 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/Lustre ] &&
44     MODPROBECONF=/etc/modprobe.d/Lustre
45 [ -z "$MODPROBECONF" -a -f /etc/modprobe.conf ] &&
46     MODPROBECONF=/etc/modprobe.conf
47
48 assert_DIR () {
49     local failed=""
50     [[ $DIR/ = $MOUNT/* ]] || \
51         { failed=1 && echo "DIR=$DIR not in $MOUNT. Aborting."; }
52     [[ $DIR1/ = $MOUNT1/* ]] || \
53         { failed=1 && echo "DIR1=$DIR1 not in $MOUNT1. Aborting."; }
54     [[ $DIR2/ = $MOUNT2/* ]] || \
55         { failed=1 && echo "DIR2=$DIR2 not in $MOUNT2. Aborting"; }
56
57     [ -n "$failed" ] && exit 99 || true
58 }
59
60 usage() {
61     echo "usage: $0 [-r] [-f cfgfile]"
62     echo "       -r: reformat"
63
64     exit
65 }
66
67 print_summary () {
68     trap 0
69     [ "$TESTSUITE" == "lfsck" ] && return 0
70     [ -n "$ONLY" ] && echo "WARNING: ONLY is set to $(echo $ONLY)"
71     local details
72     local form="%-13s %-17s %-9s %s %s\n"
73     printf "$form" "status" "script" "Total(sec)" "E(xcluded) S(low)"
74     echo "------------------------------------------------------------------------------------"
75     for O in $DEFAULT_SUITES; do
76         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
77         [ "${!O}" = "no" ] && continue || true
78         local o=$(echo $O  | tr "[:upper:]_" "[:lower:]-")
79         local log=${TMP}/${o}.log
80         if is_sanity_benchmark $o; then
81             log=${TMP}/sanity-benchmark.log
82         fi
83         local slow=
84         local skipped=
85         local total=
86         local status=Unfinished
87         if [ -f $log ]; then
88             skipped=$(grep excluded $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
89             slow=$(egrep "^PASS|^FAIL" $log | tr -d "("| sed s/s\)$//g | sort -nr -k 3  | head -5 |  awk '{ print $2":"$3"s" }')
90             total=$(grep duration $log | awk '{ print $2}')
91             if [ "${!O}" = "done" ]; then
92                 status=Done
93             fi
94             if $DDETAILS; then
95                 local durations=$(egrep "^PASS|^FAIL" $log |  tr -d "("| sed s/s\)$//g | awk '{ print $2":"$3"|" }')
96                 details=$(printf "%s\n%s %s %s\n" "$details" "DDETAILS" "$O" "$(echo $durations)")
97             fi
98         fi
99         printf "$form" $status "$O" "${total}" "E=$skipped"
100         printf "$form" "-" "-" "-" "S=$(echo $slow)"
101     done
102
103     for O in $DEFAULT_SUITES; do
104         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
105         if [ "${!O}" = "no" ]; then
106             printf "$form" "Skipped" "$O" ""
107         fi
108     done
109
110     # print the detailed tests durations if DDETAILS=true
111     if $DDETAILS; then
112         echo "$details"
113     fi
114 }
115
116 init_test_env() {
117     export LUSTRE=`absolute_path $LUSTRE`
118     export TESTSUITE=`basename $0 .sh`
119     export TEST_FAILED=false
120     export FAIL_ON_SKIP_ENV=${FAIL_ON_SKIP_ENV:-false}
121
122     export MKE2FS=${MKE2FS:-mke2fs}
123     export DEBUGFS=${DEBUGFS:-debugfs}
124     export TUNE2FS=${TUNE2FS:-tune2fs}
125     export E2LABEL=${E2LABEL:-e2label}
126     export DUMPE2FS=${DUMPE2FS:-dumpe2fs}
127     export E2FSCK=${E2FSCK:-e2fsck}
128     export LFSCK_BIN=${LFSCK_BIN:-lfsck}
129
130     export LFSCK_ALWAYS=${LFSCK_ALWAYS:-"no"} # check fs after each test suite
131     export FSCK_MAX_ERR=4   # File system errors left uncorrected
132
133     #[ -d /r ] && export ROOT=${ROOT:-/r}
134     export TMP=${TMP:-$ROOT/tmp}
135     export TESTSUITELOG=${TMP}/${TESTSUITE}.log
136     export LOGDIR=${LOGDIR:-${TMP}/test_logs/$(date +%s)}
137     export TESTLOG_PREFIX=$LOGDIR/$TESTSUITE
138
139     export HOSTNAME=${HOSTNAME:-$(hostname -s)}
140     if ! echo $PATH | grep -q $LUSTRE/utils; then
141         export PATH=$LUSTRE/utils:$PATH
142     fi
143     if ! echo $PATH | grep -q $LUSTRE/utils/gss; then
144         export PATH=$LUSTRE/utils/gss:$PATH
145     fi
146     if ! echo $PATH | grep -q $LUSTRE/tests; then
147         export PATH=$LUSTRE/tests:$PATH
148     fi
149     if ! echo $PATH | grep -q $LUSTRE/../lustre-iokit/sgpdd-survey; then
150         export PATH=$LUSTRE/../lustre-iokit/sgpdd-survey:$PATH
151     fi
152     export LST=${LST:-"$LUSTRE/../lnet/utils/lst"}
153     [ ! -f "$LST" ] && export LST=$(which lst)
154     export SGPDDSURVEY=${SGPDDSURVEY:-"$LUSTRE/../lustre-iokit/sgpdd-survey/sgpdd-survey")}
155     [ ! -f "$SGPDDSURVEY" ] && export SGPDDSURVEY=$(which sgpdd-survey)
156     # Ubuntu, at least, has a truncate command in /usr/bin
157     # so fully path our truncate command.
158     export TRUNCATE=${TRUNCATE:-$LUSTRE/tests/truncate}
159     export MDSRATE=${MDSRATE:-"$LUSTRE/tests/mpi/mdsrate"}
160     [ ! -f "$MDSRATE" ] && export MDSRATE=$(which mdsrate 2> /dev/null)
161     if ! echo $PATH | grep -q $LUSTRE/tests/racer; then
162         export PATH=$LUSTRE/tests/racer:$PATH:
163     fi
164     if ! echo $PATH | grep -q $LUSTRE/tests/mpi; then
165         export PATH=$LUSTRE/tests/mpi:$PATH
166     fi
167     export RSYNC_RSH=${RSYNC_RSH:-rsh}
168     export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
169     [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
170     export LFS=${LFS:-"$LUSTRE/utils/lfs"}
171     [ ! -f "$LFS" ] && export LFS=$(which lfs)
172     export L_GETIDENTITY=${L_GETIDENTITY:-"$LUSTRE/utils/l_getidentity"}
173     if [ ! -f "$L_GETIDENTITY" ]; then
174         if `which l_getidentity > /dev/null 2>&1`; then
175             export L_GETIDENTITY=$(which l_getidentity)
176         else
177             export L_GETIDENTITY=NONE
178         fi
179     fi
180     export LL_DECODE_FILTER_FID=${LL_DECODE_FILTER_FID:-"$LUSTRE/utils/ll_decode_filter_fid"}
181     [ ! -f "$LL_DECODE_FILTER_FID" ] && export LL_DECODE_FILTER_FID=$(which ll_decode_filter_fid)
182     export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
183     [ ! -f "$MKFS" ] && export MKFS=$(which mkfs.lustre)
184     export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
185     [ ! -f "$TUNEFS" ] && export TUNEFS=$(which tunefs.lustre)
186     export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
187     export LUSTRE_RMMOD=${LUSTRE_RMMOD:-$LUSTRE/scripts/lustre_rmmod}
188     [ ! -f "$LUSTRE_RMMOD" ] && export LUSTRE_RMMOD=$(which lustre_rmmod 2> /dev/null)
189     export FSTYPE=${FSTYPE:-"ldiskfs"}
190     export NAME=${NAME:-local}
191     export LGSSD=${LGSSD:-"$LUSTRE/utils/gss/lgssd"}
192     [ "$GSS_PIPEFS" = "true" ] && [ ! -f "$LGSSD" ] && \
193         export LGSSD=$(which lgssd)
194     export LSVCGSSD=${LSVCGSSD:-"$LUSTRE/utils/gss/lsvcgssd"}
195     [ ! -f "$LSVCGSSD" ] && export LSVCGSSD=$(which lsvcgssd 2> /dev/null)
196     export KRB5DIR=${KRB5DIR:-"/usr/kerberos"}
197     export DIR2
198     export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
199     export AT_MAX_PATH
200
201     if [ "$ACCEPTOR_PORT" ]; then
202         export PORT_OPT="--port $ACCEPTOR_PORT"
203     fi
204
205     case "x$SEC" in
206         xkrb5*)
207             echo "Using GSS/krb5 ptlrpc security flavor"
208             which lgss_keyring > /dev/null 2>&1 || \
209                 error_exit "built with gss disabled! SEC=$SEC"
210             GSS=true
211             GSS_KRB5=true
212             ;;
213     esac
214
215     case "x$IDUP" in
216         xtrue)
217             IDENTITY_UPCALL=true
218             ;;
219         xfalse)
220             IDENTITY_UPCALL=false
221             ;;
222     esac
223     export LOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}
224
225     # Paths on remote nodes, if different
226     export RLUSTRE=${RLUSTRE:-$LUSTRE}
227     export RPWD=${RPWD:-$PWD}
228     export I_MOUNTED=${I_MOUNTED:-"no"}
229     if [ ! -f /lib/modules/$(uname -r)/kernel/fs/lustre/mds.ko -a \
230         ! -f /lib/modules/$(uname -r)/updates/kernel/fs/lustre/mds.ko -a \
231         ! -f `dirname $0`/../mds/mds.ko ]; then
232         export CLIENTMODSONLY=yes
233     fi
234
235     export SHUTDOWN_ATTEMPTS=${SHUTDOWN_ATTEMPTS:-3}
236
237     # command line
238
239     while getopts "rvwf:" opt $*; do
240         case $opt in
241             f) CONFIG=$OPTARG;;
242             r) REFORMAT=--reformat;;
243             v) VERBOSE=true;;
244             w) WRITECONF=writeconf;;
245             \?) usage;;
246         esac
247     done
248
249     shift $((OPTIND - 1))
250     ONLY=${ONLY:-$*}
251
252     # print the durations of each test if "true"
253     DDETAILS=${DDETAILS:-false}
254     [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
255     rm -f $TMP/*active
256 }
257
258 kernel_version() {
259     echo -n $((($1 << 16) | ($2 << 8) | $3))
260 }
261
262 export LINUX_VERSION=$(uname -r | sed -e "s/[-.]/ /3" -e "s/ .*//")
263 export LINUX_VERSION_CODE=$(kernel_version ${LINUX_VERSION//\./ })
264
265 case `uname -r` in
266 2.4.*) EXT=".o"; USE_QUOTA=no; [ ! "$CLIENTONLY" ] && FSTYPE=ext3;;
267     *) EXT=".ko"; USE_QUOTA=yes;;
268 esac
269
270
271 module_loaded () {
272    /sbin/lsmod | grep -q "^\<$1\>"
273 }
274
275 # Load a module on the system where this is running.
276 #
277 # Synopsis: load_module module_name [module arguments for insmod/modprobe]
278 #
279 # If module arguments are not given but MODOPTS_<MODULE> is set, then its value
280 # will be used as the arguments.  Otherwise arguments will be obtained from
281 # /etc/modprobe.conf, from /etc/modprobe.d/Lustre, or else none will be used.
282 #
283 load_module() {
284     local optvar
285     EXT=".ko"
286     module=$1
287     shift
288     BASE=`basename $module $EXT`
289
290     module_loaded ${BASE} && return
291
292     # If no module arguments were passed, get them from $MODOPTS_<MODULE>, else from
293     # modprobe.conf
294     if [ $# -eq 0 ]; then
295         # $MODOPTS_<MODULE>; we could use associative arrays, but that's not in
296         # Bash until 4.x, so we resort to eval.
297         optvar="MODOPTS_$(basename $module | tr a-z A-Z)"
298         eval set -- \$$optvar
299         if [ $# -eq 0 -a -n "$MODPROBECONF" ]; then
300             # Nothing in $MODOPTS_<MODULE>; try modprobe.conf
301             set -- $(grep -P "^options\\s+${BASE}" $MODPROBECONF)
302             # Get rid of "options $module"
303             (($# > 0)) && shift 2
304
305             # Ensure we have accept=all for lnet
306             if [ $(basename $module) = lnet ]; then
307                 # OK, this is a bit wordy...
308                 local arg accept_all_present=false
309                 for arg in "$@"; do
310                     [ "$arg" = accept=all ] && accept_all_present=true
311                 done
312                 $accept_all_present || set -- "$@" accept=all
313             fi
314         fi
315     fi
316
317     [ $# -gt 0 ] && echo "${module} options: '$*'"
318
319     # Note that insmod will ignore anything in modprobe.conf, which is why we're
320     # passing options on the command-line.
321     if [ "$BASE" == "lnet_selftest" ] && \
322             [ -f ${LUSTRE}/../lnet/selftest/${module}${EXT} ]; then
323         insmod ${LUSTRE}/../lnet/selftest/${module}${EXT}
324     elif [ -f ${LUSTRE}/${module}${EXT} ]; then
325         insmod ${LUSTRE}/${module}${EXT} "$@"
326     else
327         # must be testing a "make install" or "rpm" installation
328         # note failed to load ptlrpc_gss is considered not fatal
329         if [ "$BASE" == "ptlrpc_gss" ]; then
330             modprobe $BASE "$@" 2>/dev/null || echo "gss/krb5 is not supported"
331         else
332             modprobe $BASE "$@"
333         fi
334     fi
335 }
336
337 llite_lloop_enabled() {
338     local n1=$(uname -r | cut -d. -f1)
339     local n2=$(uname -r | cut -d. -f2)
340     local n3=$(uname -r | cut -d- -f1 | cut -d. -f3)
341
342     # load the llite_lloop module for < 2.6.32 kernels
343     if [[ $n1 -lt 2 ]] || [[ $n1 -eq 2 && $n2 -lt 6 ]] || \
344        [[ $n1 -eq 2 && $n2 -eq 6 && $n3 -lt 32 ]] || \
345         $LOAD_LLOOP; then
346         return 0
347     fi
348     return 1
349 }
350
351 load_modules_local() {
352     if [ -n "$MODPROBE" ]; then
353         # use modprobe
354         echo "Using modprobe to load modules"
355         return 0
356     fi
357
358     echo Loading modules from $LUSTRE
359     load_module ../libcfs/libcfs/libcfs
360     [ "$PTLDEBUG" ] && lctl set_param debug="$PTLDEBUG"
361     [ "$SUBSYSTEM" ] && lctl set_param subsystem_debug="${SUBSYSTEM# }"
362     load_module ../lnet/lnet/lnet
363     LNETLND=${LNETLND:-"socklnd/ksocklnd"}
364     load_module ../lnet/klnds/$LNETLND
365     load_module lvfs/lvfs
366     load_module obdclass/obdclass
367     load_module ptlrpc/ptlrpc
368     load_module ptlrpc/gss/ptlrpc_gss
369     [ "$USE_QUOTA" = "yes" -a "$LQUOTA" != "no" ] && load_module quota/lquota $LQUOTAOPTS
370     load_module fld/fld
371     load_module fid/fid
372     load_module lmv/lmv
373     load_module mdc/mdc
374     load_module osc/osc
375     load_module lov/lov
376     load_module mgc/mgc
377     if ! client_only; then
378         SYMLIST=/proc/kallsyms
379         grep -q crc16 $SYMLIST || { modprobe crc16 2>/dev/null || true; }
380         grep -q -w jbd $SYMLIST || { modprobe jbd 2>/dev/null || true; }
381         grep -q -w jbd2 $SYMLIST || { modprobe jbd2 2>/dev/null || true; }
382         if [ "$FSTYPE" = "ldiskfs" ]; then
383             grep -q exportfs_decode_fh $SYMLIST ||
384                 { modprobe exportfs 2> /dev/null || true; }
385             load_module ../ldiskfs/ldiskfs/ldiskfs
386         fi
387         load_module mgs/mgs
388         load_module mds/mds
389         load_module mdd/mdd
390         load_module mdt/mdt
391         load_module lvfs/fsfilt_$FSTYPE
392         load_module cmm/cmm
393         load_module osd-ldiskfs/osd_ldiskfs
394         load_module ost/ost
395         load_module obdfilter/obdfilter
396     fi
397
398
399     load_module llite/lustre
400     llite_lloop_enabled && load_module llite/llite_lloop
401     [ -d /r ] && OGDB=${OGDB:-"/r/tmp"}
402     OGDB=${OGDB:-$TMP}
403     rm -f $OGDB/ogdb-$HOSTNAME
404     $LCTL modules > $OGDB/ogdb-$HOSTNAME
405
406     # 'mount' doesn't look in $PATH, just sbin
407     if [ -f $LUSTRE/utils/mount.lustre ] && \
408        ! grep -qe "/sbin/mount\.lustre " /proc/mounts; then
409         [ ! -f /sbin/mount.lustre ] && touch /sbin/mount.lustre
410         mount --bind $LUSTRE/utils/mount.lustre /sbin/mount.lustre || true
411     fi
412 }
413
414 load_modules () {
415     load_modules_local
416     # bug 19124
417     # load modules on remote nodes optionally
418     # lustre-tests have to be installed on these nodes
419     if $LOAD_MODULES_REMOTE ; then
420         local list=$(comma_list $(remote_nodes_list))
421         echo loading modules on $list
422         do_rpc_nodes $list load_modules 
423     fi
424 }
425
426 check_mem_leak () {
427     LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
428     LEAK_PORTALS=$(dmesg | tail -n 20 | grep "Portals memory leaked" || true)
429     if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
430         echo "$LEAK_LUSTRE" 1>&2
431         echo "$LEAK_PORTALS" 1>&2
432         mv $TMP/debug $TMP/debug-leak.`date +%s` || true
433         echo "Memory leaks detected"
434         [ -n "$IGNORE_LEAK" ] && { echo "ignoring leaks" && return 0; } || true
435         return 1
436     fi
437 }
438
439 unload_modules() {
440     wait_exit_ST client # bug 12845
441
442     $LUSTRE_RMMOD $FSTYPE || return 2
443
444     if $LOAD_MODULES_REMOTE ; then
445         local list=$(comma_list $(remote_nodes_list))
446         if [ ! -z $list ]; then
447             echo unloading modules on $list
448             do_rpc_nodes $list $LUSTRE_RMMOD $FSTYPE
449             do_rpc_nodes $list check_mem_leak
450         fi
451     fi
452
453     if grep -qe "/sbin/mount\.lustre" /proc/mounts; then
454         umount /sbin/mount.lustre || true
455         [ -w /sbin/mount.lustre -a ! -s /sbin/mount.lustre ] && \
456             rm -f /sbin/mount.lustre || true
457     fi
458
459     check_mem_leak || return 254
460
461     echo "modules unloaded."
462     return 0
463 }
464
465 check_gss_daemon_nodes() {
466     local list=$1
467     dname=$2
468
469     do_nodesv $list "num=\\\$(ps -o cmd -C $dname | grep $dname | wc -l);
470 if [ \\\"\\\$num\\\" -ne 1 ]; then
471     echo \\\$num instance of $dname;
472     exit 1;
473 fi; "
474 }
475
476 check_gss_daemon_facet() {
477     facet=$1
478     dname=$2
479
480     num=`do_facet $facet ps -o cmd -C $dname | grep $dname | wc -l`
481     if [ $num -ne 1 ]; then
482         echo "$num instance of $dname on $facet"
483         return 1
484     fi
485     return 0
486 }
487
488 send_sigint() {
489     local list=$1
490     shift
491     echo Stopping $@ on $list
492     do_nodes $list "killall -2 $@ 2>/dev/null || true"
493 }
494
495 # start gss daemons on all nodes, or
496 # "daemon" on "list" if set
497 start_gss_daemons() {
498     local list=$1
499     local daemon=$2
500
501     if [ "$list" ] && [ "$daemon" ] ; then
502         echo "Starting gss daemon on nodes: $list"
503         do_nodes $list "$daemon" || return 8
504         return 0
505     fi
506
507     local list=$(comma_list $(mdts_nodes))
508
509     echo "Starting gss daemon on mds: $list"
510     do_nodes $list "$LSVCGSSD -v" || return 1
511     if $GSS_PIPEFS; then
512         do_nodes $list "$LGSSD -v" || return 2
513     fi
514
515     list=$(comma_list $(osts_nodes))
516     echo "Starting gss daemon on ost: $list"
517     do_nodes $list "$LSVCGSSD -v" || return 3
518     # starting on clients
519
520     local clients=${CLIENTS:-`hostname`}
521     if $GSS_PIPEFS; then
522         echo "Starting $LGSSD on clients $clients "
523         do_nodes $clients  "$LGSSD -v" || return 4
524     fi
525
526     # wait daemons entering "stable" status
527     sleep 5
528
529     #
530     # check daemons are running
531     #
532     list=$(comma_list $(mdts_nodes) $(osts_nodes))
533     check_gss_daemon_nodes $list lsvcgssd || return 5
534     if $GSS_PIPEFS; then
535         list=$(comma_list $(mdts_nodes))
536         check_gss_daemon_nodes $list lgssd || return 6
537     fi
538     if $GSS_PIPEFS; then
539         check_gss_daemon_nodes $clients lgssd || return 7
540     fi
541 }
542
543 stop_gss_daemons() {
544     local list=$(comma_list $(mdts_nodes))
545     
546     send_sigint $list lsvcgssd lgssd
547
548     list=$(comma_list $(osts_nodes))
549     send_sigint $list lsvcgssd
550
551     list=${CLIENTS:-`hostname`}
552     send_sigint $list lgssd
553 }
554
555 init_gss() {
556     if $GSS; then
557         if ! module_loaded ptlrpc_gss; then
558             load_module ptlrpc/gss/ptlrpc_gss
559             module_loaded ptlrpc_gss ||
560                 error_exit "init_gss : GSS=$GSS, but gss/krb5 is not supported!"
561         fi
562         start_gss_daemons || error_exit "start gss daemon failed! rc=$?"
563
564         if [ -n "$LGSS_KEYRING_DEBUG" ]; then
565             echo $LGSS_KEYRING_DEBUG > /proc/fs/lustre/sptlrpc/gss/lgss_keyring/debug_level
566         fi
567     fi
568 }
569
570 cleanup_gss() {
571     if $GSS; then
572         stop_gss_daemons
573         # maybe cleanup credential cache?
574     fi
575 }
576
577 mdsdevlabel() {
578     local num=$1
579     local device=`mdsdevname $num`
580     local label=`do_facet mds$num "e2label ${device}" | grep -v "CMD: "`
581     echo -n $label
582 }
583
584 ostdevlabel() {
585     local num=$1
586     local device=`ostdevname $num`
587     local label=`do_facet ost$num "e2label ${device}" | grep -v "CMD: "`
588     echo -n $label
589 }
590
591 set_debug_size () {
592     local dz=${1:-$DEBUG_SIZE}
593     local cpus=$(($(cut -d "-" -f 2 /sys/devices/system/cpu/possible)+1))
594
595     # bug 19944, adjust size to be -gt num_possible_cpus()
596     # promise 2MB for every cpu at least
597     if [ -n "$cpus" ] && [ $((cpus * 2)) -gt $dz ]; then
598         dz=$((cpus * 2))
599     fi
600     lctl set_param debug_mb=$dz
601 }
602
603 set_default_debug () {
604     local debug=${1:-"$PTLDEBUG"}
605     local subsys=${2:-"$SUBSYSTEM"}
606     local debug_size=${3:-$DEBUG_SIZE}
607
608     [ -n "$debug" ] && lctl set_param debug="$debug" >/dev/null
609     [ -n "$subsys" ] && lctl set_param subsystem_debug="${subsys# }" >/dev/null
610
611     [ -n "$debug_size" ] && set_debug_size $debug_size > /dev/null
612 }
613
614 set_default_debug_nodes () {
615     local nodes=$1
616
617     if [[ ,$nodes, = *,$HOSTNAME,* ]]; then
618         nodes=$(exclude_items_from_list "$nodes" "$HOSTNAME")
619             set_default_debug
620     fi
621
622     [[ -n $nodes ]] && do_rpc_nodes $nodes set_default_debug \
623         \\\"$PTLDEBUG\\\" \\\"$SUBSYSTEM\\\" $DEBUG_SIZE || true
624 }
625
626 set_default_debug_facet () {
627     local facet=$1
628     local node=$(facet_active_host $facet)
629     [ -z "$node" ] && echo "No host defined for facet $facet" && exit 1
630
631     set_default_debug_nodes $node
632 }
633
634 # Facet functions
635 mount_facets () {
636     local facets=${1:-$(get_facets)}
637     local facet
638
639     for facet in ${facets//,/ }; do
640         mount_facet $facet || error "Restart of $facet failed!"
641     done
642 }
643
644 mount_facet() {
645     local facet=$1
646     shift
647     local dev=$(facet_active $facet)_dev
648     local opt=${facet}_opt
649     local mntpt=$(facet_mntpt $facet)
650
651     echo "Starting ${facet}: ${!opt} $@ ${!dev} $mntpt"
652     do_facet ${facet} "mkdir -p $mntpt; mount -t lustre ${!opt} $@ ${!dev} $mntpt"
653     RC=${PIPESTATUS[0]}
654     if [ $RC -ne 0 ]; then
655         echo "mount -t lustre $@ ${!dev} $mntpt"
656         echo "Start of ${!dev} on ${facet} failed ${RC}"
657     else
658         set_default_debug_facet $facet
659
660         label=$(do_facet ${facet} "$E2LABEL ${!dev}")
661         [ -z "$label" ] && echo no label for ${!dev} && exit 1
662         eval export ${facet}_svc=${label}
663         echo Started ${label}
664     fi
665     return $RC
666 }
667
668 # start facet device options
669 start() {
670     local facet=$1
671     shift
672     local device=$1
673     shift
674     eval export ${facet}_dev=${device}
675     eval export ${facet}_opt=\"$@\"
676
677     local varname=${facet}failover_dev
678     if [ -n "${!varname}" ] ; then
679         eval export ${facet}failover_dev=${!varname}
680     else
681         eval export ${facet}failover_dev=$device
682     fi
683
684     local mntpt=$(facet_mntpt $facet)
685     do_facet ${facet} mkdir -p $mntpt
686     eval export ${facet}_MOUNT=$mntpt
687     mount_facet ${facet}
688     RC=$?
689     return $RC
690 }
691
692 stop() {
693     local running
694     local facet=$1
695     shift
696     local HOST=`facet_active_host $facet`
697     [ -z $HOST ] && echo stop: no host for $facet && return 0
698
699     local mntpt=$(facet_mntpt $facet)
700     running=$(do_facet ${facet} "grep -c $mntpt' ' /proc/mounts") || true
701     if [ ${running} -ne 0 ]; then
702         echo "Stopping $mntpt (opts:$@) on $HOST"
703         do_facet ${facet} umount -d $@ $mntpt
704     fi
705
706     # umount should block, but we should wait for unrelated obd's
707     # like the MGS or MGC to also stop.
708     wait_exit_ST ${facet}
709 }
710
711 # save quota version (both administrative and operational quotas)
712 # add an additional parameter if mountpoint is ever different from $MOUNT
713 quota_save_version() {
714     local fsname=${2:-$FSNAME}
715     local spec=$1
716     local ver=$(tr -c -d "123" <<< $spec)
717     local type=$(tr -c -d "ug" <<< $spec)
718
719     [ -n "$ver" -a "$ver" != "3" ] && error "wrong quota version specifier"
720
721     [ -n "$type" ] && { $LFS quotacheck -$type $MOUNT || error "quotacheck has failed"; }
722
723     do_facet mgs "lctl conf_param ${fsname}-MDT*.mdd.quota_type=$spec"
724     local varsvc
725     local osts=$(get_facets OST)
726     for ost in ${osts//,/ }; do
727         varsvc=${ost}_svc
728         do_facet mgs "lctl conf_param ${!varsvc}.ost.quota_type=$spec"
729     done
730 }
731
732 # client could mount several lustre 
733 quota_type () {
734     local fsname=${1:-$FSNAME}
735     local rc=0
736     do_facet mgs lctl get_param mdd.${fsname}-MDT*.quota_type || rc=$?
737     do_nodes $(comma_list $(osts_nodes)) \
738         lctl get_param obdfilter.${fsname}-OST*.quota_type || rc=$?
739     return $rc 
740 }
741
742 restore_quota_type () {
743    local mntpt=${1:-$MOUNT}
744    local quota_type=$(quota_type $FSNAME | grep MDT | cut -d "=" -f2)
745    if [ ! "$old_QUOTA_TYPE" ] || [ "$quota_type" = "$old_QUOTA_TYPE" ]; then
746         return
747    fi
748    quota_save_version $old_QUOTA_TYPE
749 }
750
751 setup_quota(){
752     local mntpt=$1
753
754     # We need save the original quota_type params, and restore them after testing
755
756     # Suppose that quota type the same on mds and ost
757     local quota_type=$(quota_type | grep MDT | cut -d "=" -f2)
758     [ ${PIPESTATUS[0]} -eq 0 ] || error "quota_type failed!"
759     echo "[HOST:$HOSTNAME] [old_quota_type:$quota_type] [new_quota_type:$QUOTA_TYPE]"
760     if [ "$quota_type" != "$QUOTA_TYPE" ]; then
761         export old_QUOTA_TYPE=$quota_type
762         quota_save_version $QUOTA_TYPE
763     else
764         qtype=$(tr -c -d "ug" <<< $QUOTA_TYPE)
765         $LFS quotacheck -$qtype $mntpt || error "quotacheck has failed for $type"
766     fi
767
768     local quota_usrs=$QUOTA_USERS
769
770     # get_filesystem_size
771     local disksz=$(lfs df $mntpt | grep "filesystem summary:"  | awk '{print $3}')
772     local blk_soft=$((disksz + 1024))
773     local blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over
774
775     local Inodes=$(lfs df -i $mntpt | grep "filesystem summary:"  | awk '{print $3}')
776     local i_soft=$Inodes
777     local i_hard=$((i_soft + i_soft / 20))
778
779     echo "Total disk size: $disksz  block-softlimit: $blk_soft block-hardlimit:
780         $blk_hard inode-softlimit: $i_soft inode-hardlimit: $i_hard"
781
782     local cmd
783     for usr in $quota_usrs; do
784         echo "Setting up quota on $HOSTNAME:$mntpt for $usr..."
785         for type in u g; do
786             cmd="$LFS setquota -$type $usr -b $blk_soft -B $blk_hard -i $i_soft -I $i_hard $mntpt"
787             echo "+ $cmd"
788             eval $cmd || error "$cmd FAILED!"
789         done
790         # display the quota status
791         echo "Quota settings for $usr : "
792         $LFS quota -v -u $usr $mntpt || true
793     done
794 }
795
796 zconf_mount() {
797     local client=$1
798     local mnt=$2
799     local OPTIONS=${3:-$MOUNTOPT}
800
801     local device=$MGSNID:/$FSNAME
802     if [ -z "$mnt" -o -z "$FSNAME" ]; then
803         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
804         exit 1
805     fi
806
807     echo "Starting client: $client: $OPTIONS $device $mnt"
808     do_node $client mkdir -p $mnt
809     do_node $client mount -t lustre $OPTIONS $device $mnt || return 1
810
811     set_default_debug_nodes $client
812
813     return 0
814 }
815
816 zconf_umount() {
817     local client=$1
818     local mnt=$2
819     local force
820     local busy 
821     local need_kill
822
823     [ "$3" ] && force=-f
824     local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
825     if [ $running -ne 0 ]; then
826         echo "Stopping client $client $mnt (opts:$force)"
827         do_node $client lsof -t $mnt || need_kill=no
828         if [ "x$force" != "x" -a "x$need_kill" != "xno" ]; then
829             pids=$(do_node $client lsof -t $mnt | sort -u);
830             if [ -n $pids ]; then
831                 do_node $client kill -9 $pids || true
832             fi
833         fi
834
835         busy=$(do_node $client "umount $force $mnt 2>&1" | grep -c "busy") || true
836         if [ $busy -ne 0 ] ; then
837             echo "$mnt is still busy, wait one second" && sleep 1
838             do_node $client umount $force $mnt
839         fi
840     fi
841 }
842
843 # nodes is comma list
844 sanity_mount_check_nodes () {
845     local nodes=$1
846     shift
847     local mnts="$@"
848     local mnt
849
850     # FIXME: assume that all cluster nodes run the same os
851     [ "$(uname)" = Linux ] || return 0
852
853     local rc=0
854     for mnt in $mnts ; do
855         do_nodes $nodes "running=\\\$(grep -c $mnt' ' /proc/mounts);
856 mpts=\\\$(mount | grep -w -c $mnt);
857 if [ \\\$running -ne \\\$mpts ]; then
858     echo \\\$(hostname) env are INSANE!;
859     exit 1;
860 fi"
861     [ $? -eq 0 ] || rc=1 
862     done
863     return $rc
864 }
865
866 sanity_mount_check_servers () {
867     [ "$CLIENTONLY" ] && 
868         { echo "CLIENTONLY mode, skip mount_check_servers"; return 0; } || true
869     echo Checking servers environments
870
871     # FIXME: modify get_facets to display all facets wo params
872     local facets="$(get_facets OST),$(get_facets MDS),mgs"
873     local node
874     local mntpt
875     local facet
876     for facet in ${facets//,/ }; do
877         node=$(facet_host ${facet})
878         mntpt=$(facet_mntpt $facet)
879         sanity_mount_check_nodes $node $mntpt ||
880             { error "server $node environments are insane!"; return 1; }
881     done
882 }
883
884 sanity_mount_check_clients () {
885     local clients=${1:-$CLIENTS}
886     local mntpt=${2:-$MOUNT}
887     local mntpt2=${3:-$MOUNT2}
888
889     [ -z $clients ] && clients=$(hostname)
890     echo Checking clients $clients environments
891
892     sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
893        error "clients environments are insane!"
894 }
895
896 sanity_mount_check () {
897     sanity_mount_check_servers || return 1
898     sanity_mount_check_clients || return 2
899 }
900
901 # mount clients if not mouted
902 zconf_mount_clients() {
903     local clients=$1
904     local mnt=$2
905     local OPTIONS=${3:-$MOUNTOPT}
906
907     local device=$MGSNID:/$FSNAME
908     if [ -z "$mnt" -o -z "$FSNAME" ]; then
909         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
910         exit 1
911     fi
912
913     echo "Starting client $clients: $OPTIONS $device $mnt"
914
915     do_nodes $clients "
916 running=\\\$(mount | grep -c $mnt' ');
917 rc=0;
918 if [ \\\$running -eq 0 ] ; then
919     mkdir -p $mnt;
920     mount -t lustre $OPTIONS $device $mnt;
921     rc=\\\$?;
922 fi;
923 exit \\\$rc" || return ${PIPESTATUS[0]}
924
925     echo "Started clients $clients: "
926     do_nodes $clients "mount | grep -w $mnt"
927
928     set_default_debug_nodes $clients
929
930     return 0
931 }
932
933 zconf_umount_clients() {
934     local clients=$1
935     local mnt=$2
936     local force
937
938     [ "$3" ] && force=-f
939
940     echo "Stopping clients: $clients $mnt (opts:$force)"
941     do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
942 if [ \\\$running -ne 0 ] ; then
943 echo Stopping client \\\$(hostname) $mnt opts:$force;
944 lsof $mnt || need_kill=no;
945 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
946     pids=\\\$(lsof -t $mnt | sort -u);
947     if [ -n \\\"\\\$pids\\\" ]; then
948              kill -9 \\\$pids;
949     fi
950 fi;
951 while umount $force $mnt 2>&1 | grep -q "busy"; do
952     echo "$mnt is still busy, wait one second" && sleep 1;
953 done;
954 fi"
955 }
956
957 shutdown_node () {
958     local node=$1
959     echo + $POWER_DOWN $node
960     $POWER_DOWN $node
961 }
962
963 shutdown_node_hard () {
964     local host=$1
965     local attempts=$SHUTDOWN_ATTEMPTS
966
967     for i in $(seq $attempts) ; do
968         shutdown_node $host
969         sleep 1
970         wait_for_function --quiet "! ping -w 3 -c 1 $host" 5 1 && return 0
971         echo "waiting for $host to fail attempts=$attempts"
972         [ $i -lt $attempts ] || \
973             { echo "$host still pingable after power down! attempts=$attempts" && return 1; } 
974     done
975 }
976
977 shutdown_client() {
978     local client=$1
979     local mnt=${2:-$MOUNT}
980     local attempts=3
981
982     if [ "$FAILURE_MODE" = HARD ]; then
983         shutdown_node_hard $client
984     else
985        zconf_umount_clients $client $mnt -f
986     fi
987 }
988
989 facets_on_host () {
990     local host=$1
991     local facets="$(get_facets OST),$(get_facets MDS)"
992     local affected
993
994     combined_mgs_mds || facets="$facets,mgs"
995
996     for facet in ${facets//,/ }; do
997         if [ $(facet_active_host $facet) == $host ]; then
998            affected="$affected $facet"
999         fi
1000     done
1001
1002     echo $(comma_list $affected)
1003 }
1004
1005 facet_up () {
1006     local facet=$1
1007     local host=${2:-$(facet_host $facet)}
1008
1009     local label=$(convert_facet2label $facet)
1010     do_node $host lctl dl | awk '{print $4}' | grep -q $label
1011 }
1012
1013 facets_up_on_host () {
1014     local host=$1
1015     local facets=$(facets_on_host $host)
1016     local affected_up
1017
1018     for facet in ${facets//,/ }; do
1019         if $(facet_up $facet $host); then
1020             affected_up="$affected_up $facet"
1021         fi
1022     done
1023
1024     echo $(comma_list $affected_up)
1025 }
1026
1027 shutdown_facet() {
1028     local facet=$1
1029
1030     if [ "$FAILURE_MODE" = HARD ]; then
1031         shutdown_node_hard $(facet_active_host $facet)
1032     else
1033         stop $facet
1034     fi
1035 }
1036
1037 reboot_node() {
1038     local node=$1
1039     echo + $POWER_UP $node
1040     $POWER_UP $node
1041 }
1042
1043 remount_facet() {
1044     local facet=$1
1045
1046     stop $facet
1047     mount_facet $facet
1048 }
1049
1050 reboot_facet() {
1051     local facet=$1
1052     if [ "$FAILURE_MODE" = HARD ]; then
1053         reboot_node $(facet_active_host $facet)
1054     else
1055         sleep 10
1056     fi
1057 }
1058
1059 boot_node() {
1060     local node=$1
1061     if [ "$FAILURE_MODE" = HARD ]; then
1062        reboot_node $node
1063        wait_for_host $node
1064     fi
1065 }
1066
1067 facets_hosts () {
1068     local facets=$1
1069     local hosts
1070
1071     for facet in ${facets//,/ }; do
1072         hosts=$(expand_list $hosts $(facet_host $facet) )
1073     done
1074
1075     echo $hosts
1076 }
1077
1078 _check_progs_installed () {
1079     local progs=$@
1080     local rc=0
1081
1082     for prog in $progs; do
1083         if ! [ "$(which $prog)"  -o  "${!prog}" ]; then
1084            echo $prog missing on $(hostname)
1085            rc=1
1086         fi
1087     done
1088     return $rc
1089 }
1090
1091 check_progs_installed () {
1092     local nodes=$1
1093     shift
1094
1095     do_rpc_nodes $nodes _check_progs_installed $@
1096 }
1097
1098 # recovery-scale functions
1099 node_var_name() {
1100     echo __$(echo $1 | tr '-' '_' | tr '.' '_')
1101 }
1102
1103 start_client_load() {
1104     local client=$1
1105     local load=$2
1106     local var=$(node_var_name $client)_load
1107     eval export ${var}=$load
1108
1109     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
1110                               BREAK_ON_ERROR=$BREAK_ON_ERROR \
1111                               END_RUN_FILE=$END_RUN_FILE \
1112                               LOAD_PID_FILE=$LOAD_PID_FILE \
1113                               TESTLOG_PREFIX=$TESTLOG_PREFIX \
1114                               run_${load}.sh" &
1115     local ppid=$!
1116     log "Started client load: ${load} on $client"
1117
1118     # get the children process IDs
1119     local pids=$(ps --ppid $ppid -o pid= | xargs)
1120     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $ppid $pids"
1121     return 0
1122 }
1123
1124 start_client_loads () {
1125     local -a clients=(${1//,/ })
1126     local numloads=${#CLIENT_LOADS[@]}
1127     local testnum
1128
1129     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
1130         testnum=$((nodenum % numloads))
1131         start_client_load ${clients[nodenum]} ${CLIENT_LOADS[testnum]}
1132     done
1133     # bug 22169: wait the background threads to start
1134     sleep 2
1135 }
1136
1137 # only for remote client 
1138 check_client_load () {
1139     local client=$1
1140     local var=$(node_var_name $client)_load
1141     local TESTLOAD=run_${!var}.sh
1142
1143     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
1144     
1145     # bug 18914: try to connect several times not only when
1146     # check ps, but  while check_catastrophe also
1147     local tries=3
1148     local RC=254
1149     while [ $RC = 254 -a $tries -gt 0 ]; do
1150         let tries=$tries-1
1151         # assume success
1152         RC=0
1153         if ! check_catastrophe $client; then
1154             RC=${PIPESTATUS[0]}
1155             if [ $RC -eq 254 ]; then
1156                 # FIXME: not sure how long we shuold sleep here
1157                 sleep 10
1158                 continue
1159             fi
1160             echo "check catastrophe failed: RC=$RC "
1161             return $RC
1162         fi
1163     done
1164     # We can continue try to connect if RC=254
1165     # Just print the warning about this
1166     if [ $RC = 254 ]; then
1167         echo "got a return status of $RC from do_node while checking catastrophe on $client"
1168     fi
1169
1170     # see if the load is still on the client
1171     tries=3
1172     RC=254
1173     while [ $RC = 254 -a $tries -gt 0 ]; do
1174         let tries=$tries-1
1175         # assume success
1176         RC=0
1177         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
1178             RC=${PIPESTATUS[0]}
1179             sleep 30
1180         fi
1181     done
1182     if [ $RC = 254 ]; then
1183         echo "got a return status of $RC from do_node while checking (catastrophe and 'ps') the client load on $client"
1184         # see if we can diagnose a bit why this is
1185     fi
1186
1187     return $RC
1188 }
1189 check_client_loads () {
1190    local clients=${1//,/ }
1191    local client=
1192    local rc=0
1193
1194    for client in $clients; do
1195       check_client_load $client
1196       rc=${PIPESTATUS[0]}
1197       if [ "$rc" != 0 ]; then
1198         log "Client load failed on node $client, rc=$rc"
1199         return $rc
1200       fi
1201    done
1202 }
1203
1204 restart_client_loads () {
1205     local clients=${1//,/ }
1206     local expectedfail=${2:-""}
1207     local client=
1208     local rc=0
1209
1210     for client in $clients; do
1211         check_client_load $client
1212         rc=${PIPESTATUS[0]}
1213         if [ "$rc" != 0 -a "$expectedfail" ]; then
1214             local var=$(node_var_name $client)_load
1215             start_client_load $client ${!var}
1216             echo "Restarted client load ${!var}: on $client. Checking ..."
1217             check_client_load $client
1218             rc=${PIPESTATUS[0]}
1219             if [ "$rc" != 0 ]; then
1220                 log "Client load failed to restart on node $client, rc=$rc"
1221                 # failure one client load means test fail
1222                 # we do not need to check other 
1223                 return $rc
1224             fi
1225         else
1226             return $rc
1227         fi
1228     done
1229 }
1230 # End recovery-scale functions
1231
1232 # verify that lustre actually cleaned up properly
1233 cleanup_check() {
1234     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
1235         error "LBUG/LASSERT detected"
1236     BUSY=`dmesg | grep -i destruct || true`
1237     if [ "$BUSY" ]; then
1238         echo "$BUSY" 1>&2
1239         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
1240         exit 205
1241     fi
1242
1243     check_mem_leak || exit 204
1244
1245     [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl && \
1246         echo "$0: lustre didn't clean up..." 1>&2 && return 202 || true
1247
1248     if module_loaded lnet || module_loaded libcfs; then
1249         echo "$0: modules still loaded..." 1>&2
1250         /sbin/lsmod 1>&2
1251         return 203
1252     fi
1253     return 0
1254 }
1255
1256 wait_update () {
1257     local node=$1
1258     local TEST=$2
1259     local FINAL=$3
1260     local MAX=${4:-90}
1261
1262         local RESULT
1263         local WAIT=0
1264         local sleep=1
1265         local print=10
1266         while [ true ]; do
1267             RESULT=$(do_node $node "$TEST")
1268             if [ "$RESULT" == "$FINAL" ]; then
1269                 [ -z "$RESULT" -o $WAIT -le $sleep ] ||
1270                     echo "Updated after ${WAIT}s: wanted '$FINAL' got '$RESULT'"
1271                 return 0
1272             fi
1273             [ $WAIT -ge $MAX ] && break
1274             [ $((WAIT % print)) -eq 0 ] &&
1275                 echo "Waiting $((MAX - WAIT)) secs for update"
1276             WAIT=$((WAIT + sleep))
1277             sleep $sleep
1278         done
1279         echo "Update not seen after ${MAX}s: wanted '$FINAL' got '$RESULT'"
1280         return 3
1281 }
1282
1283 wait_update_facet () {
1284     local facet=$1
1285     wait_update  $(facet_active_host $facet) "$@"
1286 }
1287
1288 wait_delete_completed () {
1289     local TOTALPREV=`lctl get_param -n osc.*.kbytesavail | \
1290                      awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1291
1292     local WAIT=0
1293     local MAX_WAIT=20
1294     while [ "$WAIT" -ne "$MAX_WAIT" ]; do
1295         sleep 1
1296         TOTAL=`lctl get_param -n osc.*.kbytesavail | \
1297                awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1298         [ "$TOTAL" -eq "$TOTALPREV" ] && return 0
1299         echo "Waiting delete completed ... prev: $TOTALPREV current: $TOTAL "
1300         TOTALPREV=$TOTAL
1301         WAIT=$(( WAIT + 1))
1302     done
1303     echo "Delete is not completed in $MAX_WAIT sec"
1304     return 1
1305 }
1306
1307 wait_for_host() {
1308     local hostlist=$1
1309
1310     # we can use "for" here because we are waiting the slowest
1311     for host in ${hostlist//,/ }; do
1312         check_network "$host" 900
1313     done
1314     while ! do_nodes $hostlist hostname  > /dev/null; do sleep 5; done
1315 }
1316
1317 wait_for_facet() {
1318     local facetlist=$1
1319     local hostlist
1320
1321     for facet in ${facetlist//,/ }; do
1322         hostlist=$(expand_list $hostlist $(facet_active_host $facet))
1323     done
1324     wait_for_host $hostlist
1325 }
1326
1327 _wait_recovery_complete () {
1328     local param=$1
1329
1330     # Use default policy if $2 is not passed by caller.
1331     local MAX=${2:-$(max_recovery_time)}
1332
1333     local WAIT=0
1334     local STATUS=
1335
1336     while [ $WAIT -lt $MAX ]; do
1337         STATUS=$(lctl get_param -n $param | grep status)
1338         echo $param $STATUS
1339         [[ $STATUS = "status: COMPLETE" || $STATUS = "status: INACTIVE" ]] && return 0
1340         sleep 5
1341         WAIT=$((WAIT + 5))
1342         echo "Waiting $((MAX - WAIT)) secs for $param recovery done. $STATUS"
1343     done
1344     echo "$param recovery not done in $MAX sec. $STATUS"
1345     return 1
1346 }
1347
1348 wait_recovery_complete () {
1349     local facet=$1
1350
1351     # with an assumption that at_max is the same on all nodes
1352     local MAX=${2:-$(max_recovery_time)}
1353
1354     local facets=$facet
1355     if [ "$FAILURE_MODE" = HARD ]; then
1356         facets=$(facets_on_host $(facet_active_host $facet))
1357     fi
1358     echo affected facets: $facets
1359
1360     # we can use "for" here because we are waiting the slowest
1361     for facet in ${facets//,/ }; do
1362         local var_svc=${facet}_svc
1363         local param="*.${!var_svc}.recovery_status"
1364
1365         local host=$(facet_active_host $facet)
1366         do_rpc_nodes $host _wait_recovery_complete $param $MAX
1367     done
1368 }
1369
1370 wait_mds_ost_sync () {
1371     # just because recovery is done doesn't mean we've finished
1372     # orphan cleanup. Wait for llogs to get synchronized.
1373     echo "Waiting for orphan cleanup..."
1374     # MAX value includes time needed for MDS-OST reconnection
1375     local MAX=$(( TIMEOUT * 2 ))
1376     local WAIT=0
1377     while [ $WAIT -lt $MAX ]; do
1378         local -a sync=($(do_nodes $(comma_list $(osts_nodes)) \
1379             "$LCTL get_param -n obdfilter.*.mds_sync"))
1380         local con=1
1381         local i
1382         for ((i=0; i<${#sync[@]}; i++)); do
1383             [ ${sync[$i]} -eq 0 ] && continue
1384             # there is a not finished MDS-OST synchronization
1385             con=0
1386             break;
1387         done
1388         sleep 2 # increase waiting time and cover statfs cache
1389         [ ${con} -eq 1 ] && return 0
1390         echo "Waiting $WAIT secs for $facet mds-ost sync done."
1391         WAIT=$((WAIT + 2))
1392     done
1393     echo "$facet recovery not done in $MAX sec. $STATUS"
1394     return 1
1395 }
1396
1397 wait_destroy_complete () {
1398     echo "Waiting for destroy to be done..."
1399     # MAX value shouldn't be big as this mean server responsiveness
1400     # never increase this just to make test pass but investigate
1401     # why it takes so long time
1402     local MAX=5
1403     local WAIT=0
1404     while [ $WAIT -lt $MAX ]; do
1405         local -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))
1406         local con=1
1407         for ((i=0; i<${#RPCs[@]}; i++)); do
1408             [ ${RPCs[$i]} -eq 0 ] && continue
1409             # there are still some destroy RPCs in flight
1410             con=0
1411             break;
1412         done
1413         sleep 1
1414         [ ${con} -eq 1 ] && return 0 # done waiting
1415         echo "Waiting $WAIT secs for destroys to be done."
1416         WAIT=$((WAIT + 1))
1417     done
1418     echo "Destroys weren't done in $MAX sec."
1419     return 1
1420 }
1421
1422 wait_exit_ST () {
1423     local facet=$1
1424
1425     local WAIT=0
1426     local INTERVAL=1
1427     local running
1428     # conf-sanity 31 takes a long time cleanup
1429     while [ $WAIT -lt 300 ]; do
1430         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
1431         [ -z "${running}" ] && return 0
1432         echo "waited $WAIT for${running}"
1433         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
1434         sleep $INTERVAL
1435         WAIT=$((WAIT + INTERVAL))
1436     done
1437     echo "service didn't stop after $WAIT seconds.  Still running:"
1438     echo ${running}
1439     return 1
1440 }
1441
1442 wait_remote_prog () {
1443    local prog=$1
1444    local WAIT=0
1445    local INTERVAL=5
1446    local rc=0
1447
1448    [ "$PDSH" = "no_dsh" ] && return 0
1449
1450    while [ $WAIT -lt $2 ]; do
1451         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
1452         [ -z "${running}" ] && return 0 || true
1453         echo "waited $WAIT for: "
1454         echo "$running"
1455         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
1456         sleep $INTERVAL
1457         WAIT=$((WAIT + INTERVAL))
1458     done
1459     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
1460     [ -z "$pids" ] && return 0
1461     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
1462     # FIXME: not portable
1463     for pid in $pids; do
1464         cat /proc/${pid}/status || true
1465         cat /proc/${pid}/wchan || true
1466         echo "Killing $pid"
1467         kill -9 $pid || true
1468         sleep 1
1469         ps -P $pid && rc=1
1470     done
1471
1472     return $rc
1473 }
1474
1475 clients_up() {
1476     # not every config has many clients
1477     sleep 1
1478     if [ ! -z "$CLIENTS" ]; then
1479         $PDSH $CLIENTS "stat -f $MOUNT" > /dev/null
1480     else
1481         stat -f $MOUNT > /dev/null
1482     fi
1483 }
1484
1485 client_up() {
1486     local client=$1
1487     # usually checked on particular client or locally
1488     sleep 1
1489     if [ ! -z "$client" ]; then
1490         $PDSH $client "stat -f $MOUNT" > /dev/null
1491     else
1492         stat -f $MOUNT > /dev/null
1493     fi
1494 }
1495
1496 client_evicted() {
1497     ! client_up $1
1498 }
1499
1500 client_reconnect() {
1501     uname -n >> $MOUNT/recon
1502     if [ -z "$CLIENTS" ]; then
1503         df $MOUNT; uname -n >> $MOUNT/recon
1504     else
1505         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
1506     fi
1507     echo Connected clients:
1508     cat $MOUNT/recon
1509     ls -l $MOUNT/recon > /dev/null
1510     rm $MOUNT/recon
1511 }
1512
1513 affected_facets () {
1514     local facet=$1
1515
1516     local host=$(facet_active_host $facet)
1517     local affected=$facet
1518
1519     if [ "$FAILURE_MODE" = HARD ]; then
1520         affected=$(facets_up_on_host $host)
1521     fi
1522     echo $affected
1523 }
1524
1525 facet_failover() {
1526     local facet=$1
1527     local sleep_time=$2
1528     local host=$(facet_active_host $facet)
1529
1530     echo "Failing $facet on node $host"
1531
1532     # Make sure the client data is synced to disk. LU-924
1533     #
1534     # We don't write client data synchrnously (to avoid flooding sync writes
1535     # when there are many clients connecting), so if the server reboots before
1536     # the client data reachs disk, the client data will be lost and the client
1537     # will be evicted after recovery, which is not what we expected.
1538     do_facet $facet "sync; sync; sync"
1539
1540     local affected=$(affected_facets $facet)
1541
1542     shutdown_facet $facet
1543
1544     echo affected facets: $affected
1545
1546     [ -n "$sleep_time" ] && sleep $sleep_time
1547
1548     reboot_facet $facet
1549
1550     change_active $affected
1551
1552     wait_for_facet $affected
1553     # start mgs first if it is affected
1554     if ! combined_mgs_mds && list_member $affected mgs; then
1555         mount_facet mgs || error "Restart of mgs failed"
1556     fi
1557     # FIXME; has to be changed to mount all facets concurrently
1558     affected=$(exclude_items_from_list $affected mgs)
1559     mount_facets $affected
1560 }
1561
1562 obd_name() {
1563     local facet=$1
1564 }
1565
1566 replay_barrier() {
1567     local facet=$1
1568     do_facet $facet "sync; sync; sync"
1569     df $MOUNT
1570
1571     # make sure there will be no seq change
1572     local clients=${CLIENTS:-$HOSTNAME}
1573     do_nodes $clients "f=${MOUNT}/fsa-\\\$(hostname); mcreate \\\$f; rm \\\$f"
1574
1575     local svc=${facet}_svc
1576     do_facet $facet $LCTL --device %${!svc} notransno
1577     do_facet $facet $LCTL --device %${!svc} readonly
1578     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1579     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1580 }
1581
1582 replay_barrier_nodf() {
1583     local facet=$1    echo running=${running}
1584     do_facet $facet "sync; sync; sync"
1585     local svc=${facet}_svc
1586     echo Replay barrier on ${!svc}
1587     do_facet $facet $LCTL --device %${!svc} notransno
1588     do_facet $facet $LCTL --device %${!svc} readonly
1589     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1590     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1591 }
1592
1593 replay_barrier_nosync() {
1594     local facet=$1    echo running=${running}
1595     local svc=${facet}_svc
1596     echo Replay barrier on ${!svc}
1597     do_facet $facet $LCTL --device %${!svc} notransno
1598     do_facet $facet $LCTL --device %${!svc} readonly
1599     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1600     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1601 }
1602
1603 mds_evict_client() {
1604     UUID=`lctl get_param -n mdc.${mds1_svc}-mdc-*.uuid`
1605     do_facet mds1 "lctl set_param -n mdt.${mds1_svc}.evict_client $UUID"
1606 }
1607
1608 ost_evict_client() {
1609     UUID=`lctl get_param -n devices| grep ${ost1_svc}-osc- | egrep -v 'MDT' | awk '{print $5}'`
1610     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
1611 }
1612
1613 fail() {
1614     facet_failover $* || error "failover: $?"
1615     clients_up || error "post-failover df: $?"
1616 }
1617
1618 fail_nodf() {
1619         local facet=$1
1620         facet_failover $facet
1621 }
1622
1623 fail_abort() {
1624     local facet=$1
1625     stop $facet
1626     change_active $facet
1627     wait_for_facet $facet
1628     mount_facet $facet -o abort_recovery
1629     clients_up || echo "first df failed: $?"
1630     clients_up || error "post-failover df: $?"
1631 }
1632
1633 do_lmc() {
1634     echo There is no lmc.  This is mountconf, baby.
1635     exit 1
1636 }
1637
1638 host_nids_address() {
1639     local nodes=$1
1640     local kind=$2
1641
1642     if [ -n "$kind" ]; then
1643         nids=$(do_nodes $nodes "$LCTL list_nids | grep $kind | cut -f 1 -d '@'")
1644     else
1645         nids=$(do_nodes $nodes "$LCTL list_nids all | cut -f 1 -d '@'")
1646     fi
1647     echo $nids
1648 }
1649
1650 h2name_or_ip() {
1651     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1652         echo $1"@$2"
1653     fi
1654 }
1655
1656 h2ptl() {
1657    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1658        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
1659        if [ -z "$ID" ]; then
1660            echo "Could not get a ptl id for $1..."
1661            exit 1
1662        fi
1663        echo $ID"@ptl"
1664    fi
1665 }
1666 declare -fx h2ptl
1667
1668 h2tcp() {
1669     h2name_or_ip "$1" "tcp"
1670 }
1671 declare -fx h2tcp
1672
1673 h2elan() {
1674     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1675         if type __h2elan >/dev/null 2>&1; then
1676             ID=$(__h2elan $1)
1677         else
1678             ID=`echo $1 | sed 's/[^0-9]*//g'`
1679         fi
1680         echo $ID"@elan"
1681     fi
1682 }
1683 declare -fx h2elan
1684
1685 h2o2ib() {
1686     h2name_or_ip "$1" "o2ib"
1687 }
1688 declare -fx h2o2ib
1689
1690 # This enables variables in cfg/"setup".sh files to support the pdsh HOSTLIST
1691 # expressions format. As a bonus we can then just pass in those variables
1692 # to pdsh. What this function does is take a HOSTLIST type string and
1693 # expand it into a space deliminated list for us.
1694 hostlist_expand() {
1695     local hostlist=$1
1696     local offset=$2
1697     local myList
1698     local item
1699     local list
1700
1701     [ -z "$hostlist" ] && return
1702
1703     # Translate the case of [..],..,[..] to [..] .. [..]
1704     list="${hostlist/],/] }"
1705     front=${list%%[*}
1706     [[ "$front" == *,* ]] && {
1707         new="${list%,*} "
1708         old="${list%,*},"
1709         list=${list/${old}/${new}}
1710     }
1711
1712     for item in $list; do
1713         # Test if we have any []'s at all
1714         if [ "$item" != "${item/\[/}" ]; then {
1715             # Expand the [*] into list
1716             name=${item%%[*}
1717             back=${item#*]}
1718
1719             if [ "$name" != "$item" ]; then
1720                 group=${item#$name[*}
1721                 group=${group%%]*}
1722
1723                 for range in ${group//,/ }; do
1724                     begin=${range%-*}
1725                     end=${range#*-}
1726
1727                     # Number of leading zeros
1728                     padlen=${#begin}
1729                     padlen2=${#end}
1730                     end=$(echo $end | sed 's/0*//')
1731                     [[ -z "$end" ]] && end=0
1732                     [[ $padlen2 -gt $padlen ]] && {
1733                         [[ $padlen2 -eq ${#end} ]] && padlen2=0
1734                         padlen=$padlen2
1735                     }
1736                     begin=$(echo $begin | sed 's/0*//')
1737                     [ -z $begin ] && begin=0
1738
1739                     for num in $(seq -f "%0${padlen}g" $begin $end); do
1740                         value="${name#*,}${num}${back}"
1741                         [ "$value" != "${value/\[/}" ] && {
1742                             value=$(hostlist_expand "$value")
1743                         }
1744                         myList="$myList $value"
1745                     done
1746                 done
1747             fi
1748         } else {
1749             myList="$myList $item"
1750         } fi
1751     done
1752     myList=${myList//,/ }
1753     myList=${myList:1} # Remove first character which is a space
1754
1755     # Filter any duplicates without sorting
1756     list="$myList "
1757     myList="${list%% *}"
1758
1759     while [[ "$list" != ${myList##* } ]]; do
1760         list=${list//${list%% *} /}
1761         myList="$myList ${list%% *}"
1762     done
1763     myList="${myList%* }";
1764
1765     # We can select an object at a offset in the list
1766     [ $# -eq 2 ] && {
1767         cnt=0
1768         for item in $myList; do
1769             let cnt=cnt+1
1770             [ $cnt -eq $offset ] && {
1771                 myList=$item
1772             }
1773         done
1774         [ $(get_node_count $myList) -ne 1 ] && myList=""
1775     }
1776     echo $myList
1777 }
1778
1779 facet_host() {
1780     local facet=$1
1781
1782     [ "$facet" == client ] && echo -n $HOSTNAME && return
1783     varname=${facet}_HOST
1784     if [ -z "${!varname}" ]; then
1785         if [ "${facet:0:3}" == "ost" ]; then
1786             eval ${facet}_HOST=${ost_HOST}
1787         fi
1788     fi
1789     echo -n ${!varname}
1790 }
1791
1792 facet_active() {
1793     local facet=$1
1794     local activevar=${facet}active
1795
1796     if [ -f $TMP/${facet}active ] ; then
1797         source $TMP/${facet}active
1798     fi
1799
1800     active=${!activevar}
1801     if [ -z "$active" ] ; then
1802         echo -n ${facet}
1803     else
1804         echo -n ${active}
1805     fi
1806 }
1807
1808 facet_active_host() {
1809     local facet=$1
1810     local active=`facet_active $facet`
1811     if [ "$facet" == client ]; then
1812         echo $HOSTNAME
1813     else
1814         echo `facet_host $active`
1815     fi
1816 }
1817
1818 change_active() {
1819     local facetlist=$1
1820     local facet
1821
1822     facetlist=$(exclude_items_from_list $facetlist mgs)
1823
1824     for facet in ${facetlist//,/ }; do
1825     local failover=${facet}failover
1826     local host=`facet_host $failover`
1827     [ -z "$host" ] && return
1828
1829     local curactive=`facet_active $facet`
1830     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
1831         eval export ${facet}active=$facet
1832     else
1833         eval export ${facet}active=$failover
1834     fi
1835     # save the active host for this facet
1836     local activevar=${facet}active
1837     echo "$activevar=${!activevar}" > $TMP/$activevar
1838     [[ $facet = mds1 ]] && combined_mgs_mds && \
1839         echo "mgsactive=${!activevar}" > $TMP/mgsactive
1840     local TO=`facet_active_host $facet`
1841     echo "Failover $facet to $TO"
1842     done
1843 }
1844
1845 do_node() {
1846     local verbose=false
1847     # do not stripe off hostname if verbose, bug 19215
1848     if [ x$1 = x--verbose ]; then
1849         shift
1850         verbose=true
1851     fi
1852
1853     local HOST=$1
1854     shift
1855     local myPDSH=$PDSH
1856     if [ "$HOST" = "$HOSTNAME" ]; then
1857         myPDSH="no_dsh"
1858     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
1859         echo "cannot run remote command on $HOST with $myPDSH"
1860         return 128
1861     fi
1862     if $VERBOSE; then
1863         echo "CMD: $HOST $@" >&2
1864         $myPDSH $HOST "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
1865     fi
1866
1867     if [ "$myPDSH" = "rsh" ]; then
1868 # we need this because rsh does not return exit code of an executed command
1869         local command_status="$TMP/cs"
1870         rsh $HOST ":> $command_status"
1871         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
1872                     cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
1873                     echo command failed >$command_status"
1874         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
1875         return 0
1876     fi
1877
1878     if $verbose ; then
1879         # print HOSTNAME for myPDSH="no_dsh"
1880         if [[ $myPDSH = no_dsh ]]; then
1881             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
1882         else
1883             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
1884         fi
1885     else
1886         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
1887     fi
1888     return ${PIPESTATUS[0]}
1889 }
1890
1891 do_nodev() {
1892     do_node --verbose "$@"
1893 }
1894
1895 single_local_node () {
1896    [ "$1" = "$HOSTNAME" ]
1897 }
1898
1899 # Outputs environment variable assignments that should be passed to remote nodes
1900 get_env_vars() {
1901     local var
1902     local value
1903
1904     for var in ${!MODOPTS_*}; do
1905         value=${!var}
1906         echo "${var}=\"$value\""
1907     done
1908 }
1909
1910 do_nodes() {
1911     local verbose=false
1912     # do not stripe off hostname if verbose, bug 19215
1913     if [ x$1 = x--verbose ]; then
1914         shift
1915         verbose=true
1916     fi
1917
1918     local rnodes=$1
1919     shift
1920
1921     if single_local_node $rnodes; then
1922         if $verbose; then
1923            do_nodev $rnodes "$@"
1924         else
1925            do_node $rnodes "$@"
1926         fi
1927         return $?
1928     fi
1929
1930     # This is part from do_node
1931     local myPDSH=$PDSH
1932
1933     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
1934         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
1935
1936     if $VERBOSE; then
1937         echo "CMD: $rnodes $@" >&2
1938         $myPDSH $rnodes "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
1939     fi
1940
1941     # do not replace anything from pdsh output if -N is used
1942     # -N     Disable hostname: prefix on lines of output.
1943     if $verbose || [[ $myPDSH = *-N* ]]; then
1944         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")"
1945     else
1946         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")" | sed -re "s/^[^:]*: //g"
1947     fi
1948     return ${PIPESTATUS[0]}
1949 }
1950
1951 do_facet() {
1952     local facet=$1
1953     shift
1954     local HOST=`facet_active_host $facet`
1955     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
1956     do_node $HOST "$@"
1957 }
1958
1959 do_nodesv() {
1960     do_nodes --verbose "$@"
1961 }
1962
1963 add() {
1964     local facet=$1
1965     shift
1966     # make sure its not already running
1967     stop ${facet} -f
1968     rm -f $TMP/${facet}active
1969     [[ $facet = mds1 ]] && combined_mgs_mds && rm -f $TMP/mgsactive
1970     do_facet ${facet} $MKFS $*
1971 }
1972
1973 ostdevname() {
1974     num=$1
1975     DEVNAME=OSTDEV$num
1976     #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
1977     eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}}
1978     echo -n $DEVPTR
1979 }
1980
1981 mdsdevname() {
1982     num=$1
1983     DEVNAME=MDSDEV$num
1984     #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
1985     eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}}
1986     echo -n $DEVPTR
1987 }
1988
1989 facet_mntpt () {
1990     local facet=$1
1991     [[ $facet = mgs ]] && combined_mgs_mds && facet="mds1"
1992
1993     local var=${facet}_MOUNT
1994     eval mntpt=${!var:-${MOUNT%/*}/$facet}
1995
1996     echo -n $mntpt
1997 }
1998
1999 ########
2000 ## MountConf setup
2001
2002 stopall() {
2003     # make sure we are using the primary server, so test-framework will
2004     # be able to clean up properly.
2005     activemds=`facet_active mds1`
2006     if [ $activemds != "mds1" ]; then
2007         fail mds1
2008     fi
2009
2010     local clients=$CLIENTS
2011     [ -z $clients ] && clients=$(hostname)
2012
2013     zconf_umount_clients $clients $MOUNT "$*" || true
2014     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
2015
2016     [ "$CLIENTONLY" ] && return
2017     # The add fn does rm ${facet}active file, this would be enough
2018     # if we use do_facet <facet> only after the facet added, but
2019     # currently we use do_facet mds in local.sh
2020     for num in `seq $MDSCOUNT`; do
2021         stop mds$num -f
2022         rm -f ${TMP}/mds${num}active
2023     done
2024     combined_mgs_mds && rm -f $TMP/mgsactive
2025
2026     for num in `seq $OSTCOUNT`; do
2027         stop ost$num -f
2028         rm -f $TMP/ost${num}active
2029     done
2030
2031     if ! combined_mgs_mds ; then
2032         stop mgs
2033     fi
2034
2035     return 0
2036 }
2037
2038 cleanup_echo_devs () {
2039     local devs=$($LCTL dl | grep echo | awk '{print $4}')
2040
2041     for dev in $devs; do
2042         $LCTL --device $dev cleanup
2043         $LCTL --device $dev detach
2044     done
2045 }
2046
2047 cleanupall() {
2048     nfs_client_mode && return
2049
2050     stopall $*
2051     cleanup_echo_devs
2052
2053     unload_modules
2054     cleanup_gss
2055 }
2056
2057 combined_mgs_mds () {
2058     [[ $MDSDEV1 = $MGSDEV ]] && [[ $mds1_HOST = $mgs_HOST ]]
2059 }
2060
2061 mkfs_opts () {
2062     local facet=$1
2063
2064     local tgt=$(echo $facet | tr -d [:digit:] | tr "[:lower:]" "[:upper:]")
2065     local optvar=${tgt}_MKFS_OPTS
2066     local opt=${!optvar}
2067
2068     # FIXME: ! combo  mgs/mds + mgsfailover is not supported yet
2069     [[ $facet = mgs ]] && echo $opt && return
2070
2071     # 1.
2072     # --failnode options 
2073     local var=${facet}failover_HOST
2074     if [ x"${!var}" != x ] && [ x"${!var}" != x$(facet_host $facet) ] ; then
2075         local failnode=$(h2$NETTYPE ${!var})
2076         failnode="--failnode=$failnode"
2077         # options does not contain
2078         # or contains wrong --failnode=
2079         if [[ $opt != *${failnode}* ]]; then
2080             opt=$(echo $opt | sed 's/--failnode=.* / /')
2081             opt="$opt $failnode"
2082         fi
2083     fi
2084
2085     # 2.
2086     # --mgsnode options
2087     # no additional mkfs mds "--mgsnode" option for this configuration
2088     if [[ $facet = mds ]] && combined_mgs_mds; then
2089         echo $opt
2090         return
2091     fi
2092
2093     # additional mkfs "--mgsnode"
2094     local mgsnode="--mgsnode=$MGSNID"
2095     opt=${opt//$mgsnode }
2096     for nid in ${MGSNID//:/ }; do
2097         local mgsnode="--mgsnode=$nid"
2098         # options does not contain
2099         # --mgsnode=$nid
2100         if [[ $opt != *${mgsnode}" "* ]]; then
2101             opt="$opt --mgsnode=$nid"
2102         fi
2103     done
2104
2105     echo $opt
2106 }
2107
2108 formatall() {
2109     if [ "$IAMDIR" == "yes" ]; then
2110         MDS_MKFS_OPTS="$MDS_MKFS_OPTS --iam-dir"
2111     fi
2112
2113     [ "$FSTYPE" ] && FSTYPE_OPT="--backfstype $FSTYPE"
2114
2115     stopall
2116     # We need ldiskfs here, may as well load them all
2117     load_modules
2118     [ "$CLIENTONLY" ] && return
2119     echo Formatting mgs, mds, osts
2120     if ! combined_mgs_mds ; then
2121         add mgs $(mkfs_opts mgs) $FSTYPE_OPT --reformat $MGSDEV || exit 10
2122     fi
2123
2124     for num in `seq $MDSCOUNT`; do
2125         echo "Format mds$num: $(mdsdevname $num)"
2126         if $VERBOSE; then
2127             add mds$num $(mkfs_opts mds) $FSTYPE_OPT --reformat $(mdsdevname $num) || exit 10
2128         else
2129             add mds$num $(mkfs_opts mds) $FSTYPE_OPT --reformat $(mdsdevname $num) > /dev/null || exit 10
2130         fi
2131     done
2132
2133     # the ost-s could have different OST_MKFS_OPTS
2134     # because of different failnode-s
2135     for num in `seq $OSTCOUNT`; do
2136         echo "Format ost$num: $(ostdevname $num)"
2137         if $VERBOSE; then
2138             add ost$num $(mkfs_opts ost${num}) $FSTYPE_OPT --reformat `ostdevname $num` || exit 10
2139         else
2140             add ost$num $(mkfs_opts ost${num}) $FSTYPE_OPT --reformat `ostdevname $num` > /dev/null || exit 10
2141         fi
2142     done
2143 }
2144
2145 mount_client() {
2146     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
2147 }
2148
2149 umount_client() {
2150     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
2151 }
2152
2153 # return value:
2154 # 0: success, the old identity set already.
2155 # 1: success, the old identity does not set.
2156 # 2: fail.
2157 switch_identity() {
2158     local num=$1
2159     local switch=$2
2160     local j=`expr $num - 1`
2161     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
2162
2163     if [ -z "$MDT" ]; then
2164         return 2
2165     fi
2166
2167     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
2168
2169     if $switch; then
2170         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
2171     else
2172         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
2173     fi
2174
2175     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush=-1"
2176
2177     if [ $old = "NONE" ]; then
2178         return 1
2179     else
2180         return 0
2181     fi
2182 }
2183
2184 remount_client()
2185 {
2186         zconf_umount `hostname` $1 || error "umount failed"
2187         zconf_mount `hostname` $1 || error "mount failed"
2188 }
2189
2190 writeconf_facet () {
2191     local facet=$1
2192     local dev=$2
2193
2194     do_facet $facet "$TUNEFS --writeconf $dev"
2195 }
2196
2197 writeconf_all () {
2198     for num in `seq $MDSCOUNT`; do
2199         DEVNAME=$(mdsdevname $num)
2200         writeconf_facet mds$num $DEVNAME
2201     done
2202
2203     for num in `seq $OSTCOUNT`; do
2204         DEVNAME=$(ostdevname $num)
2205         writeconf_facet ost$num $DEVNAME
2206     done
2207 }
2208
2209 setupall() {
2210     nfs_client_mode && return
2211
2212     sanity_mount_check ||
2213         error "environments are insane!"
2214
2215     load_modules
2216
2217     if [ -z "$CLIENTONLY" ]; then
2218         echo Setup mgs, mdt, osts
2219         echo $WRITECONF | grep -q "writeconf" && \
2220             writeconf_all
2221         if ! combined_mgs_mds ; then
2222             start mgs $MGSDEV $MGS_MOUNT_OPTS
2223         fi
2224
2225         for num in `seq $MDSCOUNT`; do
2226             DEVNAME=$(mdsdevname $num)
2227             start mds$num $DEVNAME $MDS_MOUNT_OPTS
2228
2229             # We started mds, now we should set failover variables properly.
2230             # Set mds${num}failover_HOST if it is not set (the default failnode).
2231             local varname=mds${num}failover_HOST
2232             if [ -z "${!varname}" ]; then
2233                 eval mds${num}failover_HOST=$(facet_host mds$num)
2234             fi
2235
2236             if [ $IDENTITY_UPCALL != "default" ]; then
2237                 switch_identity $num $IDENTITY_UPCALL
2238             fi
2239         done
2240         for num in `seq $OSTCOUNT`; do
2241             DEVNAME=$(ostdevname $num)
2242             start ost$num $DEVNAME $OST_MOUNT_OPTS
2243
2244             # We started ost$num, now we should set ost${num}failover variable properly.
2245             # Set ost${num}failover_HOST if it is not set (the default failnode).
2246             varname=ost${num}failover_HOST
2247             if [ -z "${!varname}" ]; then
2248                 eval ost${num}failover_HOST=$(facet_host ost${num})
2249             fi
2250
2251         done
2252     fi
2253
2254     init_gss
2255
2256     # wait a while to allow sptlrpc configuration be propogated to targets,
2257     # only needed when mounting new target devices.
2258     if $GSS; then
2259         sleep 10
2260     fi
2261
2262     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
2263     mount_client $MOUNT
2264     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
2265
2266     if [ "$MOUNT_2" ]; then
2267         mount_client $MOUNT2
2268         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
2269     fi
2270
2271     init_param_vars
2272
2273     # by remounting mdt before ost, initial connect from mdt to ost might
2274     # timeout because ost is not ready yet. wait some time to its fully
2275     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
2276     # by a context negotiation rpc with $TIMEOUT.
2277     # FIXME better by monitoring import status.
2278     if $GSS; then
2279         set_flavor_all $SEC
2280         sleep $((TIMEOUT + 5))
2281     else
2282         sleep 5
2283     fi
2284 }
2285
2286 mounted_lustre_filesystems() {
2287         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
2288 }
2289
2290 init_facet_vars () {
2291     [ "$CLIENTONLY" ] && return 0
2292     local facet=$1
2293     shift
2294     local device=$1
2295
2296     shift
2297
2298     eval export ${facet}_dev=${device}
2299     eval export ${facet}_opt=\"$@\"
2300
2301     local dev=${facet}_dev
2302     local label=$(do_facet ${facet} "$E2LABEL ${!dev}")
2303     [ -z "$label" ] && echo no label for ${!dev} && exit 1
2304
2305     eval export ${facet}_svc=${label}
2306
2307     local varname=${facet}failover_HOST
2308     if [ -z "${!varname}" ]; then
2309        eval $varname=$(facet_host $facet) 
2310     fi
2311
2312     # ${facet}failover_dev is set in cfg file
2313     varname=${facet}failover_dev
2314     if [ -n "${!varname}" ] ; then
2315         eval export ${facet}failover_dev=${!varname}
2316     else
2317         eval export ${facet}failover_dev=$device
2318     fi
2319
2320     # get mount point of already mounted device
2321     # is facet_dev is already mounted then use the real
2322     #  mount point of this facet; otherwise use $(facet_mntpt $facet)
2323     # i.e. ${facet}_MOUNT if specified by user or default
2324     local mntpt=$(do_facet ${facet} cat /proc/mounts | \
2325             awk '"'${!dev}'" == $1 && $3 == "lustre" { print $2 }')
2326     if [ -z $mntpt ]; then
2327         mntpt=$(facet_mntpt $facet)
2328     fi
2329     eval export ${facet}_MOUNT=$mntpt
2330 }
2331
2332 init_facets_vars () {
2333     local DEVNAME
2334
2335     if ! remote_mds_nodsh; then 
2336         for num in `seq $MDSCOUNT`; do
2337             DEVNAME=`mdsdevname $num`
2338             init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
2339         done
2340     fi
2341
2342     combined_mgs_mds || init_facet_vars mgs $MGSDEV $MGS_MOUNT_OPTS
2343
2344     remote_ost_nodsh && return
2345
2346     for num in `seq $OSTCOUNT`; do
2347         DEVNAME=`ostdevname $num`
2348         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
2349     done
2350 }
2351
2352 osc_ensure_active () {
2353     local facet=$1
2354     local timeout=$2
2355     local period=0
2356
2357     while [ $period -lt $timeout ]; do
2358         count=$(do_facet $facet "lctl dl | grep ' IN osc ' 2>/dev/null | wc -l")
2359         if [ $count -eq 0 ]; then
2360             break
2361         fi
2362
2363         echo "There are $count OST are inactive, wait $period seconds, and try again"
2364         sleep 3
2365         period=$((period+3))
2366     done
2367
2368     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
2369 }
2370
2371 init_param_vars () {
2372     if ! remote_ost_nodsh && ! remote_mds_nodsh; then
2373         export MDSVER=$(do_facet $SINGLEMDS "lctl get_param version" | cut -d. -f1,2)
2374         export OSTVER=$(do_facet ost1 "lctl get_param version" | cut -d. -f1,2)
2375         export CLIVER=$(lctl get_param version | cut -d. -f 1,2)
2376     fi
2377
2378     remote_mds_nodsh ||
2379         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
2380
2381     log "Using TIMEOUT=$TIMEOUT"
2382
2383     osc_ensure_active $SINGLEMDS $TIMEOUT
2384     osc_ensure_active client $TIMEOUT
2385
2386     if [ $QUOTA_AUTO -ne 0 ]; then
2387         if [ "$ENABLE_QUOTA" ]; then
2388             echo "enable quota as required"
2389             setup_quota $MOUNT || return 2
2390         else
2391             echo "disable quota as required"
2392             $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
2393         fi
2394     fi
2395
2396     return 0
2397 }
2398
2399 nfs_client_mode () {
2400     if [ "$NFSCLIENT" ]; then
2401         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
2402         local clients=$CLIENTS
2403         [ -z $clients ] && clients=$(hostname)
2404
2405         # FIXME: remove hostname when 19215 fixed
2406         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
2407         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
2408         if [[ ${#nfsexport[@]} -eq 0 ]]; then
2409                 error_exit NFSCLIENT=$NFSCLIENT mode, but no NFS export found!
2410         fi
2411         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
2412         return
2413     fi
2414     return 1
2415 }
2416
2417 check_config_client () {
2418     local mntpt=$1
2419
2420     local mounted=$(mount | grep " $mntpt ")
2421     if [ "$CLIENTONLY" ]; then
2422         # bug 18021
2423         # CLIENTONLY should not depend on *_HOST settings
2424         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
2425         # in theory someone could create a new,
2426         # client-only config file that assumed lustre was already
2427         # configured and didn't set the MGSNID. If MGSNID is not set,
2428         # then we should use the mgs nid currently being used 
2429         # as the default value. bug 18021
2430         [[ x$MGSNID = x ]] &&
2431             MGSNID=${mgc//MGC/}
2432
2433         if [[ x$mgc != xMGC$MGSNID ]]; then
2434             if [ "$mgs_HOST" ]; then
2435                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
2436 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
2437 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
2438             fi
2439         fi
2440         return 0
2441     fi
2442
2443     local myMGS_host=$mgs_HOST   
2444     if [ "$NETTYPE" = "ptl" ]; then
2445         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
2446     fi
2447
2448     echo Checking config lustre mounted on $mntpt
2449     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
2450     mgshost=$(echo $mgshost | awk -F: '{print $1}')
2451
2452 #    if [ "$mgshost" != "$myMGS_host" ]; then
2453 #            log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
2454 #                   Please use correct config or set mds_HOST correctly!"
2455 #    fi
2456
2457 }
2458
2459 check_config_clients () {
2460     local clients=${CLIENTS:-$HOSTNAME}
2461     local mntpt=$1
2462
2463     nfs_client_mode && return
2464
2465     do_rpc_nodes $clients check_config_client $mntpt
2466
2467     sanity_mount_check ||
2468         error "environments are insane!"
2469 }
2470
2471 check_timeout () {
2472     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
2473     local cltimeout=$(lctl get_param -n timeout)
2474     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
2475         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
2476         return 1
2477     fi
2478 }
2479
2480 is_mounted () {
2481     local mntpt=$1
2482     [ -z $mntpt ] && return 1
2483     local mounted=$(mounted_lustre_filesystems)
2484
2485     echo $mounted' ' | grep -w -q $mntpt' '
2486 }
2487
2488 is_empty_dir() {
2489     [ $(find $1 -maxdepth 1 -print | wc -l) = 1 ] && return 0
2490     return 1
2491 }
2492
2493 # empty lustre filesystem may have empty directories lost+found and .lustre
2494 is_empty_fs() {
2495     [ $(find $1 -maxdepth 1 -name lost+found -o -name .lustre -prune -o \
2496        -print | wc -l) = 1 ] || return 1
2497     [ ! -d $1/lost+found ] || is_empty_dir $1/lost+found && return 0
2498     [ ! -d $1/.lustre ] || is_empty_dir $1/.lustre && return 0
2499     return 1
2500 }
2501
2502 check_and_setup_lustre() {
2503     nfs_client_mode && return
2504
2505     local MOUNTED=$(mounted_lustre_filesystems)
2506
2507     local do_check=true
2508     # 1.
2509     # both MOUNT and MOUNT2 are not mounted
2510     if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
2511         [ "$REFORMAT" ] && formatall
2512         # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
2513         setupall
2514         is_mounted $MOUNT || error "NAME=$NAME not mounted"
2515         export I_MOUNTED=yes
2516         do_check=false
2517     # 2.
2518     # MOUNT2 is mounted
2519     elif is_mounted $MOUNT2; then
2520             # 3.
2521             # MOUNT2 is mounted, while MOUNT_2 is not set
2522             if ! [ "$MOUNT_2" ]; then
2523                 cleanup_mount $MOUNT2
2524                 export I_UMOUNTED2=yes
2525
2526             # 4.
2527             # MOUNT2 is mounted, MOUNT_2 is set
2528             else
2529                 # FIXME: what to do if check_config failed?
2530                 # i.e. if:
2531                 # 1) remote client has mounted other Lustre fs ?
2532                 # 2) it has insane env ?
2533                 # let's try umount MOUNT2 on all clients and mount it again:
2534                 if ! check_config_clients $MOUNT2; then
2535                     cleanup_mount $MOUNT2
2536                     restore_mount $MOUNT2
2537                     export I_MOUNTED2=yes
2538                 fi
2539             fi 
2540
2541     # 5.
2542     # MOUNT is mounted MOUNT2 is not mounted
2543     elif [ "$MOUNT_2" ]; then
2544         restore_mount $MOUNT2
2545         export I_MOUNTED2=yes
2546     fi
2547
2548     if $do_check; then
2549         # FIXME: what to do if check_config failed?
2550         # i.e. if:
2551         # 1) remote client has mounted other Lustre fs?
2552         # 2) lustre is mounted on remote_clients atall ?
2553         check_config_clients $MOUNT
2554         init_facets_vars
2555         init_param_vars
2556
2557         set_default_debug_nodes $(comma_list $(nodes_list))
2558     fi
2559
2560     init_gss
2561     set_flavor_all $SEC
2562
2563     if [ "$ONLY" == "setup" ]; then
2564         exit 0
2565     fi
2566 }
2567
2568 restore_mount () {
2569    local clients=${CLIENTS:-$HOSTNAME}
2570    local mntpt=$1
2571
2572    zconf_mount_clients $clients $mntpt
2573 }
2574
2575 cleanup_mount () {
2576     local clients=${CLIENTS:-$HOSTNAME}
2577     local mntpt=$1
2578
2579     zconf_umount_clients $clients $mntpt    
2580 }
2581
2582 cleanup_and_setup_lustre() {
2583     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
2584         lctl set_param debug=0 || true
2585         cleanupall
2586         if [ "$ONLY" == "cleanup" ]; then
2587             exit 0
2588         fi
2589     fi
2590     check_and_setup_lustre
2591 }
2592
2593 # Get all of the server target devices from a given server node and type.
2594 get_mnt_devs() {
2595     local node=$1
2596     local type=$2
2597     local obd_type
2598     local devs
2599     local dev
2600
2601     case $type in
2602     mdt) obd_type="osd" ;;
2603     ost) obd_type="obdfilter" ;; # needs to be fixed when OST also uses an OSD
2604     *) echo "invalid server type" && return 1 ;;
2605     esac
2606
2607     devs=$(do_node $node "lctl get_param -n $obd_type*.*.mntdev")
2608     for dev in $devs; do
2609         case $dev in
2610         *loop*) do_node $node "losetup $dev" | \
2611                 sed -e "s/.*(//" -e "s/).*//" ;;
2612         *) echo $dev ;;
2613         esac
2614     done
2615 }
2616
2617 # Get all of the server target devices.
2618 get_svr_devs() {
2619     local i
2620
2621     # MDT device
2622     MDTDEV=$(get_mnt_devs $(mdts_nodes) mdt)
2623
2624     # OST devices
2625     i=0
2626     for node in $(osts_nodes); do
2627         OSTDEVS[i]=$(get_mnt_devs $node ost)
2628         i=$((i + 1))
2629     done
2630 }
2631
2632 # Run e2fsck on MDT or OST device.
2633 run_e2fsck() {
2634     local node=$1
2635     local target_dev=$2
2636     local extra_opts=$3
2637
2638     df > /dev/null      # update statfs data on disk
2639     local cmd="$E2FSCK -d -v -t -t -f -n $extra_opts $target_dev"
2640     echo $cmd
2641     local rc=0
2642     do_node $node $cmd || rc=$?
2643     [ $rc -le $FSCK_MAX_ERR ] || \
2644         error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
2645     return 0
2646 }
2647
2648 # verify a directory is shared among nodes.
2649 check_shared_dir() {
2650     local dir=$1
2651
2652     [ -z "$dir" ] && return 1
2653     do_rpc_nodes $(comma_list $(nodes_list)) check_logdir $dir
2654     check_write_access $dir || return 1
2655     return 0
2656 }
2657
2658 # Run e2fsck on MDT and OST(s) to generate databases used for lfsck.
2659 generate_db() {
2660     local i
2661     local ostidx
2662     local dev
2663
2664     check_shared_dir $SHARED_DIRECTORY ||
2665         error "$SHARED_DIRECTORY isn't a shared directory"
2666
2667     export MDSDB=$SHARED_DIRECTORY/mdsdb
2668     export OSTDB=$SHARED_DIRECTORY/ostdb
2669
2670     [ $MDSCOUNT -eq 1 ] || error "CMD is not supported"
2671
2672     run_e2fsck $(mdts_nodes) $MDTDEV "--mdsdb $MDSDB"
2673
2674     i=0
2675     ostidx=0
2676     OSTDB_LIST=""
2677     for node in $(osts_nodes); do
2678         for dev in ${OSTDEVS[i]}; do
2679             run_e2fsck $node $dev "--mdsdb $MDSDB --ostdb $OSTDB-$ostidx"
2680             OSTDB_LIST="$OSTDB_LIST $OSTDB-$ostidx"
2681             ostidx=$((ostidx + 1))
2682         done
2683         i=$((i + 1))
2684     done
2685 }
2686
2687 run_lfsck() {
2688     local cmd="$LFSCK_BIN -c -l --mdsdb $MDSDB --ostdb $OSTDB_LIST $MOUNT"
2689     echo $cmd
2690     local rc=0
2691     eval $cmd || rc=$?
2692     [ $rc -le $FSCK_MAX_ERR ] || \
2693         error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
2694     echo "lfsck finished with rc=$rc"
2695
2696     rm -rvf $MDSDB* $OSTDB* || true
2697     return 0
2698 }
2699
2700 check_and_cleanup_lustre() {
2701     if [ "$LFSCK_ALWAYS" = "yes" -a "$TESTSUITE" != "lfsck" ]; then
2702         get_svr_devs
2703         generate_db
2704         run_lfsck
2705     fi
2706
2707     if is_mounted $MOUNT; then
2708         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
2709         [ "$ENABLE_QUOTA" ] && restore_quota_type || true
2710     fi
2711
2712     if [ "$I_UMOUNTED2" = "yes" ]; then
2713         restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
2714     fi
2715
2716     if [ "$I_MOUNTED2" = "yes" ]; then
2717         cleanup_mount $MOUNT2
2718     fi
2719
2720     if [ "$I_MOUNTED" = "yes" ]; then
2721         cleanupall -f || error "cleanup failed"
2722         unset I_MOUNTED
2723     fi
2724 }
2725
2726 #######
2727 # General functions
2728
2729 wait_for_function () {
2730     local quiet=""
2731
2732     # suppress fn both stderr and stdout
2733     if [ "$1" = "--quiet" ]; then
2734         shift
2735         quiet=" > /dev/null 2>&1"
2736
2737     fi
2738
2739     local fn=$1
2740     local max=${2:-900}
2741     local sleep=${3:-5}
2742
2743     local wait=0
2744
2745     while true; do
2746
2747         eval $fn $quiet && return 0
2748
2749         wait=$((wait + sleep))
2750         [ $wait -lt $max ] || return 1
2751         echo waiting $fn, $((max - wait)) secs left ...
2752         sleep $sleep
2753     done
2754 }
2755
2756 check_network() {
2757     local host=$1
2758     local max=$2
2759     local sleep=${3:-5}
2760
2761     echo `date +"%H:%M:%S (%s)"` waiting for $host network $max secs ...
2762     if ! wait_for_function --quiet "ping -c 1 -w 3 $host" $max $sleep ; then
2763         echo "Network not available!"
2764         exit 1
2765     fi
2766
2767     echo `date +"%H:%M:%S (%s)"` network interface is UP
2768 }
2769
2770 no_dsh() {
2771     shift
2772     eval $@
2773 }
2774
2775 comma_list() {
2776     # the sed converts spaces to commas, but leaves the last space
2777     # alone, so the line doesn't end with a comma.
2778     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
2779 }
2780
2781 list_member () {
2782     local list=$1
2783     local item=$2
2784     echo $list | grep -qw $item
2785 }
2786
2787 # list, excluded are the comma separated lists
2788 exclude_items_from_list () {
2789     local list=$1
2790     local excluded=$2
2791     local item
2792
2793     list=${list//,/ }
2794     for item in ${excluded//,/ }; do
2795         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
2796     done
2797     echo $(comma_list $list)
2798 }
2799
2800 # list, expand  are the comma separated lists
2801 expand_list () {
2802     local list=${1//,/ }
2803     local expand=${2//,/ }
2804     local expanded=
2805
2806     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
2807     echo $(comma_list $expanded)
2808 }
2809
2810 testslist_filter () {
2811     local script=$LUSTRE/tests/${TESTSUITE}.sh
2812
2813     [ -f $script ] || return 0
2814
2815     local start_at=$START_AT
2816     local stop_at=$STOP_AT
2817
2818     local var=${TESTSUITE//-/_}_START_AT
2819     [ x"${!var}" != x ] && start_at=${!var}
2820     var=${TESTSUITE//-/_}_STOP_AT
2821     [ x"${!var}" != x ] && stop_at=${!var}
2822
2823     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
2824         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
2825             /^'${start_at}'$/ {flag = 0}
2826             {if (flag == 1) print $0}
2827             /^'${stop_at}'$/ { flag = 1 }'
2828 }
2829
2830 absolute_path() {
2831     (cd `dirname $1`; echo $PWD/`basename $1`)
2832 }
2833
2834 get_facets () {
2835     local types=${1:-"OST MDS MGS"}
2836
2837     local list=""
2838
2839     for entry in $types; do
2840         local name=$(echo $entry | tr "[:upper:]" "[:lower:]")
2841         local type=$(echo $entry | tr "[:lower:]" "[:upper:]")
2842
2843         case $type in
2844                 MGS ) list="$list $name";;
2845             MDS|OST ) local count=${type}COUNT
2846                        for ((i=1; i<=${!count}; i++)) do
2847                           list="$list ${name}$i"
2848                       done;;
2849                   * ) error "Invalid facet type"
2850                  exit 1;;
2851         esac
2852     done
2853     echo $(comma_list $list)
2854 }
2855
2856 ##################################
2857 # Adaptive Timeouts funcs
2858
2859 at_is_enabled() {
2860     # only check mds, we assume at_max is the same on all nodes
2861     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
2862     if [ $at_max -eq 0 ]; then
2863         return 1
2864     else
2865         return 0
2866     fi
2867 }
2868
2869 at_get() {
2870     local facet=$1
2871     local at=$2
2872
2873     # suppose that all ost-s have the same $at value set
2874     [ $facet != "ost" ] || facet=ost1
2875
2876     do_facet $facet "lctl get_param -n $at"
2877 }
2878
2879 at_max_get() {
2880     at_get $1 at_max
2881 }
2882
2883 at_max_set() {
2884     local at_max=$1
2885     shift
2886
2887     local facet
2888     local hosts
2889     for facet in $@; do
2890         if [ $facet == "ost" ]; then
2891             facet=$(get_facets OST)
2892         elif [ $facet == "mds" ]; then
2893             facet=$(get_facets MDS)
2894         fi
2895         hosts=$(expand_list $hosts $(facets_hosts $facet))
2896     done
2897
2898     do_nodes $hosts lctl set_param at_max=$at_max
2899 }
2900
2901 ##################################
2902 # OBD_FAIL funcs
2903
2904 drop_request() {
2905 # OBD_FAIL_MDS_ALL_REQUEST_NET
2906     RC=0
2907     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
2908     do_facet client "$1" || RC=$?
2909     do_facet $SINGLEMDS lctl set_param fail_loc=0
2910     return $RC
2911 }
2912
2913 drop_reply() {
2914 # OBD_FAIL_MDS_ALL_REPLY_NET
2915     RC=0
2916     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
2917     do_facet client "$@" || RC=$?
2918     do_facet $SINGLEMDS lctl set_param fail_loc=0
2919     return $RC
2920 }
2921
2922 drop_reint_reply() {
2923 # OBD_FAIL_MDS_REINT_NET_REP
2924     RC=0
2925     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
2926     do_facet client "$@" || RC=$?
2927     do_facet $SINGLEMDS lctl set_param fail_loc=0
2928     return $RC
2929 }
2930
2931 pause_bulk() {
2932 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
2933     RC=0
2934     do_facet ost1 lctl set_param fail_loc=0x214
2935     do_facet client "$1" || RC=$?
2936     do_facet client "sync"
2937     do_facet ost1 lctl set_param fail_loc=0
2938     return $RC
2939 }
2940
2941 drop_ldlm_cancel() {
2942 #define OBD_FAIL_LDLM_CANCEL             0x304
2943     RC=0
2944     do_facet client lctl set_param fail_loc=0x304
2945     do_facet client "$@" || RC=$?
2946     do_facet client lctl set_param fail_loc=0
2947     return $RC
2948 }
2949
2950 drop_bl_callback() {
2951 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
2952     RC=0
2953     do_facet client lctl set_param fail_loc=0x305
2954     do_facet client "$@" || RC=$?
2955     do_facet client lctl set_param fail_loc=0
2956     return $RC
2957 }
2958
2959 drop_ldlm_reply() {
2960 #define OBD_FAIL_LDLM_REPLY              0x30c
2961     RC=0
2962     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
2963     do_facet client "$@" || RC=$?
2964     do_facet $SINGLEMDS lctl set_param fail_loc=0
2965     return $RC
2966 }
2967
2968 clear_failloc() {
2969     facet=$1
2970     pause=$2
2971     sleep $pause
2972     echo "clearing fail_loc on $facet"
2973     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
2974 }
2975
2976 set_nodes_failloc () {
2977     do_nodes $(comma_list $1)  lctl set_param fail_loc=$2
2978 }
2979
2980 cancel_lru_locks() {
2981     $LCTL mark "cancel_lru_locks $1 start"
2982     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
2983         $LCTL set_param -n $d=clear
2984     done
2985     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
2986     $LCTL mark "cancel_lru_locks $1 stop"
2987 }
2988
2989 default_lru_size()
2990 {
2991         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
2992         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
2993         echo "$DEFAULT_LRU_SIZE"
2994 }
2995
2996 lru_resize_enable()
2997 {
2998     lctl set_param ldlm.namespaces.*$1*.lru_size=0
2999 }
3000
3001 lru_resize_disable()
3002 {
3003     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
3004 }
3005
3006 pgcache_empty() {
3007     local FILE
3008     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
3009         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
3010             echo there is still data in page cache $FILE ?
3011             lctl get_param -n $FILE
3012             return 1
3013         fi
3014     done
3015     return 0
3016 }
3017
3018 debugsave() {
3019     DEBUGSAVE="$(lctl get_param -n debug)"
3020 }
3021
3022 debugrestore() {
3023     [ -n "$DEBUGSAVE" ] && \
3024         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
3025     DEBUGSAVE=""
3026 }
3027
3028 debug_size_save() {
3029     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
3030 }
3031
3032 debug_size_restore() {
3033     [ -n "$DEBUG_SIZE_SAVED" ] && \
3034         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
3035     DEBUG_SIZE_SAVED=""
3036 }
3037
3038 start_full_debug_logging() {
3039     debugsave
3040     debug_size_save
3041
3042     local FULLDEBUG=-1
3043     local DEBUG_SIZE=150
3044
3045     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
3046     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
3047 }
3048
3049 stop_full_debug_logging() {
3050     debug_size_restore
3051     debugrestore
3052 }
3053
3054 ##################################
3055 # Test interface
3056 ##################################
3057
3058 error_noexit() {
3059     local TYPE=${TYPE:-"FAIL"}
3060
3061     local dump=true
3062     # do not dump logs if $1=false
3063     if [ "x$1" = "xfalse" ]; then
3064         shift
3065         dump=false
3066     fi
3067
3068     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
3069
3070     # We need to dump the logs on all nodes
3071     if $dump; then
3072         gather_logs $(comma_list $(nodes_list)) 0
3073     fi
3074
3075     debugrestore
3076     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
3077     echo "$@" > $LOGDIR/err
3078 }
3079
3080 exit_status () {
3081     local status=0
3082     local log=$TESTSUITELOG
3083
3084     [ -f "$log" ] && grep -q FAIL: $log && status=1
3085     exit $status
3086 }
3087
3088 error() {
3089     error_noexit "$@"
3090     exit 1
3091 }
3092
3093 error_exit() {
3094     error "$@"
3095 }
3096
3097 # use only if we are ignoring failures for this test, bugno required.
3098 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
3099 # e.g. error_ignore 5494 "your message"
3100 error_ignore() {
3101     local TYPE="IGNORE (bz$1)"
3102     shift
3103     error_noexit "$@"
3104 }
3105
3106 skip_env () {
3107     $FAIL_ON_SKIP_ENV && error false $@ || skip $@
3108 }
3109
3110 skip () {
3111     echo
3112     log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
3113     [ "$ALWAYS_SKIPPED" ] && \
3114         skip_logged ${TESTNAME} "$@" || true
3115     [ "$TESTSUITELOG" ] && \
3116         echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
3117 }
3118
3119 build_test_filter() {
3120     EXCEPT="$EXCEPT $(testslist_filter)"
3121
3122     [ "$ONLY" ] && log "only running test `echo $ONLY`"
3123     for O in $ONLY; do
3124         eval ONLY_${O}=true
3125     done
3126     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
3127         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
3128     [ "$EXCEPT_SLOW" ] && \
3129         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
3130     for E in $EXCEPT; do
3131         eval EXCEPT_${E}=true
3132     done
3133     for E in $ALWAYS_EXCEPT; do
3134         eval EXCEPT_ALWAYS_${E}=true
3135     done
3136     for E in $EXCEPT_SLOW; do
3137         eval EXCEPT_SLOW_${E}=true
3138     done
3139     for G in $GRANT_CHECK_LIST; do
3140         eval GCHECK_ONLY_${G}=true
3141         done
3142 }
3143
3144 basetest() {
3145     if [[ $1 = [a-z]* ]]; then
3146         echo $1
3147     else
3148         echo ${1%%[a-z]*}
3149     fi
3150 }
3151
3152 # print a newline if the last test was skipped
3153 export LAST_SKIPPED=
3154 export ALWAYS_SKIPPED=
3155 #
3156 # Main entry into test-framework. This is called with the name and
3157 # description of a test. The name is used to find the function to run
3158 # the test using "test_$name".
3159 #
3160 # This supports a variety of methods of specifying specific test to
3161 # run or not run.  These need to be documented...
3162 #
3163 run_test() {
3164     assert_DIR
3165
3166     export base=`basetest $1`
3167     if [ ! -z "$ONLY" ]; then
3168         testname=ONLY_$1
3169         if [ ${!testname}x != x ]; then
3170             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
3171             run_one_logged $1 "$2"
3172             return $?
3173         fi
3174         testname=ONLY_$base
3175         if [ ${!testname}x != x ]; then
3176             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
3177             run_one_logged $1 "$2"
3178             return $?
3179         fi
3180         LAST_SKIPPED="y"
3181         echo -n "."
3182         return 0
3183     fi
3184     testname=EXCEPT_$1
3185     if [ ${!testname}x != x ]; then
3186         LAST_SKIPPED="y"
3187         TESTNAME=test_$1 skip "skipping excluded test $1"
3188         return 0
3189     fi
3190     testname=EXCEPT_$base
3191     if [ ${!testname}x != x ]; then
3192         LAST_SKIPPED="y"
3193         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
3194         return 0
3195     fi
3196     testname=EXCEPT_ALWAYS_$1
3197     if [ ${!testname}x != x ]; then
3198         LAST_SKIPPED="y"
3199         ALWAYS_SKIPPED="y"
3200         TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1"
3201         return 0
3202     fi
3203     testname=EXCEPT_ALWAYS_$base
3204     if [ ${!testname}x != x ]; then
3205         LAST_SKIPPED="y"
3206         ALWAYS_SKIPPED="y"
3207         TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1 (base $base)"
3208         return 0
3209     fi
3210     testname=EXCEPT_SLOW_$1
3211     if [ ${!testname}x != x ]; then
3212         LAST_SKIPPED="y"
3213         TESTNAME=test_$1 skip "skipping SLOW test $1"
3214         return 0
3215     fi
3216     testname=EXCEPT_SLOW_$base
3217     if [ ${!testname}x != x ]; then
3218         LAST_SKIPPED="y"
3219         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
3220         return 0
3221     fi
3222
3223     LAST_SKIPPED=
3224     ALWAYS_SKIPPED=
3225     run_one_logged $1 "$2"
3226
3227     return $?
3228 }
3229
3230 equals_msg() {
3231     banner "$*"
3232 }
3233
3234 log() {
3235     echo "$*"
3236     module_loaded lnet || load_modules
3237
3238     local MSG="$*"
3239     # Get rid of '
3240     MSG=${MSG//\'/\\\'}
3241     MSG=${MSG//\(/\\\(}
3242     MSG=${MSG//\)/\\\)}
3243     MSG=${MSG//\;/\\\;}
3244     MSG=${MSG//\|/\\\|}
3245     MSG=${MSG//\>/\\\>}
3246     MSG=${MSG//\</\\\<}
3247     MSG=${MSG//\//\\\/}
3248     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
3249 }
3250
3251 trace() {
3252         log "STARTING: $*"
3253         strace -o $TMP/$1.strace -ttt $*
3254         RC=$?
3255         log "FINISHED: $*: rc $RC"
3256         return 1
3257 }
3258
3259 complete () {
3260     equals_msg $1 test complete, duration $2 sec
3261     [ -f "$TESTSUITELOG" ] && egrep .FAIL $TESTSUITELOG || true
3262     echo duration $2 >>$TESTSUITELOG
3263 }
3264
3265 pass() {
3266     # Set TEST_STATUS here; will be used for logging the result
3267     if [ -f $LOGDIR/err ]; then
3268         TEST_STATUS="FAIL"
3269     else
3270         TEST_STATUS="PASS"
3271     fi
3272     echo "$TEST_STATUS $@" 2>&1 | tee -a $TESTSUITELOG
3273 }
3274
3275 check_mds() {
3276     local FFREE=$(do_node $SINGLEMDS \
3277         lctl get_param -n osd*.*MDT*.filesfree | calc_sum)
3278     local FTOTAL=$(do_node $SINGLEMDS \
3279         lctl get_param -n osd*.*MDT*.filestotal | calc_sum)
3280
3281     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
3282 }
3283
3284 reset_fail_loc () {
3285     echo -n "Resetting fail_loc on all nodes..."
3286     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
3287     echo done.
3288 }
3289
3290
3291 #
3292 # Log a message (on all nodes) padded with "=" before and after. 
3293 # Also appends a timestamp and prepends the testsuite name.
3294
3295
3296 EQUALS="===================================================================================================="
3297 banner() {
3298     msg="== ${TESTSUITE} $*"
3299     last=${msg: -1:1}
3300     [[ $last != "=" && $last != " " ]] && msg="$msg "
3301     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
3302     # always include at least == after the message
3303     log "$msg== $(date +"%H:%M:%S (%s)")"
3304 }
3305
3306 #
3307 # Run a single test function and cleanup after it.  
3308 #
3309 # This function should be run in a subshell so the test func can
3310 # exit() without stopping the whole script.
3311 #
3312 run_one() {
3313     local testnum=$1
3314     local message=$2
3315     tfile=f${testnum}
3316     export tdir=d0.${TESTSUITE}/d${base}
3317     export TESTNAME=test_$testnum
3318     local SAVE_UMASK=`umask`
3319     umask 0022
3320
3321     banner "test $testnum: $message"
3322     test_${testnum} || error "test_$testnum failed with $?"
3323     cd $SAVE_PWD
3324     reset_fail_loc
3325     check_grant ${testnum} || error "check_grant $testnum failed with $?"
3326     check_catastrophe || error "LBUG/LASSERT detected"
3327     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
3328     unset TESTNAME
3329     unset tdir
3330     umask $SAVE_UMASK
3331     return 0
3332 }
3333
3334 #
3335 # Wrapper around run_one to ensure:
3336 #  - test runs in subshell
3337 #  - output of test is saved to separate log file for error reporting
3338 #  - test result is saved to data file
3339 #
3340 run_one_logged() {
3341     local BEFORE=`date +%s`
3342     local TEST_ERROR
3343     local name=${TESTSUITE}.test_${1}.test_log.$(hostname -s).log
3344     local test_log=$LOGDIR/$name
3345     rm -rf $LOGDIR/err
3346     local SAVE_UMASK=`umask`
3347     umask 0022
3348
3349     echo
3350     log_sub_test_begin test_${1}
3351     (run_one $1 "$2") 2>&1 | tee -i $test_log
3352     local RC=${PIPESTATUS[0]}
3353
3354     [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] && \
3355         echo "test_$1 returned $RC" | tee $LOGDIR/err
3356
3357     duration=$((`date +%s` - $BEFORE))
3358     pass "$1" "(${duration}s)"
3359     [ -f $LOGDIR/err ] && TEST_ERROR=$(cat $LOGDIR/err)
3360     log_sub_test_end $TEST_STATUS $duration "$RC" "$TEST_ERROR"
3361
3362     if [ -f $LOGDIR/err ]; then
3363         $FAIL_ON_ERROR && exit $RC
3364     fi
3365
3366     umask $SAVE_UMASK
3367
3368     return 0
3369 }
3370
3371 #
3372 # Print information of skipped tests to result.yml
3373 #
3374 skip_logged(){
3375     log_sub_test_begin $1
3376     log_sub_test_end "SKIP" "0" "0" "\"$2\""
3377 }
3378
3379 canonical_path() {
3380     (cd `dirname $1`; echo $PWD/`basename $1`)
3381 }
3382
3383
3384 check_grant() {
3385     export base=`basetest $1`
3386     [ "$CHECK_GRANT" == "no" ] && return 0
3387
3388         testname=GCHECK_ONLY_${base}
3389         [ ${!testname}x == x ] && return 0
3390
3391     echo -n "checking grant......"
3392
3393         local clients=$CLIENTS
3394         [ -z $clients ] && clients=$(hostname)
3395
3396     # sync all the data and make sure no pending data on server
3397     do_nodes $clients sync
3398
3399     # get client grant
3400     client_grant=`do_nodes $clients \
3401                     "$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes" | \
3402                     awk '{total += $1} END{print total}'`
3403
3404     # get server grant
3405     server_grant=`do_nodes $(comma_list $(osts_nodes)) \
3406                     "$LCTL get_param -n obdfilter.${FSNAME}-OST*.tot_granted" | \
3407                     awk '{total += $1} END{print total}'`
3408
3409     # check whether client grant == server grant
3410     if [ $client_grant -ne $server_grant ]; then
3411         echo "failed: client:${client_grant} server: ${server_grant}."
3412         do_nodes $(comma_list $(osts_nodes)) \
3413                    "$LCTL get_param obdfilter.${FSNAME}-OST*.tot*"
3414         do_nodes $clients "$LCTL get_param osc.${FSNAME}-*.cur_*_bytes"
3415         return 1
3416     else
3417         echo "pass: client:${client_grant} server: ${server_grant}"
3418     fi
3419
3420 }
3421
3422 ########################
3423 # helper functions
3424
3425 osc_to_ost()
3426 {
3427     osc=$1
3428     ost=`echo $1 | awk -F_ '{print $3}'`
3429     if [ -z $ost ]; then
3430         ost=`echo $1 | sed 's/-osc.*//'`
3431     fi
3432     echo $ost
3433 }
3434
3435 ostuuid_from_index()
3436 {
3437     $LFS osts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
3438 }
3439
3440 ostname_from_index() {
3441     local uuid=$(ostuuid_from_index $1)
3442     echo ${uuid/_UUID/}
3443 }
3444
3445 index_from_ostuuid()
3446 {
3447     $LFS osts $2 | sed -ne "/${1}/s/\(.*\): .* .*$/\1/p"
3448 }
3449
3450 mdtuuid_from_index()
3451 {
3452     $LFS mdts $2 | awk '/^'$1'/ { print $2 }'
3453 }
3454
3455 remote_node () {
3456     local node=$1
3457     [ "$node" != "$(hostname)" ]
3458 }
3459
3460 remote_mds ()
3461 {
3462     local node
3463     for node in $(mdts_nodes); do
3464         remote_node $node && return 0
3465     done
3466     return 1
3467 }
3468
3469 remote_mds_nodsh()
3470 {
3471     [ "$CLIENTONLY" ] && return 0 || true
3472     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
3473 }
3474
3475 require_dsh_mds()
3476 {
3477         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
3478             MSKIPPED=1 && return 1
3479         return 0
3480 }
3481
3482 remote_ost ()
3483 {
3484     local node
3485     for node in $(osts_nodes) ; do
3486         remote_node $node && return 0
3487     done
3488     return 1
3489 }
3490
3491 remote_ost_nodsh()
3492 {
3493     [ "$CLIENTONLY" ] && return 0 || true 
3494     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
3495 }
3496
3497 require_dsh_ost()
3498 {
3499         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
3500             OSKIPPED=1 && return 1
3501         return 0
3502 }
3503
3504 remote_mgs_nodsh()
3505 {
3506     local MGS 
3507     MGS=$(facet_host mgs)
3508     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
3509 }
3510
3511 local_mode ()
3512 {
3513     remote_mds_nodsh || remote_ost_nodsh || \
3514         $(single_local_node $(comma_list $(nodes_list)))
3515 }
3516
3517 mdts_nodes () {
3518     local MDSNODES
3519     local NODES_sort
3520     for num in `seq $MDSCOUNT`; do
3521         MDSNODES="$MDSNODES $(facet_host mds$num)"
3522     done
3523     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
3524
3525     echo $NODES_sort
3526 }
3527
3528 remote_servers () {
3529     remote_ost && remote_mds
3530 }
3531
3532 facets_nodes () {
3533     local facets=$1
3534     local nodes
3535     local NODES_sort
3536
3537     for facet in ${facets//,/ }; do
3538         if [ "$FAILURE_MODE" = HARD ]; then
3539             nodes="$nodes $(facet_active_host $facet)"
3540         else
3541             nodes="$nodes $(facet_host $facet)"
3542         fi
3543     done
3544     NODES_sort=$(for i in $nodes; do echo $i; done | sort -u)
3545
3546     echo $NODES_sort
3547 }
3548
3549 osts_nodes () {
3550     local facets=$(get_facets OST)
3551     local nodes=$(facets_nodes $facets)
3552
3553     echo $nodes
3554 }
3555
3556 nodes_list () {
3557     # FIXME. We need a list of clients
3558     local myNODES=$HOSTNAME
3559     local myNODES_sort
3560
3561     # CLIENTS (if specified) contains the local client
3562     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
3563
3564     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
3565         myNODES="$myNODES $(facets_nodes $(get_facets))"
3566     fi
3567
3568     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
3569
3570     echo $myNODES_sort
3571 }
3572
3573 remote_nodes_list () {
3574     local rnodes=$(nodes_list)
3575     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
3576     echo $rnodes
3577 }
3578
3579 init_clients_lists () {
3580     # Sanity check: exclude the local client from RCLIENTS
3581     local clients=$(hostlist_expand "$RCLIENTS")
3582     local rclients=$(exclude_items_from_list "$clients" $HOSTNAME)
3583
3584     # Sanity check: exclude the dup entries
3585     RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)
3586
3587     clients="$SINGLECLIENT $HOSTNAME $RCLIENTS"
3588
3589     # Sanity check: exclude the dup entries from CLIENTS
3590     # for those configs which has SINGLCLIENT set to local client
3591     clients=$(for i in $clients; do echo $i; done | sort -u)
3592
3593     CLIENTS=$(comma_list $clients)
3594     local -a remoteclients=($RCLIENTS)
3595     for ((i=0; $i<${#remoteclients[@]}; i++)); do
3596             varname=CLIENT$((i + 2))
3597             eval $varname=${remoteclients[i]}
3598     done
3599
3600     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
3601 }
3602
3603 get_random_entry () {
3604     local rnodes=$1
3605
3606     rnodes=${rnodes//,/ }
3607
3608     local -a nodes=($rnodes)
3609     local num=${#nodes[@]} 
3610     local i=$((RANDOM * num * 2 / 65536))
3611
3612     echo ${nodes[i]}
3613 }
3614
3615 client_only () {
3616     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
3617 }
3618
3619 is_patchless ()
3620 {
3621     lctl get_param version | grep -q patchless
3622 }
3623
3624 check_versions () {
3625     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
3626 }
3627
3628 get_node_count() {
3629     local nodes="$@"
3630     echo $nodes | wc -w || true
3631 }
3632
3633 mixed_ost_devs () {
3634     local nodes=$(osts_nodes)
3635     local osscount=$(get_node_count "$nodes")
3636     [ ! "$OSTCOUNT" = "$osscount" ]
3637 }
3638
3639 mixed_mdt_devs () {
3640     local nodes=$(mdts_nodes)
3641     local mdtcount=$(get_node_count "$nodes")
3642     [ ! "$MDSCOUNT" = "$mdtcount" ]
3643 }
3644
3645 generate_machine_file() {
3646     local nodes=${1//,/ }
3647     local machinefile=$2
3648     rm -f $machinefile
3649     for node in $nodes; do
3650         echo $node >>$machinefile || \
3651             { echo "can not generate machinefile $machinefile" && return 1; }
3652     done
3653 }
3654
3655 get_stripe () {
3656     local file=$1/stripe
3657     touch $file
3658     $LFS getstripe -v $file || error
3659     rm -f $file
3660 }
3661
3662 setstripe_nfsserver () {
3663     local dir=$1
3664
3665     local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
3666                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -1)
3667
3668     [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
3669
3670     do_nodev $nfsserver lfs setstripe "$@"
3671 }
3672
3673 check_runas_id_ret() {
3674     local myRC=0
3675     local myRUNAS_UID=$1
3676     local myRUNAS_GID=$2
3677     shift 2
3678     local myRUNAS=$@
3679     if [ -z "$myRUNAS" ]; then
3680         error_exit "myRUNAS command must be specified for check_runas_id"
3681     fi
3682     if $GSS_KRB5; then
3683         $myRUNAS krb5_login.sh || \
3684             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
3685     fi
3686     mkdir $DIR/d0_runas_test
3687     chmod 0755 $DIR
3688     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
3689     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
3690     rm -rf $DIR/d0_runas_test
3691     return $myRC
3692 }
3693
3694 check_runas_id() {
3695     local myRUNAS_UID=$1
3696     local myRUNAS_GID=$2
3697     shift 2
3698     local myRUNAS=$@
3699     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
3700         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
3701         Please set RUNAS_ID to some UID which exists on MDS and client or
3702         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
3703 }
3704
3705 # obtain the UID/GID for MPI_USER
3706 get_mpiuser_id() {
3707     local mpi_user=$1
3708
3709     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
3710 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
3711
3712     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
3713 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
3714 }
3715
3716 # obtain and cache Kerberos ticket-granting ticket
3717 refresh_krb5_tgt() {
3718     local myRUNAS_UID=$1
3719     local myRUNAS_GID=$2
3720     shift 2
3721     local myRUNAS=$@
3722     if [ -z "$myRUNAS" ]; then
3723         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
3724     fi
3725
3726     CLIENTS=${CLIENTS:-$HOSTNAME}
3727     do_nodes $CLIENTS "set -x
3728 if ! $myRUNAS krb5_login.sh; then
3729     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
3730     exit 1
3731 fi"
3732 }
3733
3734 # Run multiop in the background, but wait for it to print
3735 # "PAUSING" to its stdout before returning from this function.
3736 multiop_bg_pause() {
3737     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
3738     FILE=$1
3739     ARGS=$2
3740
3741     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
3742     mkfifo $TMPPIPE
3743
3744     echo "$MULTIOP_PROG $FILE v$ARGS"
3745     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
3746
3747     echo "TMPPIPE=${TMPPIPE}"
3748     read -t 60 multiop_output < $TMPPIPE
3749     if [ $? -ne 0 ]; then
3750         rm -f $TMPPIPE
3751         return 1
3752     fi
3753     rm -f $TMPPIPE
3754     if [ "$multiop_output" != "PAUSING" ]; then
3755         echo "Incorrect multiop output: $multiop_output"
3756         kill -9 $PID
3757         return 1
3758     fi
3759
3760     return 0
3761 }
3762
3763 do_and_time () {
3764     local cmd=$1
3765     local rc
3766
3767     SECONDS=0
3768     eval '$cmd'
3769     
3770     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
3771
3772     echo $SECONDS
3773     return $rc
3774 }
3775
3776 inodes_available () {
3777     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
3778     echo $IFree
3779 }
3780
3781 mdsrate_inodes_available () {
3782     local min_inodes=$(inodes_available)
3783     echo $((min_inodes * 99 / 100))
3784 }
3785
3786 # reset llite stat counters
3787 clear_llite_stats(){
3788         lctl set_param -n llite.*.stats 0
3789 }
3790
3791 # sum llite stat items
3792 calc_llite_stats() {
3793         local res=$(lctl get_param -n llite.*.stats |
3794                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
3795         echo $res
3796 }
3797
3798 # reset osc stat counters
3799 clear_osc_stats(){
3800         lctl set_param -n osc.*.osc_stats 0
3801 }
3802
3803 # sum osc stat items
3804 calc_osc_stats() {
3805         local res=$(lctl get_param -n osc.*.osc_stats |
3806                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
3807         echo $res
3808 }
3809
3810 calc_sum () {
3811         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
3812 }
3813
3814 calc_osc_kbytes () {
3815         df $MOUNT > /dev/null
3816         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
3817 }
3818
3819 # save_lustre_params(node, parameter_mask)
3820 # generate a stream of formatted strings (<node> <param name>=<param value>)
3821 save_lustre_params() {
3822         local s
3823         do_nodesv $1 "lctl get_param $2 | while read s; do echo \\\$s; done"
3824 }
3825
3826 # restore lustre parameters from input stream, produces by save_lustre_params
3827 restore_lustre_params() {
3828         local node
3829         local name
3830         local val
3831         while IFS=" =" read node name val; do
3832                 do_node ${node//:/} "lctl set_param -n $name $val"
3833         done
3834 }
3835
3836 check_catastrophe() {
3837     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
3838     local C=$CATASTROPHE
3839     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
3840
3841     if [ $rnodes ]; then
3842         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
3843 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
3844 exit \\\$rc;"
3845     fi 
3846 }
3847
3848 # $1 node
3849 # $2 file
3850 # $3 $RUNAS
3851 get_stripe_info() {
3852         local tmp_file
3853
3854         stripe_size=0
3855         stripe_count=0
3856         stripe_index=0
3857         tmp_file=$(mktemp)
3858
3859         do_facet $1 $3 lfs getstripe -v $2 > $tmp_file
3860
3861         stripe_size=`awk '$1 ~ /size/ {print $2}' $tmp_file`
3862         stripe_count=`awk '$1 ~ /count/ {print $2}' $tmp_file`
3863         stripe_index=`awk '$1 ~ /stripe_offset/ {print $2}' $tmp_file`
3864         rm -f $tmp_file
3865 }
3866
3867 # CMD: determine mds index where directory inode presents
3868 get_mds_dir () {
3869     local dir=$1
3870     local file=$dir/f0.get_mds_dir_tmpfile
3871
3872     mkdir -p $dir
3873     rm -f $file
3874     sleep 1
3875     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
3876     local -a oldused=($iused)
3877
3878     openfile -f O_CREAT:O_LOV_DELAY_CREATE -m 0644 $file > /dev/null
3879     sleep 1
3880     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
3881     local -a newused=($iused)
3882
3883     local num=0
3884     for ((i=0; i<${#newused[@]}; i++)); do
3885          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
3886              echo $(( i + 1 ))
3887              rm -f $file
3888              return 0
3889          fi
3890     done
3891     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
3892 }
3893
3894 mdsrate_cleanup () {
3895     if [ -d $4 ]; then
3896         mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
3897         rmdir $4
3898     fi
3899 }
3900
3901 delayed_recovery_enabled () {
3902     local var=${SINGLEMDS}_svc
3903     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
3904 }
3905
3906 ########################
3907
3908 convert_facet2label() { 
3909     local facet=$1
3910
3911     if [ x$facet = xost ]; then
3912        facet=ost1
3913     fi
3914
3915     local varsvc=${facet}_svc
3916
3917     if [ -n ${!varsvc} ]; then
3918         echo ${!varsvc}
3919     else  
3920         error "No lablel for $facet!"
3921     fi
3922 }
3923
3924 get_clientosc_proc_path() {
3925     echo "${1}-osc-[^M]*"
3926 }
3927
3928 get_lustre_version () {
3929     local facet=${1:-"$SINGLEMDS"}    
3930     do_facet $facet $LCTL get_param -n version |  awk '/^lustre:/ {print $2}'
3931 }
3932
3933 get_mds_version_major () {
3934     local facet=${1:-"$SINGLEMDS"}
3935     local version=$(get_lustre_version $facet)
3936     echo $version | awk -F. '{print $1}'
3937 }
3938
3939 get_mds_version_minor () {
3940     local facet=${1:-"$SINGLEMDS"}
3941     local version=$(get_lustre_version $facet)
3942     echo $version | awk -F. '{print $2}'
3943 }
3944
3945 # If the 2.0 MDS was mounted on 1.8 device, then the OSC and LOV names
3946 # used by MDT would not be changed.
3947 # mdt lov: fsname-mdtlov
3948 # mdt osc: fsname-OSTXXXX-osc
3949 mds_on_old_device() {
3950     local mds=${1:-"$SINGLEMDS"}
3951     local major=$(get_mds_version_major $mds)
3952     local minor=$(get_mds_version_minor $mds)
3953
3954     if [ $major -ge 2 ] || [ $major -eq 1 -a $minor -gt 8 ]; then
3955         do_facet $mds "lctl list_param osc.$FSNAME-OST*-osc \
3956             > /dev/null 2>&1" && return 0
3957     fi
3958     return 1
3959 }
3960
3961 get_mdtosc_proc_path() {
3962     local mds_facet=$1
3963     local ost_label=${2:-"*OST*"}
3964
3965     [ "$mds_facet" = "mds" ] && mds_facet=$SINGLEMDS
3966     local mdt_label=$(convert_facet2label $mds_facet)
3967     local mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')
3968
3969     local major=$(get_mds_version_major $mds_facet)
3970     local minor=$(get_mds_version_minor $mds_facet)
3971     if [ $major -le 1 -a $minor -le 8 ] || mds_on_old_device $mds_facet; then
3972         echo "${ost_label}-osc"
3973     else
3974         echo "${ost_label}-osc-${mdt_index}"
3975     fi
3976 }
3977
3978 get_osc_import_name() {
3979     local facet=$1
3980     local ost=$2
3981     local label=$(convert_facet2label $ost)
3982
3983     if [ "${facet:0:3}" = "mds" ]; then
3984         get_mdtosc_proc_path $facet $label
3985         return 0
3986     fi
3987
3988     get_clientosc_proc_path $label
3989     return 0
3990 }
3991
3992 _wait_import_state () {
3993     local expected=$1
3994     local CONN_PROC=$2
3995     local maxtime=${3:-$(max_recovery_time)}
3996     local CONN_STATE
3997     local i=0
3998
3999     CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
4000     while [ "${CONN_STATE}" != "${expected}" ]; do
4001         if [ "${expected}" == "DISCONN" ]; then
4002             # for disconn we can check after proc entry is removed
4003             [ "x${CONN_STATE}" == "x" ] && return 0
4004             #  with AT enabled, we can have connect request timeout near of
4005             # reconnect timeout and test can't see real disconnect
4006             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
4007         fi
4008         [ $i -ge $maxtime ] && \
4009             error "can't put import for $CONN_PROC into ${expected} state after $i sec, have ${CONN_STATE}" && \
4010             return 1
4011         sleep 1
4012         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
4013         i=$(($i + 1))
4014     done
4015
4016     log "$CONN_PROC in ${CONN_STATE} state after $i sec"
4017     return 0
4018 }
4019
4020 wait_import_state() {
4021     local state=$1
4022     local params=$2
4023     local maxtime=${3:-$(max_recovery_time)}
4024     local param
4025
4026     for param in ${params//,/ }; do
4027         _wait_import_state $state $param $maxtime || return
4028     done
4029 }
4030
4031 # One client request could be timed out because server was not ready
4032 # when request was sent by client.
4033 # The request timeout calculation details :
4034 # ptl_send_rpc ()
4035 #      /* We give the server rq_timeout secs to process the req, and
4036 #      add the network latency for our local timeout. */
4037 #      request->rq_deadline = request->rq_sent + request->rq_timeout +
4038 #           ptlrpc_at_get_net_latency(request) ;
4039 #
4040 # ptlrpc_connect_import ()
4041 #      request->rq_timeout = INITIAL_CONNECT_TIMEOUT
4042 #
4043 # init_imp_at () ->
4044 #   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0
4045 # ptlrpc_at_get_net_latency(request) ->
4046 #       at_get (max (iat_net_latency=0, at_min)) = at_min
4047 #
4048 # i.e.:
4049 # request->rq_timeout + ptlrpc_at_get_net_latency(request) =
4050 # INITIAL_CONNECT_TIMEOUT + at_min
4051 #
4052 # We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT
4053 # because we can not get this value in runtime,
4054 # the value depends on configure options, and it is not stored in /proc.
4055 # obd_support.h:
4056 # #define CONNECTION_SWITCH_MIN 5U
4057 # #ifndef CRAY_XT3
4058 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
4059 # #else
4060 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/2)
4061
4062 request_timeout () {
4063     local facet=$1
4064
4065     # request->rq_timeout = INITIAL_CONNECT_TIMEOUT
4066     local init_connect_timeout=$TIMEOUT
4067     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
4068
4069     local at_min=$(at_get $facet at_min)
4070
4071     echo $(( init_connect_timeout + at_min ))
4072 }
4073
4074 wait_osc_import_state() {
4075     local facet=$1
4076     local ost_facet=$2
4077     local expected=$3
4078     local ost=$(get_osc_import_name $facet $ost_facet)
4079
4080     local param="osc.${ost}.ost_server_uuid"
4081
4082     # 1. wait the deadline of client 1st request (it could be skipped)
4083     # 2. wait the deadline of client 2nd request
4084     local maxtime=$(( 2 * $(request_timeout $facet)))
4085
4086     if ! do_rpc_nodes $(facet_host $facet) \
4087                 _wait_import_state $expected $param $maxtime; then
4088         error "import is not in ${expected} state"
4089         return 1
4090     fi
4091
4092     return 0
4093 }
4094
4095 get_clientmdc_proc_path() {
4096     echo "${1}-mdc-*"
4097 }
4098
4099 do_rpc_nodes () {
4100     local list=$1
4101     shift
4102
4103     # Add paths to lustre tests for 32 and 64 bit systems.
4104     local RPATH="PATH=$RLUSTRE/tests:/usr/lib/lustre/tests:/usr/lib64/lustre/tests:$PATH"
4105     do_nodesv $list "${RPATH} NAME=${NAME} sh rpc.sh $@ "
4106 }
4107
4108 wait_clients_import_state () {
4109     local list=$1
4110     local facet=$2
4111     local expected=$3
4112
4113     local facets=$facet
4114
4115     if [ "$FAILURE_MODE" = HARD ]; then
4116         facets=$(facets_on_host $(facet_active_host $facet))
4117     fi
4118
4119     for facet in ${facets//,/ }; do
4120     local label=$(convert_facet2label $facet)
4121     local proc_path
4122     case $facet in
4123         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
4124         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
4125         *) error "unknown facet!" ;;
4126     esac
4127     local params=$(expand_list $params $proc_path)
4128     done
4129
4130     if ! do_rpc_nodes $list wait_import_state $expected $params; then
4131         error "import is not in ${expected} state"
4132         return 1
4133     fi
4134 }
4135
4136 oos_full() {
4137         local -a AVAILA
4138         local -a GRANTA
4139         local OSCFULL=1
4140         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
4141                   $LCTL get_param obdfilter.*.kbytesavail))
4142         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
4143                   $LCTL get_param -n obdfilter.*.tot_granted))
4144         for ((i=0; i<${#AVAILA[@]}; i++)); do
4145                 local -a AVAIL1=(${AVAILA[$i]//=/ })
4146                 GRANT=$((${GRANTA[$i]}/1024))
4147                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} grnt=$GRANT diff=$((AVAIL1[1] - GRANT))
4148                 [ $((AVAIL1[1] - GRANT)) -lt 400 ] && OSCFULL=0 && echo " FULL" || echo
4149         done
4150         return $OSCFULL
4151 }
4152
4153 pool_list () {
4154    do_facet mgs lctl pool_list $1
4155 }
4156
4157 create_pool() {
4158     local fsname=${1%%.*}
4159     local poolname=${1##$fsname.}
4160
4161     do_facet mgs lctl pool_new $1
4162     local RC=$?
4163     # get param should return err unless pool is created
4164     [[ $RC -ne 0 ]] && return $RC
4165
4166     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
4167         2>/dev/null || echo foo" "" || RC=1
4168     if [[ $RC -eq 0 ]]; then
4169         add_pool_to_list $1
4170     else
4171         error "pool_new failed $1"
4172     fi
4173     return $RC
4174 }
4175
4176 add_pool_to_list () {
4177     local fsname=${1%%.*}
4178     local poolname=${1##$fsname.}
4179
4180     local listvar=${fsname}_CREATED_POOLS
4181     eval export ${listvar}=$(expand_list ${!listvar} $poolname)
4182 }
4183
4184 remove_pool_from_list () {
4185     local fsname=${1%%.*}
4186     local poolname=${1##$fsname.}
4187
4188     local listvar=${fsname}_CREATED_POOLS
4189     eval export ${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
4190 }
4191
4192 destroy_pool_int() {
4193     local ost
4194     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
4195         awk '$1 !~ /^Pool:/ {print $1}')
4196     for ost in $OSTS; do
4197         do_facet mgs lctl pool_remove $1 $ost
4198     done
4199     do_facet mgs lctl pool_destroy $1
4200 }
4201
4202 # <fsname>.<poolname> or <poolname>
4203 destroy_pool() {
4204     local fsname=${1%%.*}
4205     local poolname=${1##$fsname.}
4206
4207     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
4208
4209     local RC
4210
4211     pool_list $fsname.$poolname || return $?
4212
4213     destroy_pool_int $fsname.$poolname
4214     RC=$?
4215     [[ $RC -ne 0 ]] && return $RC
4216
4217     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
4218       2>/dev/null || echo foo" "foo" || RC=1
4219
4220     if [[ $RC -eq 0 ]]; then
4221         remove_pool_from_list $fsname.$poolname
4222     else
4223         error "destroy pool failed $1"
4224     fi
4225     return $RC
4226 }
4227
4228 destroy_pools () {
4229     local fsname=${1:-$FSNAME}
4230     local poolname
4231     local listvar=${fsname}_CREATED_POOLS
4232
4233     pool_list $fsname
4234
4235     [ x${!listvar} = x ] && return 0
4236
4237     echo destroy the created pools: ${!listvar}
4238     for poolname in ${!listvar//,/ }; do
4239         destroy_pool $fsname.$poolname 
4240     done
4241 }
4242
4243 cleanup_pools () {
4244     local fsname=${1:-$FSNAME}
4245     trap 0
4246     destroy_pools $fsname
4247 }
4248
4249 gather_logs () {
4250     local list=$1
4251     local tar_logs=$2
4252
4253     local ts=$(date +%s)
4254     local docp=true
4255     [ -f $LOGDIR/shared ] && docp=false
4256  
4257     # dump lustre logs, dmesg
4258
4259     prefix="$TESTLOG_PREFIX.$TESTNAME"
4260     suffix="$ts.log"
4261     echo "Dumping lctl log to ${prefix}.*.${suffix}"
4262
4263     if [ "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
4264         echo "Dumping logs only on local client."
4265         $LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}
4266         dmesg > ${prefix}.dmesg.$(hostname -s).${suffix}
4267         return
4268     fi
4269
4270     do_nodesv $list \
4271         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname -s).${suffix};
4272          dmesg > ${prefix}.dmesg.\\\$(hostname -s).${suffix}"
4273     if [ ! -f $LOGDIR/shared ]; then
4274         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
4275       fi
4276
4277     if [ $tar_logs == 1 ]; then
4278         local archive=$LOGDIR/${TESTSUITE}-$ts.tar.bz2
4279         tar -jcf $archive $LOGDIR/*$ts* $LOGDIR/*${TESTSUITE}*
4280
4281         echo $archive
4282     fi
4283 }
4284
4285 do_ls () {
4286     local mntpt_root=$1
4287     local num_mntpts=$2
4288     local dir=$3
4289     local i
4290     local cmd
4291     local pids
4292     local rc=0
4293
4294     for i in $(seq 0 $num_mntpts); do
4295         cmd="ls -laf ${mntpt_root}$i/$dir"
4296         echo + $cmd;
4297         $cmd > /dev/null &
4298         pids="$pids $!"
4299     done
4300     echo pids=$pids
4301     for pid in $pids; do
4302         wait $pid || rc=$?
4303     done
4304
4305     return $rc
4306 }
4307
4308 # target_start_and_reset_recovery_timer()
4309 #        service_time = at_est2timeout(service_time);
4310 #        service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC +
4311 #                             INITIAL_CONNECT_TIMEOUT);
4312 # CONNECTION_SWITCH_MAX : min(25U, max(CONNECTION_SWITCH_MIN,obd_timeout))
4313 #define CONNECTION_SWITCH_INC 1
4314 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
4315 #define CONNECTION_SWITCH_MIN 5U
4316
4317 max_recovery_time () {
4318     local init_connect_timeout=$(( TIMEOUT / 20 ))
4319     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
4320
4321     local service_time=$(( $(at_max_get client) + $(( 2 * $(( 25 + 1  + init_connect_timeout)) )) ))
4322
4323     echo $service_time 
4324 }
4325
4326 get_clients_mount_count () {
4327     local clients=${CLIENTS:-`hostname`}
4328
4329     # we need to take into account the clients mounts and
4330     # exclude mds/ost mounts if any;
4331     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
4332 }
4333
4334 # gss functions
4335 PROC_CLI="srpc_info"
4336
4337 combination()
4338 {
4339     local M=$1
4340     local N=$2
4341     local R=1
4342
4343     if [ $M -lt $N ]; then
4344         R=0
4345     else
4346         N=$((N + 1))
4347         while [ $N -lt $M ]; do
4348             R=$((R * N))
4349             N=$((N + 1))
4350         done
4351     fi
4352
4353     echo $R
4354     return 0
4355 }
4356
4357 calc_connection_cnt() {
4358     local dir=$1
4359
4360     # MDT->MDT = 2 * C(M, 2)
4361     # MDT->OST = M * O
4362     # CLI->OST = C * O
4363     # CLI->MDT = C * M
4364     comb_m2=$(combination $MDSCOUNT 2)
4365
4366     local num_clients=$(get_clients_mount_count)
4367
4368     local cnt_mdt2mdt=$((comb_m2 * 2))
4369     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
4370     local cnt_cli2ost=$((num_clients * OSTCOUNT))
4371     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
4372     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
4373     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
4374     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
4375
4376     local var=cnt_$dir
4377     local res=${!var}
4378
4379     echo $res
4380 }
4381
4382 set_rule()
4383 {
4384     local tgt=$1
4385     local net=$2
4386     local dir=$3
4387     local flavor=$4
4388     local cmd="$tgt.srpc.flavor"
4389
4390     if [ $net == "any" ]; then
4391         net="default"
4392     fi
4393     cmd="$cmd.$net"
4394
4395     if [ $dir != "any" ]; then
4396         cmd="$cmd.$dir"
4397     fi
4398
4399     cmd="$cmd=$flavor"
4400     log "Setting sptlrpc rule: $cmd"
4401     do_facet mgs "$LCTL conf_param $cmd"
4402 }
4403
4404 count_flvr()
4405 {
4406     local output=$1
4407     local flavor=$2
4408     local count=0
4409
4410     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
4411     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
4412
4413     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
4414
4415     if [ "x$bulkspec" != "x" ]; then
4416         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
4417
4418         if [ "x$algs" != "x" ]; then
4419             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
4420         else
4421             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
4422             if [ $bulk == "bulkn" ]; then
4423                 bulk_count=`echo "$output" | grep "bulk flavor" \
4424                             | grep "null/null" | wc -l`
4425             elif [ $bulk == "bulki" ]; then
4426                 bulk_count=`echo "$output" | grep "bulk flavor" \
4427                             | grep "/null" | grep -v "null/" | wc -l`
4428             else
4429                 bulk_count=`echo "$output" | grep "bulk flavor" \
4430                             | grep -v "/null" | grep -v "null/" | wc -l`
4431             fi
4432         fi
4433
4434         [ $bulk_count -lt $count ] && count=$bulk_count
4435     fi
4436
4437     echo $count
4438 }
4439
4440 flvr_cnt_cli2mdt()
4441 {
4442     local flavor=$1
4443     local cnt
4444
4445     local clients=${CLIENTS:-`hostname`}
4446
4447     for c in ${clients//,/ }; do
4448         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
4449         tmpcnt=`count_flvr "$output" $flavor`
4450         cnt=$((cnt + tmpcnt))
4451     done
4452     echo $cnt
4453 }
4454
4455 flvr_cnt_cli2ost()
4456 {
4457     local flavor=$1
4458     local cnt
4459
4460     local clients=${CLIENTS:-`hostname`}
4461
4462     for c in ${clients//,/ }; do
4463         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
4464         tmpcnt=`count_flvr "$output" $flavor`
4465         cnt=$((cnt + tmpcnt))
4466     done
4467     echo $cnt
4468 }
4469
4470 flvr_cnt_mdt2mdt()
4471 {
4472     local flavor=$1
4473     local cnt=0
4474
4475     if [ $MDSCOUNT -le 1 ]; then
4476         echo 0
4477         return
4478     fi
4479
4480     for num in `seq $MDSCOUNT`; do
4481         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
4482         tmpcnt=`count_flvr "$output" $flavor`
4483         cnt=$((cnt + tmpcnt))
4484     done
4485     echo $cnt;
4486 }
4487
4488 flvr_cnt_mdt2ost()
4489 {
4490     local flavor=$1
4491     local cnt=0
4492     local mdtosc
4493
4494     for num in `seq $MDSCOUNT`; do
4495         mdtosc=$(get_mdtosc_proc_path mds$num)
4496         mdtosc=${mdtosc/-MDT*/-MDT\*}
4497         output=$(do_facet mds$num lctl get_param -n \
4498             osc.$mdtosc.$PROC_CLI 2>/dev/null)
4499         tmpcnt=`count_flvr "$output" $flavor`
4500         cnt=$((cnt + tmpcnt))
4501     done
4502     echo $cnt;
4503 }
4504
4505 flvr_cnt_mgc2mgs()
4506 {
4507     local flavor=$1
4508
4509     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
4510     count_flvr "$output" $flavor
4511 }
4512
4513 do_check_flavor()
4514 {
4515     local dir=$1        # from to
4516     local flavor=$2     # flavor expected
4517     local res=0
4518
4519     if [ $dir == "cli2mdt" ]; then
4520         res=`flvr_cnt_cli2mdt $flavor`
4521     elif [ $dir == "cli2ost" ]; then
4522         res=`flvr_cnt_cli2ost $flavor`
4523     elif [ $dir == "mdt2mdt" ]; then
4524         res=`flvr_cnt_mdt2mdt $flavor`
4525     elif [ $dir == "mdt2ost" ]; then
4526         res=`flvr_cnt_mdt2ost $flavor`
4527     elif [ $dir == "all2ost" ]; then
4528         res1=`flvr_cnt_mdt2ost $flavor`
4529         res2=`flvr_cnt_cli2ost $flavor`
4530         res=$((res1 + res2))
4531     elif [ $dir == "all2mdt" ]; then
4532         res1=`flvr_cnt_mdt2mdt $flavor`
4533         res2=`flvr_cnt_cli2mdt $flavor`
4534         res=$((res1 + res2))
4535     elif [ $dir == "all2all" ]; then
4536         res1=`flvr_cnt_mdt2ost $flavor`
4537         res2=`flvr_cnt_cli2ost $flavor`
4538         res3=`flvr_cnt_mdt2mdt $flavor`
4539         res4=`flvr_cnt_cli2mdt $flavor`
4540         res=$((res1 + res2 + res3 + res4))
4541     fi
4542
4543     echo $res
4544 }
4545
4546 wait_flavor()
4547 {
4548     local dir=$1        # from to
4549     local flavor=$2     # flavor expected
4550     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
4551
4552     local res=0
4553
4554     for ((i=0;i<20;i++)); do
4555         echo -n "checking $dir..."
4556         res=$(do_check_flavor $dir $flavor)
4557         echo "found $res/$expect $flavor connections"
4558         [ $res -ge $expect ] && return 0
4559         sleep 4
4560     done
4561
4562     echo "Error checking $flavor of $dir: expect $expect, actual $res"
4563     return 1
4564 }
4565
4566 restore_to_default_flavor()
4567 {
4568     local proc="mgs.MGS.live.$FSNAME"
4569
4570     echo "restoring to default flavor..."
4571
4572     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
4573
4574     # remove all existing rules if any
4575     if [ $nrule -ne 0 ]; then
4576         echo "$nrule existing rules"
4577         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
4578             echo "remove rule: $rule"
4579             spec=`echo $rule | awk -F = '{print $1}'`
4580             do_facet mgs "$LCTL conf_param -d $spec"
4581         done
4582     fi
4583
4584     # verify no rules left
4585     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
4586     [ $nrule -ne 0 ] && error "still $nrule rules left"
4587
4588     # wait for default flavor to be applied
4589     # currently default flavor for all connections are 'null'
4590     wait_flavor all2all null
4591     echo "now at default flavor settings"
4592 }
4593
4594 set_flavor_all()
4595 {
4596     local flavor=${1:-null}
4597
4598     echo "setting all flavor to $flavor"
4599
4600     # FIXME need parameter to this fn
4601     # and remove global vars
4602     local cnt_all2all=$(calc_connection_cnt all2all)
4603
4604     local res=$(do_check_flavor all2all $flavor)
4605     if [ $res -eq $cnt_all2all ]; then
4606         echo "already have total $res $flavor connections"
4607         return
4608     fi
4609
4610     echo "found $res $flavor out of total $cnt_all2all connections"
4611     restore_to_default_flavor
4612
4613     [[ $flavor = null ]] && return 0
4614
4615     set_rule $FSNAME any any $flavor
4616     wait_flavor all2all $flavor
4617 }
4618
4619
4620 check_logdir() {
4621     local dir=$1
4622     # Checking for shared logdir
4623     if [ ! -d $dir ]; then
4624         # Not found. Create local logdir
4625         mkdir -p $dir
4626     else
4627         touch $dir/node.$(hostname -s).yml
4628     fi
4629     return 0
4630 }
4631
4632 check_write_access() {
4633     local dir=$1
4634     for node in $(nodes_list); do
4635         if [ ! -f "$dir/node.$(short_hostname ${node}).yml" ]; then
4636             # Logdir not accessible/writable from this node.
4637             return 1
4638         fi
4639     done
4640     rm -f $dir/node.*.yml
4641     return 0
4642 }
4643
4644 init_logging() {
4645     if [[ -n $YAML_LOG ]]; then
4646         return
4647     fi
4648     local SAVE_UMASK=`umask`
4649     umask 0000
4650
4651     export YAML_LOG=${LOGDIR}/results.yml
4652     mkdir -p $LOGDIR
4653     init_clients_lists
4654
4655     if [ ! -f $YAML_LOG ]; then       # If the yaml log already exists then we will just append to it
4656       if check_shared_dir $LOGDIR; then
4657           touch $LOGDIR/shared
4658           echo "Logging to shared log directory: $LOGDIR"
4659       else
4660           echo "Logging to local directory: $LOGDIR"
4661       fi
4662
4663       yml_nodes_file $LOGDIR >> $YAML_LOG
4664       yml_results_file >> $YAML_LOG
4665     fi
4666
4667     umask $SAVE_UMASK
4668 }
4669
4670 log_test() {
4671     yml_log_test $1 >> $YAML_LOG
4672 }
4673
4674 log_test_status() {
4675      yml_log_test_status $@ >> $YAML_LOG
4676 }
4677
4678 log_sub_test_begin() {
4679     yml_log_sub_test_begin "$@" >> $YAML_LOG
4680 }
4681
4682 log_sub_test_end() {
4683     yml_log_sub_test_end "$@" >> $YAML_LOG
4684 }
4685
4686 run_llverdev()
4687 {
4688         local dev=$1
4689         local llverdev_opts=$2
4690         local devname=$(basename $1)
4691         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
4692         # loop devices aren't in /proc/partitions
4693         [ "x$size" == "x" ] && local size=$(ls -l $dev | awk '{print $5}')
4694
4695         size=$(($size / 1024 / 1024)) # Gb
4696
4697         local partial_arg=""
4698         # Run in partial (fast) mode if the size
4699         # of a partition > 1 GB
4700         [ $size -gt 1 ] && partial_arg="-p"
4701
4702         llverdev --force $partial_arg $llverdev_opts $dev
4703 }
4704
4705 run_llverfs()
4706 {
4707         local dir=$1
4708         local llverfs_opts=$2
4709         local partial_arg=""
4710         local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB
4711
4712         # Run in partial (fast) mode if the size
4713         # of a partition > 1 GB
4714         [ $size -gt 1 ] && partial_arg="-p"
4715
4716         llverfs $partial_arg $llverfs_opts $dir
4717 }
4718
4719 remove_mdt_files() {
4720     local facet=$1
4721     local mdtdev=$2
4722     shift 2
4723     local files="$@"
4724     local mntpt=$(facet_mntpt $facet)
4725
4726     echo "removing files from $mdtdev on $facet: $files"
4727     mount -t $FSTYPE $MDS_MOUNT_OPTS $mdtdev $mntpt || return $?
4728     rc=0;
4729     for f in $files; do
4730         rm $mntpt/ROOT/$f || { rc=$?; break; }
4731     done
4732     umount -f $mntpt || return $?
4733     return $rc
4734 }
4735
4736 duplicate_mdt_files() {
4737     local facet=$1
4738     local mdtdev=$2
4739     shift 2
4740     local files="$@"
4741     local mntpt=$(facet_mntpt $facet)
4742
4743     echo "duplicating files on $mdtdev on $facet: $files"
4744     mkdir -p $mntpt || return $?
4745     mount -t $FSTYPE $MDS_MOUNT_OPTS $mdtdev $mntpt || return $?
4746
4747     do_umount() {
4748         trap 0
4749         popd > /dev/null
4750         rm $tmp
4751         umount -f $mntpt
4752     }
4753     trap do_umount EXIT
4754
4755     tmp=$(mktemp $TMP/setfattr.XXXXXXXXXX)
4756     pushd $mntpt/ROOT > /dev/null || return $?
4757     rc=0
4758     for f in $files; do
4759         touch $f.bad || return $?
4760         getfattr -n trusted.lov $f | sed "s#$f#&.bad#" > $tmp
4761         rc=${PIPESTATUS[0]}
4762         [ $rc -eq 0 ] || return $rc
4763         setfattr --restore $tmp || return $?
4764     done
4765     do_umount
4766 }
4767
4768 run_sgpdd () {
4769     local devs=${1//,/ }
4770     shift
4771     local params=$@
4772     local rslt=$TMP/sgpdd_survey
4773
4774     # sgpdd-survey cleanups ${rslt}.* files
4775
4776     local cmd="rslt=$rslt $params scsidevs=\"$devs\" $SGPDDSURVEY"
4777     echo + $cmd
4778     eval $cmd
4779     cat ${rslt}.detail
4780 }
4781
4782 # returns the canonical name for an ldiskfs device
4783 ldiskfs_canon() {
4784         local dev="$1"
4785         local facet="$2"
4786
4787         do_facet $facet "dv=\\\$(lctl get_param -n $dev);
4788 if foo=\\\$(lvdisplay -c \\\$dv 2>/dev/null); then
4789     echo dm-\\\${foo##*:};
4790 else
4791     echo \\\$(basename \\\$dv);
4792 fi;"
4793 }
4794
4795 is_sanity_benchmark() {
4796     local benchmarks="dbench bonnie iozone fsx"
4797     local suite=$1
4798     for b in $benchmarks; do
4799         if [ "$b" == "$suite" ]; then
4800             return 0
4801         fi
4802     done
4803     return 1
4804 }
4805
4806 min_ost_size () {
4807     $LCTL get_param -n osc.*.kbytesavail | sort -n | head -n1
4808 }
4809
4810 # Get the block size of the filesystem.
4811 get_block_size() {
4812     local facet=$1
4813     local device=$2
4814     local size
4815
4816     size=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
4817            awk '/^Block size:/ {print $3}')
4818     echo $size
4819 }
4820
4821 # Check whether the "large_xattr" feature is enabled or not.
4822 large_xattr_enabled() {
4823     local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
4824
4825     do_facet $SINGLEMDS "$DUMPE2FS -h $mds_dev 2>&1 | grep -q large_xattr"
4826     return ${PIPESTATUS[0]}
4827 }
4828
4829 # Get the maximum xattr size supported by the filesystem.
4830 max_xattr_size() {
4831     local size
4832
4833     if large_xattr_enabled; then
4834         # include/linux/limits.h: #define XATTR_SIZE_MAX 65536
4835         size=65536
4836     else
4837         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
4838         local block_size=$(get_block_size $SINGLEMDS $mds_dev)
4839
4840         # maximum xattr size = size of block - size of header -
4841         #                      size of 1 entry - 4 null bytes
4842         size=$((block_size - 32 - 32 - 4))
4843     fi
4844
4845     echo $size
4846 }
4847
4848 # Dump the value of the named xattr from a file.
4849 get_xattr_value() {
4850     local xattr_name=$1
4851     local file=$2
4852
4853     echo "$(getfattr -n $xattr_name --absolute-names --only-values $file)"
4854 }
4855
4856 # Generate a string with size of $size bytes.
4857 generate_string() {
4858     local size=${1:-1024} # in bytes
4859
4860     echo "$(head -c $size < /dev/zero | tr '\0' y)"
4861 }