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