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