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