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