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