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