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