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