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