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