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