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