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