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