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