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