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