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