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