Whamcloud - gitweb
b85a480285039b683970756561dd9a733dc12a0f
[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     do_nodes $clients "f=${MOUNT}/fsa-\\\$(hostname); mcreate \\\$f; rm \\\$f"
2059
2060     local svc=${facet}_svc
2061     do_facet $facet $LCTL --device %${!svc} notransno
2062     do_facet $facet $LCTL --device %${!svc} readonly
2063     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
2064     $LCTL mark "local REPLAY BARRIER on ${!svc}"
2065 }
2066
2067 replay_barrier_nodf() {
2068     local facet=$1    echo running=${running}
2069     do_facet $facet "sync; sync; sync"
2070     local svc=${facet}_svc
2071     echo Replay barrier on ${!svc}
2072     do_facet $facet $LCTL --device %${!svc} notransno
2073     do_facet $facet $LCTL --device %${!svc} readonly
2074     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
2075     $LCTL mark "local REPLAY BARRIER on ${!svc}"
2076 }
2077
2078 replay_barrier_nosync() {
2079     local facet=$1    echo running=${running}
2080     local svc=${facet}_svc
2081     echo Replay barrier on ${!svc}
2082     do_facet $facet $LCTL --device %${!svc} notransno
2083     do_facet $facet $LCTL --device %${!svc} readonly
2084     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
2085     $LCTL mark "local REPLAY BARRIER on ${!svc}"
2086 }
2087
2088 mds_evict_client() {
2089     UUID=`lctl get_param -n mdc.${mds1_svc}-mdc-*.uuid`
2090     do_facet mds1 "lctl set_param -n mdt.${mds1_svc}.evict_client $UUID"
2091 }
2092
2093 ost_evict_client() {
2094     UUID=`lctl get_param -n devices| grep ${ost1_svc}-osc- | egrep -v 'MDT' | awk '{print $5}'`
2095     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
2096 }
2097
2098 fail() {
2099     facet_failover $* || error "failover: $?"
2100     clients_up || error "post-failover df: $?"
2101 }
2102
2103 fail_nodf() {
2104         local facet=$1
2105         facet_failover $facet
2106 }
2107
2108 fail_abort() {
2109         local facet=$1
2110         stop $facet
2111         refresh_disk ${facet}
2112         change_active $facet
2113         wait_for_facet $facet
2114         mount_facet $facet -o abort_recovery
2115         clients_up || echo "first df failed: $?"
2116         clients_up || error "post-failover df: $?"
2117 }
2118
2119 do_lmc() {
2120     echo There is no lmc.  This is mountconf, baby.
2121     exit 1
2122 }
2123
2124 host_nids_address() {
2125     local nodes=$1
2126     local kind=$2
2127
2128     if [ -n "$kind" ]; then
2129         nids=$(do_nodes $nodes "$LCTL list_nids | grep $kind | cut -f 1 -d '@'")
2130     else
2131         nids=$(do_nodes $nodes "$LCTL list_nids all | cut -f 1 -d '@'")
2132     fi
2133     echo $nids
2134 }
2135
2136 h2name_or_ip() {
2137     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
2138         echo $1"@$2"
2139     fi
2140 }
2141
2142 h2ptl() {
2143    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
2144        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
2145        if [ -z "$ID" ]; then
2146            echo "Could not get a ptl id for $1..."
2147            exit 1
2148        fi
2149        echo $ID"@ptl"
2150    fi
2151 }
2152 declare -fx h2ptl
2153
2154 h2tcp() {
2155     h2name_or_ip "$1" "tcp"
2156 }
2157 declare -fx h2tcp
2158
2159 h2elan() {
2160     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
2161         if type __h2elan >/dev/null 2>&1; then
2162             ID=$(__h2elan $1)
2163         else
2164             ID=`echo $1 | sed 's/[^0-9]*//g'`
2165         fi
2166         echo $ID"@elan"
2167     fi
2168 }
2169 declare -fx h2elan
2170
2171 h2o2ib() {
2172     h2name_or_ip "$1" "o2ib"
2173 }
2174 declare -fx h2o2ib
2175
2176 # This enables variables in cfg/"setup".sh files to support the pdsh HOSTLIST
2177 # expressions format. As a bonus we can then just pass in those variables
2178 # to pdsh. What this function does is take a HOSTLIST type string and
2179 # expand it into a space deliminated list for us.
2180 hostlist_expand() {
2181     local hostlist=$1
2182     local offset=$2
2183     local myList
2184     local item
2185     local list
2186
2187     [ -z "$hostlist" ] && return
2188
2189     # Translate the case of [..],..,[..] to [..] .. [..]
2190     list="${hostlist/],/] }"
2191     front=${list%%[*}
2192     [[ "$front" == *,* ]] && {
2193         new="${list%,*} "
2194         old="${list%,*},"
2195         list=${list/${old}/${new}}
2196     }
2197
2198     for item in $list; do
2199         # Test if we have any []'s at all
2200         if [ "$item" != "${item/\[/}" ]; then {
2201             # Expand the [*] into list
2202             name=${item%%[*}
2203             back=${item#*]}
2204
2205             if [ "$name" != "$item" ]; then
2206                 group=${item#$name[*}
2207                 group=${group%%]*}
2208
2209                 for range in ${group//,/ }; do
2210                     begin=${range%-*}
2211                     end=${range#*-}
2212
2213                     # Number of leading zeros
2214                     padlen=${#begin}
2215                     padlen2=${#end}
2216                     end=$(echo $end | sed 's/0*//')
2217                     [[ -z "$end" ]] && end=0
2218                     [[ $padlen2 -gt $padlen ]] && {
2219                         [[ $padlen2 -eq ${#end} ]] && padlen2=0
2220                         padlen=$padlen2
2221                     }
2222                     begin=$(echo $begin | sed 's/0*//')
2223                     [ -z $begin ] && begin=0
2224
2225                     for num in $(seq -f "%0${padlen}g" $begin $end); do
2226                         value="${name#*,}${num}${back}"
2227                         [ "$value" != "${value/\[/}" ] && {
2228                             value=$(hostlist_expand "$value")
2229                         }
2230                         myList="$myList $value"
2231                     done
2232                 done
2233             fi
2234         } else {
2235             myList="$myList $item"
2236         } fi
2237     done
2238     myList=${myList//,/ }
2239     myList=${myList:1} # Remove first character which is a space
2240
2241     # Filter any duplicates without sorting
2242     list="$myList "
2243     myList="${list%% *}"
2244
2245     while [[ "$list" != ${myList##* } ]]; do
2246         list=${list//${list%% *} /}
2247         myList="$myList ${list%% *}"
2248     done
2249     myList="${myList%* }";
2250
2251     # We can select an object at a offset in the list
2252     [ $# -eq 2 ] && {
2253         cnt=0
2254         for item in $myList; do
2255             let cnt=cnt+1
2256             [ $cnt -eq $offset ] && {
2257                 myList=$item
2258             }
2259         done
2260         [ $(get_node_count $myList) -ne 1 ] && myList=""
2261     }
2262     echo $myList
2263 }
2264
2265 facet_host() {
2266     local facet=$1
2267
2268     [ "$facet" == client ] && echo -n $HOSTNAME && return
2269     varname=${facet}_HOST
2270     if [ -z "${!varname}" ]; then
2271         if [ "${facet:0:3}" == "ost" ]; then
2272             eval ${facet}_HOST=${ost_HOST}
2273         fi
2274     fi
2275     echo -n ${!varname}
2276 }
2277
2278 facet_failover_host() {
2279         local facet=$1
2280         local var
2281
2282         var=${facet}failover_HOST
2283         if [ -n "${!var}" ]; then
2284                 echo ${!var}
2285                 return
2286         fi
2287
2288         if [[ $facet == ost* ]]; then
2289                 var=ostfailover_HOST
2290                 if [ -n "${!var}" ]; then
2291                         echo ${!var}
2292                         return
2293                 fi
2294         fi
2295 }
2296
2297 facet_active() {
2298     local facet=$1
2299     local activevar=${facet}active
2300
2301     if [ -f $TMP/${facet}active ] ; then
2302         source $TMP/${facet}active
2303     fi
2304
2305     active=${!activevar}
2306     if [ -z "$active" ] ; then
2307         echo -n ${facet}
2308     else
2309         echo -n ${active}
2310     fi
2311 }
2312
2313 facet_active_host() {
2314     local facet=$1
2315     local active=`facet_active $facet`
2316     if [ "$facet" == client ]; then
2317         echo $HOSTNAME
2318     else
2319         echo `facet_host $active`
2320     fi
2321 }
2322
2323 change_active() {
2324     local facetlist=$1
2325     local facet
2326
2327     facetlist=$(exclude_items_from_list $facetlist mgs)
2328
2329     for facet in ${facetlist//,/ }; do
2330     local failover=${facet}failover
2331     local host=`facet_host $failover`
2332     [ -z "$host" ] && return
2333
2334     local curactive=`facet_active $facet`
2335     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
2336         eval export ${facet}active=$facet
2337     else
2338         eval export ${facet}active=$failover
2339     fi
2340     # save the active host for this facet
2341     local activevar=${facet}active
2342     echo "$activevar=${!activevar}" > $TMP/$activevar
2343     [[ $facet = mds1 ]] && combined_mgs_mds && \
2344         echo "mgsactive=${!activevar}" > $TMP/mgsactive
2345     local TO=`facet_active_host $facet`
2346     echo "Failover $facet to $TO"
2347     done
2348 }
2349
2350 do_node() {
2351     local verbose=false
2352     # do not stripe off hostname if verbose, bug 19215
2353     if [ x$1 = x--verbose ]; then
2354         shift
2355         verbose=true
2356     fi
2357
2358     local HOST=$1
2359     shift
2360     local myPDSH=$PDSH
2361     if [ "$HOST" = "$HOSTNAME" ]; then
2362         myPDSH="no_dsh"
2363     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
2364         echo "cannot run remote command on $HOST with $myPDSH"
2365         return 128
2366     fi
2367     if $VERBOSE; then
2368         echo "CMD: $HOST $@" >&2
2369         $myPDSH $HOST "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
2370     fi
2371
2372     if [ "$myPDSH" = "rsh" ]; then
2373 # we need this because rsh does not return exit code of an executed command
2374         local command_status="$TMP/cs"
2375         rsh $HOST ":> $command_status"
2376         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
2377                     cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
2378                     echo command failed >$command_status"
2379         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
2380         return 0
2381     fi
2382
2383     if $verbose ; then
2384         # print HOSTNAME for myPDSH="no_dsh"
2385         if [[ $myPDSH = no_dsh ]]; then
2386             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
2387         else
2388             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
2389         fi
2390     else
2391         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
2392     fi
2393     return ${PIPESTATUS[0]}
2394 }
2395
2396 do_nodev() {
2397     do_node --verbose "$@"
2398 }
2399
2400 single_local_node () {
2401    [ "$1" = "$HOSTNAME" ]
2402 }
2403
2404 # Outputs environment variable assignments that should be passed to remote nodes
2405 get_env_vars() {
2406         local var
2407         local value
2408         local facets=$(get_facets)
2409         local facet
2410
2411         for var in ${!MODOPTS_*}; do
2412                 value=${!var}
2413                 echo -n " ${var}=\"$value\""
2414         done
2415
2416         echo -n " USE_OFD=$USE_OFD"
2417
2418         for facet in ${facets//,/ }; do
2419                 var=${facet}_FSTYPE
2420                 if [ -n "${!var}" ]; then
2421                         echo -n " $var=${!var}"
2422                 fi
2423         done
2424
2425         for var in MGSFSTYPE MDSFSTYPE OSTFSTYPE; do
2426                 if [ -n "${!var}" ]; then
2427                         echo -n " $var=${!var}"
2428                 fi
2429         done
2430
2431         if [ -n "$FSTYPE" ]; then
2432                 echo -n " FSTYPE=$FSTYPE"
2433         fi
2434 }
2435
2436 do_nodes() {
2437     local verbose=false
2438     # do not stripe off hostname if verbose, bug 19215
2439     if [ x$1 = x--verbose ]; then
2440         shift
2441         verbose=true
2442     fi
2443
2444     local rnodes=$1
2445     shift
2446
2447     if single_local_node $rnodes; then
2448         if $verbose; then
2449            do_nodev $rnodes "$@"
2450         else
2451            do_node $rnodes "$@"
2452         fi
2453         return $?
2454     fi
2455
2456     # This is part from do_node
2457     local myPDSH=$PDSH
2458
2459     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
2460         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
2461
2462     export FANOUT=$(get_node_count "${rnodes//,/ }")
2463     if $VERBOSE; then
2464         echo "CMD: $rnodes $@" >&2
2465         $myPDSH $rnodes "$LCTL mark \"$@\"" > /dev/null 2>&1 || :
2466     fi
2467
2468     # do not replace anything from pdsh output if -N is used
2469     # -N     Disable hostname: prefix on lines of output.
2470     if $verbose || [[ $myPDSH = *-N* ]]; then
2471         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")"
2472     else
2473         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")" | sed -re "s/^[^:]*: //g"
2474     fi
2475     return ${PIPESTATUS[0]}
2476 }
2477
2478 do_facet() {
2479     local facet=$1
2480     shift
2481     local HOST=`facet_active_host $facet`
2482     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
2483     do_node $HOST "$@"
2484 }
2485
2486 # Function: do_facet_random_file $FACET $FILE $SIZE
2487 # Creates FILE with random content on the given FACET of given SIZE
2488
2489 do_facet_random_file() {
2490         local facet="$1"
2491         local fpath="$2"
2492         local fsize="$3"
2493         local cmd="dd if=/dev/urandom of='$fpath' bs=$fsize count=1"
2494         do_facet $facet "$cmd 2>/dev/null"
2495 }
2496
2497 do_facet_create_file() {
2498         local facet="$1"
2499         local fpath="$2"
2500         local fsize="$3"
2501         local cmd="dd if=/dev/zero of='$fpath' bs=$fsize count=1"
2502         do_facet $facet "$cmd 2>/dev/null"
2503 }
2504
2505 do_nodesv() {
2506     do_nodes --verbose "$@"
2507 }
2508
2509 add() {
2510     local facet=$1
2511     shift
2512     # make sure its not already running
2513     stop ${facet} -f
2514     rm -f $TMP/${facet}active
2515     [[ $facet = mds1 ]] && combined_mgs_mds && rm -f $TMP/mgsactive
2516     do_facet ${facet} $MKFS $*
2517 }
2518
2519 ostdevname() {
2520     num=$1
2521     DEVNAME=OSTDEV$num
2522
2523         local fstype=$(facet_fstype ost$num)
2524
2525         case $fstype in
2526                 ldiskfs )
2527                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
2528                         eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
2529                 zfs )
2530                         #dataset name is independent of vdev device names
2531                         eval DEVPTR=${FSNAME}-ost${num}/ost${num};;
2532                 * )
2533                         error "unknown fstype!";;
2534         esac
2535
2536     echo -n $DEVPTR
2537 }
2538
2539 ostvdevname() {
2540         num=$1
2541         DEVNAME=OSTDEV$num
2542
2543         local fstype=$(facet_fstype ost$num)
2544
2545         case $fstype in
2546                 ldiskfs )
2547                         # vdevs are not supported by ldiskfs
2548                         eval VDEVPTR="";;
2549                 zfs )
2550                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
2551                         eval VDEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
2552                 * )
2553                         error "unknown fstype!";;
2554         esac
2555
2556         echo -n $VDEVPTR
2557 }
2558
2559 mdsdevname() {
2560     num=$1
2561     DEVNAME=MDSDEV$num
2562
2563         local fstype=$(facet_fstype mds$num)
2564
2565         case $fstype in
2566                 ldiskfs )
2567                         #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
2568                         eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
2569                 zfs )
2570                         #dataset name is independent of vdev device names
2571                         eval DEVPTR=${FSNAME}-mdt${num}/mdt${num};;
2572                 * )
2573                         error "unknown fstype!";;
2574         esac
2575
2576         echo -n $DEVPTR
2577 }
2578
2579 mdsvdevname() {
2580         num=$1
2581         DEVNAME=MDSDEV$num
2582
2583         local fstype=$(facet_fstype mds$num)
2584
2585         case $fstype in
2586                 ldiskfs )
2587                         # vdevs are not supported by ldiskfs
2588                         eval VDEVPTR="";;
2589                 zfs )
2590                         #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
2591                         eval VDEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
2592                 * )
2593                         error "unknown fstype!";;
2594         esac
2595
2596         echo -n $VDEVPTR
2597 }
2598
2599 mgsdevname() {
2600         DEVNAME=MGSDEV
2601
2602         local fstype=$(facet_fstype mds$num)
2603
2604         case $fstype in
2605                 ldiskfs )
2606                         #if $MGSDEV isn't defined, default is $MDSDEV1
2607                         eval DEVPTR=${!DEVNAME:=${MDSDEV1}};;
2608                 zfs )
2609                         #dataset name is independent of vdev device names
2610                         eval DEVPTR=${FSNAME}-mgs/mgs;;
2611                 * )
2612                         error "unknown fstype!";;
2613         esac
2614
2615     echo -n $DEVPTR
2616 }
2617
2618 mgsvdevname() {
2619         DEVNAME=MGSDEV
2620
2621         local fstype=$(facet_fstype mds$num)
2622
2623         case $fstype in
2624                 ldiskfs )
2625                         # vdevs are not supported by ldiskfs
2626                         eval VDEVPTR="";;
2627                 zfs )
2628                         #if $MGSDEV isn't defined, default is $MGSDEV1
2629                         eval VDEVPTR=${!DEVNAME:=${MDSDEV1}};;
2630                 * )
2631                         error "unknown fstype!";;
2632         esac
2633
2634         echo -n $VDEVPTR
2635 }
2636
2637 facet_mntpt () {
2638     local facet=$1
2639     [[ $facet = mgs ]] && combined_mgs_mds && facet="mds1"
2640
2641     local var=${facet}_MOUNT
2642     eval mntpt=${!var:-${MOUNT%/*}/$facet}
2643
2644     echo -n $mntpt
2645 }
2646
2647 ########
2648 ## MountConf setup
2649
2650 stopall() {
2651     # make sure we are using the primary server, so test-framework will
2652     # be able to clean up properly.
2653     activemds=`facet_active mds1`
2654     if [ $activemds != "mds1" ]; then
2655         fail mds1
2656     fi
2657
2658     local clients=$CLIENTS
2659     [ -z $clients ] && clients=$(hostname)
2660
2661     zconf_umount_clients $clients $MOUNT "$*" || true
2662     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
2663
2664     [ "$CLIENTONLY" ] && return
2665     # The add fn does rm ${facet}active file, this would be enough
2666     # if we use do_facet <facet> only after the facet added, but
2667     # currently we use do_facet mds in local.sh
2668     for num in `seq $MDSCOUNT`; do
2669         stop mds$num -f
2670         rm -f ${TMP}/mds${num}active
2671     done
2672     combined_mgs_mds && rm -f $TMP/mgsactive
2673
2674     for num in `seq $OSTCOUNT`; do
2675         stop ost$num -f
2676         rm -f $TMP/ost${num}active
2677     done
2678
2679     if ! combined_mgs_mds ; then
2680         stop mgs
2681     fi
2682
2683     return 0
2684 }
2685
2686 cleanup_echo_devs () {
2687     local devs=$($LCTL dl | grep echo | awk '{print $4}')
2688
2689     for dev in $devs; do
2690         $LCTL --device $dev cleanup
2691         $LCTL --device $dev detach
2692     done
2693 }
2694
2695 cleanupall() {
2696     nfs_client_mode && return
2697
2698     stopall $*
2699     cleanup_echo_devs
2700
2701     unload_modules
2702     cleanup_gss
2703 }
2704
2705 combined_mgs_mds () {
2706     [[ $MDSDEV1 = $MGSDEV ]] && [[ $mds1_HOST = $mgs_HOST ]]
2707 }
2708
2709 lower() {
2710         echo -n "$1" | tr '[:upper:]' '[:lower:]'
2711 }
2712
2713 upper() {
2714         echo -n "$1" | tr '[:lower:]' '[:upper:]'
2715 }
2716
2717 mkfs_opts() {
2718         local facet=$1
2719         local type=$(facet_type $facet)
2720         local index=$(($(facet_number $facet) - 1))
2721         local fstype=$(facet_fstype $facet)
2722         local opts
2723         local fs_mkfs_opts
2724         local var
2725
2726         if [ $type == MGS ] && combined_mgs_mds; then
2727                 return 1
2728         fi
2729
2730         if [ $type == MGS ] || ( [ $type == MDS ] && combined_mgs_mds ); then
2731                 opts="--mgs"
2732         else
2733                 opts="--mgsnode=$MGSNID"
2734         fi
2735
2736         if [ $type != MGS ]; then
2737                 opts+=" --fsname=$FSNAME --$(lower ${type/MDS/MDT}) --index=$index"
2738         fi
2739
2740         var=${facet}failover_HOST
2741         if [ -n "${!var}" ] && [ ${!var} != $(facet_host $facet) ]; then
2742                 opts+=" --failnode=$(h2$NETTYPE ${!var})"
2743         fi
2744
2745         opts+=${TIMEOUT:+" --param=sys.timeout=$TIMEOUT"}
2746         opts+=${LDLM_TIMEOUT:+" --param=sys.ldlm_timeout=$LDLM_TIMEOUT"}
2747
2748         if [ $type == MDS ]; then
2749                 opts+=${SECLEVEL:+" --param=mdt.sec_level"}
2750                 opts+=${MDSCAPA:+" --param-mdt.capa=$MDSCAPA"}
2751                 opts+=${STRIPE_BYTES:+" --param=lov.stripesize=$STRIPE_BYTES"}
2752                 opts+=${STRIPES_PER_OBJ:+" --param=lov.stripecount=$STRIPES_PER_OBJ"}
2753                 opts+=${L_GETIDENTITY:+" --param=mdt.identity_upcall=$L_GETIDENTITY"}
2754
2755                 if [ $fstype == ldiskfs ]; then
2756                         opts+=${IAMDIR:+" --iam-dir"}
2757
2758                         fs_mkfs_opts+=${MDSJOURNALSIZE:+" -J size=$MDSJOURNALSIZE"}
2759                         fs_mkfs_opts+=${MDSISIZE:+" -i $MDSISIZE"}
2760                 fi
2761         fi
2762
2763         if [ $type == OST ]; then
2764                 opts+=${SECLEVEL:+" --param=ost.sec_level"}
2765                 opts+=${OSSCAPA:+" --param=ost.capa=$OSSCAPA"}
2766
2767                 if [ $fstype == ldiskfs ]; then
2768                         fs_mkfs_opts+=${OSTJOURNALSIZE:+" -J size=$OSTJOURNALSIZE"}
2769                 fi
2770         fi
2771
2772         opts+=" --backfstype=$fstype"
2773
2774         var=${type}SIZE
2775         if [ -n "${!var}" ]; then
2776                 opts+=" --device-size=${!var}"
2777         fi
2778
2779         var=$(upper $fstype)_MKFS_OPTS
2780         fs_mkfs_opts+=${!var:+" ${!var}"}
2781
2782         var=${type}_FS_MKFS_OPTS
2783         fs_mkfs_opts+=${!var:+" ${!var}"}
2784
2785         if [ -n "${fs_mkfs_opts## }" ]; then
2786                 opts+=" --mkfsoptions=\\\"${fs_mkfs_opts## }\\\""
2787         fi
2788
2789         var=${type}OPT
2790         opts+=${!var:+" ${!var}"}
2791
2792         echo -n "$opts"
2793 }
2794
2795 formatall() {
2796         local quiet
2797
2798         if ! $VERBOSE; then
2799                 quiet=yes
2800         fi
2801
2802         stopall
2803         # We need ldiskfs here, may as well load them all
2804         load_modules
2805         [ "$CLIENTONLY" ] && return
2806         echo Formatting mgs, mds, osts
2807         if ! combined_mgs_mds ; then
2808                 echo "Format mgs: $(mgsdevname)"
2809                 add mgs $(mkfs_opts mgs) --reformat $(mgsdevname) \
2810                         $(mgsvdevname) ${quiet:+>/dev/null} || exit 10
2811                 fi
2812
2813                 for num in `seq $MDSCOUNT`; do
2814                         echo "Format mds$num: $(mdsdevname $num)"
2815                         add mds$num $(mkfs_opts mds$num) --reformat \
2816                         $(mdsdevname $num) $(mdsvdevname $num) \
2817                         ${quiet:+>/dev/null} || exit 10
2818                 done
2819
2820                 for num in `seq $OSTCOUNT`; do
2821                         echo "Format ost$num: $(ostdevname $num)"
2822                         add ost$num $(mkfs_opts ost$num) --reformat \
2823                         $(ostdevname $num) $(ostvdevname ${num}) \
2824                         ${quiet:+>/dev/null} || exit 10
2825                 done
2826 }
2827
2828 mount_client() {
2829     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
2830 }
2831
2832 umount_client() {
2833     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
2834 }
2835
2836 # return value:
2837 # 0: success, the old identity set already.
2838 # 1: success, the old identity does not set.
2839 # 2: fail.
2840 switch_identity() {
2841     local num=$1
2842     local switch=$2
2843     local j=`expr $num - 1`
2844     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
2845
2846     if [ -z "$MDT" ]; then
2847         return 2
2848     fi
2849
2850     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
2851
2852     if $switch; then
2853         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
2854     else
2855         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
2856     fi
2857
2858     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush=-1"
2859
2860     if [ $old = "NONE" ]; then
2861         return 1
2862     else
2863         return 0
2864     fi
2865 }
2866
2867 remount_client()
2868 {
2869         zconf_umount `hostname` $1 || error "umount failed"
2870         zconf_mount `hostname` $1 || error "mount failed"
2871 }
2872
2873 writeconf_facet () {
2874     local facet=$1
2875     local dev=$2
2876
2877     do_facet $facet "$TUNEFS --writeconf $dev"
2878 }
2879
2880 writeconf_all () {
2881     for num in `seq $MDSCOUNT`; do
2882         DEVNAME=$(mdsdevname $num)
2883         writeconf_facet mds$num $DEVNAME
2884     done
2885
2886     for num in `seq $OSTCOUNT`; do
2887         DEVNAME=$(ostdevname $num)
2888         writeconf_facet ost$num $DEVNAME
2889     done
2890 }
2891
2892 setupall() {
2893     nfs_client_mode && return
2894
2895     sanity_mount_check ||
2896         error "environments are insane!"
2897
2898     load_modules
2899
2900     if [ -z "$CLIENTONLY" ]; then
2901         echo Setup mgs, mdt, osts
2902         echo $WRITECONF | grep -q "writeconf" && \
2903             writeconf_all
2904         if ! combined_mgs_mds ; then
2905                         start mgs $(mgsdevname) $MGS_MOUNT_OPTS
2906         fi
2907
2908         for num in `seq $MDSCOUNT`; do
2909             DEVNAME=$(mdsdevname $num)
2910             start mds$num $DEVNAME $MDS_MOUNT_OPTS
2911
2912             # We started mds, now we should set failover variables properly.
2913             # Set mds${num}failover_HOST if it is not set (the default failnode).
2914             local varname=mds${num}failover_HOST
2915             if [ -z "${!varname}" ]; then
2916                 eval mds${num}failover_HOST=$(facet_host mds$num)
2917             fi
2918
2919             if [ $IDENTITY_UPCALL != "default" ]; then
2920                 switch_identity $num $IDENTITY_UPCALL
2921             fi
2922         done
2923         for num in `seq $OSTCOUNT`; do
2924             DEVNAME=$(ostdevname $num)
2925             start ost$num $DEVNAME $OST_MOUNT_OPTS
2926
2927             # We started ost$num, now we should set ost${num}failover variable properly.
2928             # Set ost${num}failover_HOST if it is not set (the default failnode).
2929             varname=ost${num}failover_HOST
2930             if [ -z "${!varname}" ]; then
2931                 eval ost${num}failover_HOST=$(facet_host ost${num})
2932             fi
2933
2934         done
2935     fi
2936
2937     init_gss
2938
2939     # wait a while to allow sptlrpc configuration be propogated to targets,
2940     # only needed when mounting new target devices.
2941     if $GSS; then
2942         sleep 10
2943     fi
2944
2945     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
2946     mount_client $MOUNT
2947     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
2948     clients_up
2949
2950     if [ "$MOUNT_2" ]; then
2951         mount_client $MOUNT2
2952         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
2953     fi
2954
2955     init_param_vars
2956
2957     # by remounting mdt before ost, initial connect from mdt to ost might
2958     # timeout because ost is not ready yet. wait some time to its fully
2959     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
2960     # by a context negotiation rpc with $TIMEOUT.
2961     # FIXME better by monitoring import status.
2962     if $GSS; then
2963         set_flavor_all $SEC
2964         sleep $((TIMEOUT + 5))
2965     else
2966         sleep 5
2967     fi
2968 }
2969
2970 mounted_lustre_filesystems() {
2971         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
2972 }
2973
2974 init_facet_vars () {
2975     [ "$CLIENTONLY" ] && return 0
2976     local facet=$1
2977     shift
2978     local device=$1
2979
2980     shift
2981
2982     eval export ${facet}_dev=${device}
2983     eval export ${facet}_opt=\"$@\"
2984
2985     local dev=${facet}_dev
2986         local label=$(devicelabel ${facet} ${!dev})
2987     [ -z "$label" ] && echo no label for ${!dev} && exit 1
2988
2989     eval export ${facet}_svc=${label}
2990
2991     local varname=${facet}failover_HOST
2992     if [ -z "${!varname}" ]; then
2993        eval $varname=$(facet_host $facet) 
2994     fi
2995
2996     # ${facet}failover_dev is set in cfg file
2997     varname=${facet}failover_dev
2998     if [ -n "${!varname}" ] ; then
2999         eval export ${facet}failover_dev=${!varname}
3000     else
3001         eval export ${facet}failover_dev=$device
3002     fi
3003
3004     # get mount point of already mounted device
3005     # is facet_dev is already mounted then use the real
3006     #  mount point of this facet; otherwise use $(facet_mntpt $facet)
3007     # i.e. ${facet}_MOUNT if specified by user or default
3008     local mntpt=$(do_facet ${facet} cat /proc/mounts | \
3009             awk '"'${!dev}'" == $1 && $3 == "lustre" { print $2 }')
3010     if [ -z $mntpt ]; then
3011         mntpt=$(facet_mntpt $facet)
3012     fi
3013     eval export ${facet}_MOUNT=$mntpt
3014 }
3015
3016 init_facets_vars () {
3017     local DEVNAME
3018
3019     if ! remote_mds_nodsh; then 
3020         for num in `seq $MDSCOUNT`; do
3021             DEVNAME=`mdsdevname $num`
3022             init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
3023         done
3024     fi
3025
3026         combined_mgs_mds || init_facet_vars mgs $(mgsdevname) $MGS_MOUNT_OPTS
3027
3028     remote_ost_nodsh && return
3029
3030     for num in `seq $OSTCOUNT`; do
3031         DEVNAME=`ostdevname $num`
3032         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
3033     done
3034 }
3035
3036 osc_ensure_active () {
3037     local facet=$1
3038     local timeout=$2
3039     local period=0
3040
3041     while [ $period -lt $timeout ]; do
3042         count=$(do_facet $facet "lctl dl | grep ' IN osc ' 2>/dev/null | wc -l")
3043         if [ $count -eq 0 ]; then
3044             break
3045         fi
3046
3047         echo "There are $count OST are inactive, wait $period seconds, and try again"
3048         sleep 3
3049         period=$((period+3))
3050     done
3051
3052     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
3053 }
3054
3055 set_conf_param_and_check() {
3056         local myfacet=$1
3057         local TEST=$2
3058         local PARAM=$3
3059         local ORIG=$(do_facet $myfacet "$TEST")
3060         if [ $# -gt 3 ]; then
3061                 local FINAL=$4
3062         else
3063                 local -i FINAL
3064                 FINAL=$((ORIG + 5))
3065         fi
3066         echo "Setting $PARAM from $ORIG to $FINAL"
3067         do_facet mgs "$LCTL conf_param $PARAM='$FINAL'" ||
3068                 error "conf_param $PARAM failed"
3069
3070         wait_update $(facet_host $myfacet) "$TEST" "$FINAL" ||
3071                 error "check $PARAM failed!"
3072 }
3073
3074 init_param_vars () {
3075         remote_mds_nodsh ||
3076                 TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
3077
3078         log "Using TIMEOUT=$TIMEOUT"
3079
3080         osc_ensure_active $SINGLEMDS $TIMEOUT
3081         osc_ensure_active client $TIMEOUT
3082
3083         local jobid_var
3084         if [ -z "$(lctl get_param -n mdc.*.connect_flags | grep jobstats)" ]; then
3085                 jobid_var="none"
3086         elif [ $JOBSTATS_AUTO -ne 0 ]; then
3087                 echo "enable jobstats, set job scheduler as $JOBID_VAR"
3088                 jobid_var=$JOBID_VAR
3089         else
3090                 jobid_var=`$LCTL get_param -n jobid_var`
3091                 if [ $jobid_var != "disable" ]; then
3092                         echo "disable jobstats as required"
3093                         jobid_var="disable"
3094                 else
3095                         jobid_var="none"
3096                 fi
3097         fi
3098
3099         if [ $jobid_var == $JOBID_VAR -o $jobid_var == "disable" ]; then
3100                 do_facet mgs $LCTL conf_param $FSNAME.sys.jobid_var=$jobid_var
3101                 wait_update $HOSTNAME "$LCTL get_param -n jobid_var" \
3102                         $jobid_var || return 1
3103         fi
3104
3105         if [ $QUOTA_AUTO -ne 0 ]; then
3106                 if [ "$ENABLE_QUOTA" ]; then
3107                         echo "enable quota as required"
3108                         setup_quota $MOUNT || return 2
3109                 else
3110                         echo "disable quota as required"
3111                         # $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
3112                 fi
3113         fi
3114         return 0
3115 }
3116
3117 nfs_client_mode () {
3118     if [ "$NFSCLIENT" ]; then
3119         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
3120         local clients=$CLIENTS
3121         [ -z $clients ] && clients=$(hostname)
3122
3123         # FIXME: remove hostname when 19215 fixed
3124         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
3125         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
3126         if [[ ${#nfsexport[@]} -eq 0 ]]; then
3127                 error_exit NFSCLIENT=$NFSCLIENT mode, but no NFS export found!
3128         fi
3129         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
3130         return
3131     fi
3132     return 1
3133 }
3134
3135 check_config_client () {
3136     local mntpt=$1
3137
3138     local mounted=$(mount | grep " $mntpt ")
3139     if [ "$CLIENTONLY" ]; then
3140         # bug 18021
3141         # CLIENTONLY should not depend on *_HOST settings
3142         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
3143         # in theory someone could create a new,
3144         # client-only config file that assumed lustre was already
3145         # configured and didn't set the MGSNID. If MGSNID is not set,
3146         # then we should use the mgs nid currently being used 
3147         # as the default value. bug 18021
3148         [[ x$MGSNID = x ]] &&
3149             MGSNID=${mgc//MGC/}
3150
3151         if [[ x$mgc != xMGC$MGSNID ]]; then
3152             if [ "$mgs_HOST" ]; then
3153                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
3154 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
3155 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
3156             fi
3157         fi
3158         return 0
3159     fi
3160
3161     local myMGS_host=$mgs_HOST   
3162     if [ "$NETTYPE" = "ptl" ]; then
3163         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
3164     fi
3165
3166     echo Checking config lustre mounted on $mntpt
3167     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
3168     mgshost=$(echo $mgshost | awk -F: '{print $1}')
3169
3170 #    if [ "$mgshost" != "$myMGS_host" ]; then
3171 #            log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
3172 #                   Please use correct config or set mds_HOST correctly!"
3173 #    fi
3174
3175 }
3176
3177 check_config_clients () {
3178     local clients=${CLIENTS:-$HOSTNAME}
3179     local mntpt=$1
3180
3181     nfs_client_mode && return
3182
3183     do_rpc_nodes $clients check_config_client $mntpt
3184
3185     sanity_mount_check ||
3186         error "environments are insane!"
3187 }
3188
3189 check_timeout () {
3190     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
3191     local cltimeout=$(lctl get_param -n timeout)
3192     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
3193         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
3194         return 1
3195     fi
3196 }
3197
3198 is_mounted () {
3199     local mntpt=$1
3200     [ -z $mntpt ] && return 1
3201     local mounted=$(mounted_lustre_filesystems)
3202
3203     echo $mounted' ' | grep -w -q $mntpt' '
3204 }
3205
3206 is_empty_dir() {
3207     [ $(find $1 -maxdepth 1 -print | wc -l) = 1 ] && return 0
3208     return 1
3209 }
3210
3211 # empty lustre filesystem may have empty directories lost+found and .lustre
3212 is_empty_fs() {
3213     [ $(find $1 -maxdepth 1 -name lost+found -o -name .lustre -prune -o \
3214        -print | wc -l) = 1 ] || return 1
3215     [ ! -d $1/lost+found ] || is_empty_dir $1/lost+found && return 0
3216     [ ! -d $1/.lustre ] || is_empty_dir $1/.lustre && return 0
3217     return 1
3218 }
3219
3220 check_and_setup_lustre() {
3221     nfs_client_mode && return
3222
3223     local MOUNTED=$(mounted_lustre_filesystems)
3224
3225     local do_check=true
3226     # 1.
3227     # both MOUNT and MOUNT2 are not mounted
3228     if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
3229         [ "$REFORMAT" ] && formatall
3230         # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
3231         setupall
3232         is_mounted $MOUNT || error "NAME=$NAME not mounted"
3233         export I_MOUNTED=yes
3234         do_check=false
3235     # 2.
3236     # MOUNT2 is mounted
3237     elif is_mounted $MOUNT2; then
3238             # 3.
3239             # MOUNT2 is mounted, while MOUNT_2 is not set
3240             if ! [ "$MOUNT_2" ]; then
3241                 cleanup_mount $MOUNT2
3242                 export I_UMOUNTED2=yes
3243
3244             # 4.
3245             # MOUNT2 is mounted, MOUNT_2 is set
3246             else
3247                 # FIXME: what to do if check_config failed?
3248                 # i.e. if:
3249                 # 1) remote client has mounted other Lustre fs ?
3250                 # 2) it has insane env ?
3251                 # let's try umount MOUNT2 on all clients and mount it again:
3252                 if ! check_config_clients $MOUNT2; then
3253                     cleanup_mount $MOUNT2
3254                     restore_mount $MOUNT2
3255                     export I_MOUNTED2=yes
3256                 fi
3257             fi 
3258
3259     # 5.
3260     # MOUNT is mounted MOUNT2 is not mounted
3261     elif [ "$MOUNT_2" ]; then
3262         restore_mount $MOUNT2
3263         export I_MOUNTED2=yes
3264     fi
3265
3266     if $do_check; then
3267         # FIXME: what to do if check_config failed?
3268         # i.e. if:
3269         # 1) remote client has mounted other Lustre fs?
3270         # 2) lustre is mounted on remote_clients atall ?
3271         check_config_clients $MOUNT
3272         init_facets_vars
3273         init_param_vars
3274
3275         set_default_debug_nodes $(comma_list $(nodes_list))
3276     fi
3277
3278         init_gss
3279         if $GSS; then
3280                 set_flavor_all $SEC
3281         fi
3282
3283         if [ "$ONLY" == "setup" ]; then
3284                 exit 0
3285         fi
3286 }
3287
3288 restore_mount () {
3289    local clients=${CLIENTS:-$HOSTNAME}
3290    local mntpt=$1
3291
3292    zconf_mount_clients $clients $mntpt
3293 }
3294
3295 cleanup_mount () {
3296     local clients=${CLIENTS:-$HOSTNAME}
3297     local mntpt=$1
3298
3299     zconf_umount_clients $clients $mntpt    
3300 }
3301
3302 cleanup_and_setup_lustre() {
3303     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
3304         lctl set_param debug=0 || true
3305         cleanupall
3306         if [ "$ONLY" == "cleanup" ]; then
3307             exit 0
3308         fi
3309     fi
3310     check_and_setup_lustre
3311 }
3312
3313 # Get all of the server target devices from a given server node and type.
3314 get_mnt_devs() {
3315         local node=$1
3316         local type=$2
3317         local devs
3318         local dev
3319
3320         if [ "$type" == ost ]; then
3321                 devs=$(get_obdfilter_param $node "" mntdev)
3322         else
3323                 devs=$(do_node $node \
3324                        "lctl get_param -n osd-*.$FSNAME-M*.mntdev")
3325         fi
3326         for dev in $devs; do
3327                 case $dev in
3328                 *loop*) do_node $node "losetup $dev" | \
3329                                 sed -e "s/.*(//" -e "s/).*//" ;;
3330                 *) echo $dev ;;
3331                 esac
3332         done
3333 }
3334
3335 # Get all of the server target devices.
3336 get_svr_devs() {
3337     local i
3338
3339     # MDT device
3340     MDTDEV=$(get_mnt_devs $(mdts_nodes) mdt)
3341
3342     # OST devices
3343     i=0
3344     for node in $(osts_nodes); do
3345         OSTDEVS[i]=$(get_mnt_devs $node ost)
3346         i=$((i + 1))
3347     done
3348 }
3349
3350 # Run e2fsck on MDT or OST device.
3351 run_e2fsck() {
3352     local node=$1
3353     local target_dev=$2
3354     local extra_opts=$3
3355
3356     df > /dev/null      # update statfs data on disk
3357     local cmd="$E2FSCK -d -v -t -t -f -n $extra_opts $target_dev"
3358     echo $cmd
3359     local rc=0
3360     do_node $node $cmd || rc=$?
3361     [ $rc -le $FSCK_MAX_ERR ] || \
3362         error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
3363     return 0
3364 }
3365
3366 # verify a directory is shared among nodes.
3367 check_shared_dir() {
3368     local dir=$1
3369
3370     [ -z "$dir" ] && return 1
3371     do_rpc_nodes $(comma_list $(nodes_list)) check_logdir $dir
3372     check_write_access $dir || return 1
3373     return 0
3374 }
3375
3376 # Run e2fsck on MDT and OST(s) to generate databases used for lfsck.
3377 generate_db() {
3378     local i
3379     local ostidx
3380     local dev
3381
3382         [[ $(lustre_version_code $SINGLEMDS) -ne $(version_code 2.2.0) ]] ||
3383                 { skip "Lustre 2.2.0 lacks the patch for LU-1255"; exit 0; }
3384
3385     check_shared_dir $SHARED_DIRECTORY ||
3386         error "$SHARED_DIRECTORY isn't a shared directory"
3387
3388     export MDSDB=$SHARED_DIRECTORY/mdsdb
3389     export OSTDB=$SHARED_DIRECTORY/ostdb
3390
3391     [ $MDSCOUNT -eq 1 ] || error "CMD is not supported"
3392
3393     run_e2fsck $(mdts_nodes) $MDTDEV "--mdsdb $MDSDB"
3394
3395     i=0
3396     ostidx=0
3397     OSTDB_LIST=""
3398     for node in $(osts_nodes); do
3399         for dev in ${OSTDEVS[i]}; do
3400             run_e2fsck $node $dev "--mdsdb $MDSDB --ostdb $OSTDB-$ostidx"
3401             OSTDB_LIST="$OSTDB_LIST $OSTDB-$ostidx"
3402             ostidx=$((ostidx + 1))
3403         done
3404         i=$((i + 1))
3405     done
3406 }
3407
3408 run_lfsck() {
3409     local cmd="$LFSCK_BIN -c -l --mdsdb $MDSDB --ostdb $OSTDB_LIST $MOUNT"
3410     echo $cmd
3411     local rc=0
3412     eval $cmd || rc=$?
3413     [ $rc -le $FSCK_MAX_ERR ] || \
3414         error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
3415     echo "lfsck finished with rc=$rc"
3416
3417     rm -rvf $MDSDB* $OSTDB* || true
3418     return 0
3419 }
3420
3421 check_and_cleanup_lustre() {
3422     if [ "$LFSCK_ALWAYS" = "yes" -a "$TESTSUITE" != "lfsck" ]; then
3423         get_svr_devs
3424         generate_db
3425         run_lfsck
3426     fi
3427
3428         if is_mounted $MOUNT; then
3429                 [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]* ||
3430                         error "remove sub-test dirs failed"
3431                 [ "$ENABLE_QUOTA" ] && restore_quota || true
3432         fi
3433
3434     if [ "$I_UMOUNTED2" = "yes" ]; then
3435         restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
3436     fi
3437
3438     if [ "$I_MOUNTED2" = "yes" ]; then
3439         cleanup_mount $MOUNT2
3440     fi
3441
3442     if [ "$I_MOUNTED" = "yes" ]; then
3443         cleanupall -f || error "cleanup failed"
3444         unset I_MOUNTED
3445     fi
3446 }
3447
3448 #######
3449 # General functions
3450
3451 wait_for_function () {
3452     local quiet=""
3453
3454     # suppress fn both stderr and stdout
3455     if [ "$1" = "--quiet" ]; then
3456         shift
3457         quiet=" > /dev/null 2>&1"
3458
3459     fi
3460
3461     local fn=$1
3462     local max=${2:-900}
3463     local sleep=${3:-5}
3464
3465     local wait=0
3466
3467     while true; do
3468
3469         eval $fn $quiet && return 0
3470
3471         wait=$((wait + sleep))
3472         [ $wait -lt $max ] || return 1
3473         echo waiting $fn, $((max - wait)) secs left ...
3474         sleep $sleep
3475     done
3476 }
3477
3478 check_network() {
3479     local host=$1
3480     local max=$2
3481     local sleep=${3:-5}
3482
3483     echo `date +"%H:%M:%S (%s)"` waiting for $host network $max secs ...
3484     if ! wait_for_function --quiet "ping -c 1 -w 3 $host" $max $sleep ; then
3485         echo "Network not available!"
3486         exit 1
3487     fi
3488
3489     echo `date +"%H:%M:%S (%s)"` network interface is UP
3490 }
3491
3492 no_dsh() {
3493     shift
3494     eval $@
3495 }
3496
3497 comma_list() {
3498     # the sed converts spaces to commas, but leaves the last space
3499     # alone, so the line doesn't end with a comma.
3500     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
3501 }
3502
3503 list_member () {
3504     local list=$1
3505     local item=$2
3506     echo $list | grep -qw $item
3507 }
3508
3509 # list, excluded are the comma separated lists
3510 exclude_items_from_list () {
3511     local list=$1
3512     local excluded=$2
3513     local item
3514
3515     list=${list//,/ }
3516     for item in ${excluded//,/ }; do
3517         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
3518     done
3519     echo $(comma_list $list)
3520 }
3521
3522 # list, expand  are the comma separated lists
3523 expand_list () {
3524     local list=${1//,/ }
3525     local expand=${2//,/ }
3526     local expanded=
3527
3528     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
3529     echo $(comma_list $expanded)
3530 }
3531
3532 testslist_filter () {
3533     local script=$LUSTRE/tests/${TESTSUITE}.sh
3534
3535     [ -f $script ] || return 0
3536
3537     local start_at=$START_AT
3538     local stop_at=$STOP_AT
3539
3540     local var=${TESTSUITE//-/_}_START_AT
3541     [ x"${!var}" != x ] && start_at=${!var}
3542     var=${TESTSUITE//-/_}_STOP_AT
3543     [ x"${!var}" != x ] && stop_at=${!var}
3544
3545     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
3546         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
3547             /^'${start_at}'$/ {flag = 0}
3548             {if (flag == 1) print $0}
3549             /^'${stop_at}'$/ { flag = 1 }'
3550 }
3551
3552 absolute_path() {
3553     (cd `dirname $1`; echo $PWD/`basename $1`)
3554 }
3555
3556 get_facets () {
3557     local types=${1:-"OST MDS MGS"}
3558
3559     local list=""
3560
3561     for entry in $types; do
3562         local name=$(echo $entry | tr "[:upper:]" "[:lower:]")
3563         local type=$(echo $entry | tr "[:lower:]" "[:upper:]")
3564
3565         case $type in
3566                 MGS ) list="$list $name";;
3567             MDS|OST ) local count=${type}COUNT
3568                        for ((i=1; i<=${!count}; i++)) do
3569                           list="$list ${name}$i"
3570                       done;;
3571                   * ) error "Invalid facet type"
3572                  exit 1;;
3573         esac
3574     done
3575     echo $(comma_list $list)
3576 }
3577
3578 ##################################
3579 # Adaptive Timeouts funcs
3580
3581 at_is_enabled() {
3582     # only check mds, we assume at_max is the same on all nodes
3583     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
3584     if [ $at_max -eq 0 ]; then
3585         return 1
3586     else
3587         return 0
3588     fi
3589 }
3590
3591 at_get() {
3592     local facet=$1
3593     local at=$2
3594
3595     # suppose that all ost-s have the same $at value set
3596     [ $facet != "ost" ] || facet=ost1
3597
3598     do_facet $facet "lctl get_param -n $at"
3599 }
3600
3601 at_max_get() {
3602     at_get $1 at_max
3603 }
3604
3605 at_min_get() {
3606         at_get $1 at_min
3607 }
3608
3609 at_max_set() {
3610     local at_max=$1
3611     shift
3612
3613     local facet
3614     local hosts
3615     for facet in $@; do
3616         if [ $facet == "ost" ]; then
3617             facet=$(get_facets OST)
3618         elif [ $facet == "mds" ]; then
3619             facet=$(get_facets MDS)
3620         fi
3621         hosts=$(expand_list $hosts $(facets_hosts $facet))
3622     done
3623
3624     do_nodes $hosts lctl set_param at_max=$at_max
3625 }
3626
3627 ##################################
3628 # OBD_FAIL funcs
3629
3630 drop_request() {
3631 # OBD_FAIL_MDS_ALL_REQUEST_NET
3632     RC=0
3633     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
3634     do_facet client "$1" || RC=$?
3635     do_facet $SINGLEMDS lctl set_param fail_loc=0
3636     return $RC
3637 }
3638
3639 drop_reply() {
3640 # OBD_FAIL_MDS_ALL_REPLY_NET
3641     RC=0
3642     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
3643     do_facet client "$@" || RC=$?
3644     do_facet $SINGLEMDS lctl set_param fail_loc=0
3645     return $RC
3646 }
3647
3648 drop_reint_reply() {
3649 # OBD_FAIL_MDS_REINT_NET_REP
3650     RC=0
3651     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
3652     do_facet client "$@" || RC=$?
3653     do_facet $SINGLEMDS lctl set_param fail_loc=0
3654     return $RC
3655 }
3656
3657 pause_bulk() {
3658 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
3659     RC=0
3660     do_facet ost1 lctl set_param fail_loc=0x214
3661     do_facet client "$1" || RC=$?
3662     do_facet client "sync"
3663     do_facet ost1 lctl set_param fail_loc=0
3664     return $RC
3665 }
3666
3667 drop_ldlm_cancel() {
3668 #define OBD_FAIL_LDLM_CANCEL             0x304
3669         local RC=0
3670         local list=$(comma_list $(mdts_nodes) $(osts_nodes))
3671         do_nodes $list lctl set_param fail_loc=0x304
3672
3673         do_facet client "$@" || RC=$?
3674
3675         do_nodes $list lctl set_param fail_loc=0
3676         return $RC
3677 }
3678
3679 drop_bl_callback() {
3680 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
3681     RC=0
3682     do_facet client lctl set_param fail_loc=0x305
3683     do_facet client "$@" || RC=$?
3684     do_facet client lctl set_param fail_loc=0
3685     return $RC
3686 }
3687
3688 drop_ldlm_reply() {
3689 #define OBD_FAIL_LDLM_REPLY              0x30c
3690     RC=0
3691     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
3692     do_facet client "$@" || RC=$?
3693     do_facet $SINGLEMDS lctl set_param fail_loc=0
3694     return $RC
3695 }
3696
3697 clear_failloc() {
3698     facet=$1
3699     pause=$2
3700     sleep $pause
3701     echo "clearing fail_loc on $facet"
3702     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
3703 }
3704
3705 set_nodes_failloc () {
3706     do_nodes $(comma_list $1)  lctl set_param fail_loc=$2
3707 }
3708
3709 cancel_lru_locks() {
3710     $LCTL mark "cancel_lru_locks $1 start"
3711     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
3712         $LCTL set_param -n $d=clear
3713     done
3714     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
3715     $LCTL mark "cancel_lru_locks $1 stop"
3716 }
3717
3718 default_lru_size()
3719 {
3720         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
3721         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
3722         echo "$DEFAULT_LRU_SIZE"
3723 }
3724
3725 lru_resize_enable()
3726 {
3727     lctl set_param ldlm.namespaces.*$1*.lru_size=0
3728 }
3729
3730 lru_resize_disable()
3731 {
3732     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
3733 }
3734
3735 pgcache_empty() {
3736     local FILE
3737     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
3738         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
3739             echo there is still data in page cache $FILE ?
3740             lctl get_param -n $FILE
3741             return 1
3742         fi
3743     done
3744     return 0
3745 }
3746
3747 debugsave() {
3748     DEBUGSAVE="$(lctl get_param -n debug)"
3749 }
3750
3751 debugrestore() {
3752     [ -n "$DEBUGSAVE" ] && \
3753         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
3754     DEBUGSAVE=""
3755 }
3756
3757 debug_size_save() {
3758     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
3759 }
3760
3761 debug_size_restore() {
3762     [ -n "$DEBUG_SIZE_SAVED" ] && \
3763         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
3764     DEBUG_SIZE_SAVED=""
3765 }
3766
3767 start_full_debug_logging() {
3768     debugsave
3769     debug_size_save
3770
3771     local FULLDEBUG=-1
3772     local DEBUG_SIZE=150
3773
3774     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
3775     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
3776 }
3777
3778 stop_full_debug_logging() {
3779     debug_size_restore
3780     debugrestore
3781 }
3782
3783 # prints bash call stack
3784 log_trace_dump() {
3785         echo "  Trace dump:"
3786         for (( i=1; i < ${#BASH_LINENO[*]} ; i++ )) ; do
3787                 local s=${BASH_SOURCE[$i]}
3788                 local l=${BASH_LINENO[$i-1]}
3789                 local f=${FUNCNAME[$i]}
3790                 echo "  = $s:$l:$f()"
3791         done
3792 }
3793
3794 ##################################
3795 # Test interface
3796 ##################################
3797
3798 error_noexit() {
3799     local TYPE=${TYPE:-"FAIL"}
3800
3801     local dump=true
3802     # do not dump logs if $1=false
3803     if [ "x$1" = "xfalse" ]; then
3804         shift
3805         dump=false
3806     fi
3807
3808     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
3809     log_trace_dump
3810
3811     mkdir -p $LOGDIR
3812     # We need to dump the logs on all nodes
3813     if $dump; then
3814         gather_logs $(comma_list $(nodes_list))
3815     fi
3816
3817     debugrestore
3818     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
3819     echo "$@" > $LOGDIR/err
3820 }
3821
3822 exit_status () {
3823         local status=0
3824         local log=$TESTSUITELOG
3825
3826         [ -f "$log" ] && grep -q FAIL $log && status=1
3827         exit $status
3828 }
3829
3830 error() {
3831     error_noexit "$@"
3832     exit 1
3833 }
3834
3835 error_exit() {
3836     error "$@"
3837 }
3838
3839 # use only if we are ignoring failures for this test, bugno required.
3840 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
3841 # e.g. error_ignore 5494 "your message"
3842 error_ignore() {
3843     local TYPE="IGNORE (bz$1)"
3844     shift
3845     error_noexit "$@"
3846 }
3847
3848 error_and_remount() {
3849         error_noexit "$@"
3850         remount_client $MOUNT
3851         exit 1
3852 }
3853
3854 skip_env () {
3855     $FAIL_ON_SKIP_ENV && error false $@ || skip $@
3856 }
3857
3858 skip() {
3859         echo
3860         log " SKIP: $TESTSUITE $TESTNAME $@"
3861
3862         if [[ -n "$ALWAYS_SKIPPED" ]]; then
3863                 skip_logged $TESTNAME "$@"
3864         else
3865                 mkdir -p $LOGDIR
3866                 echo "$@" > $LOGDIR/skip
3867         fi
3868
3869         [[ -n "$TESTSUITELOG" ]] &&
3870                 echo "$TESTSUITE: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
3871 }
3872
3873 build_test_filter() {
3874     EXCEPT="$EXCEPT $(testslist_filter)"
3875
3876     [ "$ONLY" ] && log "only running test `echo $ONLY`"
3877     for O in $ONLY; do
3878         eval ONLY_${O}=true
3879     done
3880     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
3881         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
3882     [ "$EXCEPT_SLOW" ] && \
3883         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
3884     for E in $EXCEPT; do
3885         eval EXCEPT_${E}=true
3886     done
3887     for E in $ALWAYS_EXCEPT; do
3888         eval EXCEPT_ALWAYS_${E}=true
3889     done
3890     for E in $EXCEPT_SLOW; do
3891         eval EXCEPT_SLOW_${E}=true
3892     done
3893     for G in $GRANT_CHECK_LIST; do
3894         eval GCHECK_ONLY_${G}=true
3895         done
3896 }
3897
3898 basetest() {
3899     if [[ $1 = [a-z]* ]]; then
3900         echo $1
3901     else
3902         echo ${1%%[a-z]*}
3903     fi
3904 }
3905
3906 # print a newline if the last test was skipped
3907 export LAST_SKIPPED=
3908 export ALWAYS_SKIPPED=
3909 #
3910 # Main entry into test-framework. This is called with the name and
3911 # description of a test. The name is used to find the function to run
3912 # the test using "test_$name".
3913 #
3914 # This supports a variety of methods of specifying specific test to
3915 # run or not run.  These need to be documented...
3916 #
3917 run_test() {
3918     assert_DIR
3919
3920     export base=`basetest $1`
3921     if [ ! -z "$ONLY" ]; then
3922         testname=ONLY_$1
3923         if [ ${!testname}x != x ]; then
3924             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
3925             run_one_logged $1 "$2"
3926             return $?
3927         fi
3928         testname=ONLY_$base
3929         if [ ${!testname}x != x ]; then
3930             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
3931             run_one_logged $1 "$2"
3932             return $?
3933         fi
3934         LAST_SKIPPED="y"
3935         echo -n "."
3936         return 0
3937     fi
3938
3939         LAST_SKIPPED="y"
3940         ALWAYS_SKIPPED="y"
3941     testname=EXCEPT_$1
3942     if [ ${!testname}x != x ]; then
3943         TESTNAME=test_$1 skip "skipping excluded test $1"
3944         return 0
3945     fi
3946     testname=EXCEPT_$base
3947     if [ ${!testname}x != x ]; then
3948         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
3949         return 0
3950     fi
3951     testname=EXCEPT_ALWAYS_$1
3952     if [ ${!testname}x != x ]; then
3953         TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1"
3954         return 0
3955     fi
3956     testname=EXCEPT_ALWAYS_$base
3957     if [ ${!testname}x != x ]; then
3958         TESTNAME=test_$1 skip "skipping ALWAYS excluded test $1 (base $base)"
3959         return 0
3960     fi
3961     testname=EXCEPT_SLOW_$1
3962     if [ ${!testname}x != x ]; then
3963         TESTNAME=test_$1 skip "skipping SLOW test $1"
3964         return 0
3965     fi
3966     testname=EXCEPT_SLOW_$base
3967     if [ ${!testname}x != x ]; then
3968         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
3969         return 0
3970     fi
3971
3972     LAST_SKIPPED=
3973     ALWAYS_SKIPPED=
3974     run_one_logged $1 "$2"
3975
3976     return $?
3977 }
3978
3979 equals_msg() {
3980     banner "$*"
3981 }
3982
3983 log() {
3984     echo "$*"
3985     module_loaded lnet || load_modules
3986
3987     local MSG="$*"
3988     # Get rid of '
3989     MSG=${MSG//\'/\\\'}
3990     MSG=${MSG//\(/\\\(}
3991     MSG=${MSG//\)/\\\)}
3992     MSG=${MSG//\;/\\\;}
3993     MSG=${MSG//\|/\\\|}
3994     MSG=${MSG//\>/\\\>}
3995     MSG=${MSG//\</\\\<}
3996     MSG=${MSG//\//\\\/}
3997     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
3998 }
3999
4000 trace() {
4001         log "STARTING: $*"
4002         strace -o $TMP/$1.strace -ttt $*
4003         RC=$?
4004         log "FINISHED: $*: rc $RC"
4005         return 1
4006 }
4007
4008 complete () {
4009     equals_msg $1 test complete, duration $2 sec
4010     [ -f "$TESTSUITELOG" ] && egrep .FAIL $TESTSUITELOG || true
4011     echo duration $2 >>$TESTSUITELOG
4012 }
4013
4014 pass() {
4015         # Set TEST_STATUS here. It will be used for logging the result.
4016         TEST_STATUS="PASS"
4017
4018         if [[ -f $LOGDIR/err ]]; then
4019                 TEST_STATUS="FAIL"
4020         elif [[ -f $LOGDIR/skip ]]; then
4021                 TEST_STATUS="SKIP"
4022         fi
4023         echo "$TEST_STATUS $@" 2>&1 | tee -a $TESTSUITELOG
4024 }
4025
4026 check_mds() {
4027     local FFREE=$(do_node $SINGLEMDS \
4028         lctl get_param -n osd*.*MDT*.filesfree | calc_sum)
4029     local FTOTAL=$(do_node $SINGLEMDS \
4030         lctl get_param -n osd*.*MDT*.filestotal | calc_sum)
4031
4032     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
4033 }
4034
4035 reset_fail_loc () {
4036     echo -n "Resetting fail_loc on all nodes..."
4037     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
4038     echo done.
4039 }
4040
4041
4042 #
4043 # Log a message (on all nodes) padded with "=" before and after. 
4044 # Also appends a timestamp and prepends the testsuite name.
4045
4046
4047 EQUALS="===================================================================================================="
4048 banner() {
4049     msg="== ${TESTSUITE} $*"
4050     last=${msg: -1:1}
4051     [[ $last != "=" && $last != " " ]] && msg="$msg "
4052     msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
4053     # always include at least == after the message
4054     log "$msg== $(date +"%H:%M:%S (%s)")"
4055 }
4056
4057 #
4058 # Run a single test function and cleanup after it.  
4059 #
4060 # This function should be run in a subshell so the test func can
4061 # exit() without stopping the whole script.
4062 #
4063 run_one() {
4064     local testnum=$1
4065     local message=$2
4066     tfile=f.${TESTSUITE}.${testnum}
4067     export tdir=d0.${TESTSUITE}/d${base}
4068     export TESTNAME=test_$testnum
4069     local SAVE_UMASK=`umask`
4070     umask 0022
4071
4072     banner "test $testnum: $message"
4073     test_${testnum} || error "test_$testnum failed with $?"
4074     cd $SAVE_PWD
4075     reset_fail_loc
4076     check_grant ${testnum} || error "check_grant $testnum failed with $?"
4077     check_catastrophe || error "LBUG/LASSERT detected"
4078     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
4079     unset TESTNAME
4080     unset tdir
4081     umask $SAVE_UMASK
4082     return 0
4083 }
4084
4085 #
4086 # Wrapper around run_one to ensure:
4087 #  - test runs in subshell
4088 #  - output of test is saved to separate log file for error reporting
4089 #  - test result is saved to data file
4090 #
4091 run_one_logged() {
4092         local BEFORE=`date +%s`
4093         local TEST_ERROR
4094         local name=${TESTSUITE}.test_${1}.test_log.$(hostname -s).log
4095         local test_log=$LOGDIR/$name
4096         rm -rf $LOGDIR/err
4097         rm -rf $LOGDIR/skip
4098         local SAVE_UMASK=`umask`
4099         umask 0022
4100
4101         echo
4102         log_sub_test_begin test_${1}
4103         (run_one $1 "$2") 2>&1 | tee -i $test_log
4104         local RC=${PIPESTATUS[0]}
4105
4106         [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] && \
4107                 echo "test_$1 returned $RC" | tee $LOGDIR/err
4108
4109         duration=$((`date +%s` - $BEFORE))
4110         pass "$1" "(${duration}s)"
4111
4112         if [[ -f $LOGDIR/err ]]; then
4113                 TEST_ERROR=$(cat $LOGDIR/err)
4114         elif [[ -f $LOGDIR/skip ]]; then
4115                 TEST_ERROR=$(cat $LOGDIR/skip)
4116         fi
4117         log_sub_test_end $TEST_STATUS $duration "$RC" "$TEST_ERROR"
4118
4119         if [ -f $LOGDIR/err ]; then
4120                 $FAIL_ON_ERROR && exit $RC
4121         fi
4122
4123         umask $SAVE_UMASK
4124
4125         return 0
4126 }
4127
4128 #
4129 # Print information of skipped tests to result.yml
4130 #
4131 skip_logged(){
4132         log_sub_test_begin $1
4133         shift
4134         log_sub_test_end "SKIP" "0" "0" "$@"
4135 }
4136
4137 canonical_path() {
4138     (cd `dirname $1`; echo $PWD/`basename $1`)
4139 }
4140
4141
4142 check_grant() {
4143     export base=`basetest $1`
4144     [ "$CHECK_GRANT" == "no" ] && return 0
4145
4146         testname=GCHECK_ONLY_${base}
4147         [ ${!testname}x == x ] && return 0
4148
4149     echo -n "checking grant......"
4150
4151         local clients=$CLIENTS
4152         [ -z $clients ] && clients=$(hostname)
4153
4154     # sync all the data and make sure no pending data on server
4155     do_nodes $clients sync
4156
4157     # get client grant
4158     client_grant=`do_nodes $clients \
4159                     "$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes" | \
4160                     awk '{total += $1} END{print total}'`
4161
4162     # get server grant
4163     server_grant=`do_nodes $(comma_list $(osts_nodes)) \
4164                     "$LCTL get_param -n obdfilter.${FSNAME}-OST*.tot_granted" |
4165                     awk '{total += $1} END{print total}'`
4166
4167     # check whether client grant == server grant
4168     if [ $client_grant -ne $server_grant ]; then
4169         echo "failed: client:${client_grant} server: ${server_grant}."
4170         do_nodes $(comma_list $(osts_nodes)) \
4171                    "$LCTL get_param obdfilter.${FSNAME}-OST*.tot*"
4172         do_nodes $clients "$LCTL get_param osc.${FSNAME}-*.cur_*_bytes"
4173         return 1
4174     else
4175         echo "pass: client:${client_grant} server: ${server_grant}"
4176     fi
4177
4178 }
4179
4180 ########################
4181 # helper functions
4182
4183 osc_to_ost()
4184 {
4185     osc=$1
4186     ost=`echo $1 | awk -F_ '{print $3}'`
4187     if [ -z $ost ]; then
4188         ost=`echo $1 | sed 's/-osc.*//'`
4189     fi
4190     echo $ost
4191 }
4192
4193 ostuuid_from_index()
4194 {
4195     $LFS osts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
4196 }
4197
4198 ostname_from_index() {
4199     local uuid=$(ostuuid_from_index $1)
4200     echo ${uuid/_UUID/}
4201 }
4202
4203 index_from_ostuuid()
4204 {
4205     $LFS osts $2 | sed -ne "/${1}/s/\(.*\): .* .*$/\1/p"
4206 }
4207
4208 mdtuuid_from_index()
4209 {
4210     $LFS mdts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"
4211 }
4212
4213 remote_node () {
4214     local node=$1
4215     [ "$node" != "$(hostname)" ]
4216 }
4217
4218 remote_mds ()
4219 {
4220     local node
4221     for node in $(mdts_nodes); do
4222         remote_node $node && return 0
4223     done
4224     return 1
4225 }
4226
4227 remote_mds_nodsh()
4228 {
4229     [ "$CLIENTONLY" ] && return 0 || true
4230     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
4231 }
4232
4233 require_dsh_mds()
4234 {
4235         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
4236             MSKIPPED=1 && return 1
4237         return 0
4238 }
4239
4240 remote_ost ()
4241 {
4242     local node
4243     for node in $(osts_nodes) ; do
4244         remote_node $node && return 0
4245     done
4246     return 1
4247 }
4248
4249 remote_ost_nodsh()
4250 {
4251     [ "$CLIENTONLY" ] && return 0 || true 
4252     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
4253 }
4254
4255 require_dsh_ost()
4256 {
4257         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
4258             OSKIPPED=1 && return 1
4259         return 0
4260 }
4261
4262 remote_mgs_nodsh()
4263 {
4264     local MGS 
4265     MGS=$(facet_host mgs)
4266     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
4267 }
4268
4269 local_mode ()
4270 {
4271     remote_mds_nodsh || remote_ost_nodsh || \
4272         $(single_local_node $(comma_list $(nodes_list)))
4273 }
4274
4275 mdts_nodes () {
4276     local MDSNODES
4277     local NODES_sort
4278     for num in `seq $MDSCOUNT`; do
4279         MDSNODES="$MDSNODES $(facet_host mds$num)"
4280     done
4281     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
4282
4283     echo $NODES_sort
4284 }
4285
4286 remote_servers () {
4287     remote_ost && remote_mds
4288 }
4289
4290 facets_nodes () {
4291     local facets=$1
4292     local nodes
4293     local NODES_sort
4294
4295     for facet in ${facets//,/ }; do
4296         if [ "$FAILURE_MODE" = HARD ]; then
4297             nodes="$nodes $(facet_active_host $facet)"
4298         else
4299             nodes="$nodes $(facet_host $facet)"
4300         fi
4301     done
4302     NODES_sort=$(for i in $nodes; do echo $i; done | sort -u)
4303
4304     echo $NODES_sort
4305 }
4306
4307 osts_nodes () {
4308     local facets=$(get_facets OST)
4309     local nodes=$(facets_nodes $facets)
4310
4311     echo $nodes
4312 }
4313
4314 nodes_list () {
4315     # FIXME. We need a list of clients
4316     local myNODES=$HOSTNAME
4317     local myNODES_sort
4318
4319     # CLIENTS (if specified) contains the local client
4320     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
4321
4322     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
4323         myNODES="$myNODES $(facets_nodes $(get_facets))"
4324     fi
4325
4326     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
4327
4328     echo $myNODES_sort
4329 }
4330
4331 remote_nodes_list () {
4332     local rnodes=$(nodes_list)
4333     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
4334     echo $rnodes
4335 }
4336
4337 init_clients_lists () {
4338     # Sanity check: exclude the local client from RCLIENTS
4339     local clients=$(hostlist_expand "$RCLIENTS")
4340     local rclients=$(exclude_items_from_list "$clients" $HOSTNAME)
4341
4342     # Sanity check: exclude the dup entries
4343     RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)
4344
4345     clients="$SINGLECLIENT $HOSTNAME $RCLIENTS"
4346
4347     # Sanity check: exclude the dup entries from CLIENTS
4348     # for those configs which has SINGLCLIENT set to local client
4349     clients=$(for i in $clients; do echo $i; done | sort -u)
4350
4351     CLIENTS=$(comma_list $clients)
4352     local -a remoteclients=($RCLIENTS)
4353     for ((i=0; $i<${#remoteclients[@]}; i++)); do
4354             varname=CLIENT$((i + 2))
4355             eval $varname=${remoteclients[i]}
4356     done
4357
4358     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
4359 }
4360
4361 get_random_entry () {
4362     local rnodes=$1
4363
4364     rnodes=${rnodes//,/ }
4365
4366     local -a nodes=($rnodes)
4367     local num=${#nodes[@]} 
4368     local i=$((RANDOM * num * 2 / 65536))
4369
4370     echo ${nodes[i]}
4371 }
4372
4373 client_only () {
4374     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
4375 }
4376
4377 is_patchless ()
4378 {
4379     lctl get_param version | grep -q patchless
4380 }
4381
4382 check_versions () {
4383     [ "$(lustre_version_code client)" = "$(lustre_version_code $SINGLEMDS)" -a \
4384       "$(lustre_version_code client)" = "$(lustre_version_code ost1)" ]
4385 }
4386
4387 get_node_count() {
4388     local nodes="$@"
4389     echo $nodes | wc -w || true
4390 }
4391
4392 mixed_ost_devs () {
4393     local nodes=$(osts_nodes)
4394     local osscount=$(get_node_count "$nodes")
4395     [ ! "$OSTCOUNT" = "$osscount" ]
4396 }
4397
4398 mixed_mdt_devs () {
4399     local nodes=$(mdts_nodes)
4400     local mdtcount=$(get_node_count "$nodes")
4401     [ ! "$MDSCOUNT" = "$mdtcount" ]
4402 }
4403
4404 generate_machine_file() {
4405     local nodes=${1//,/ }
4406     local machinefile=$2
4407     rm -f $machinefile
4408     for node in $nodes; do
4409         echo $node >>$machinefile || \
4410             { echo "can not generate machinefile $machinefile" && return 1; }
4411     done
4412 }
4413
4414 get_stripe () {
4415     local file=$1/stripe
4416     touch $file
4417     $LFS getstripe -v $file || error
4418     rm -f $file
4419 }
4420
4421 setstripe_nfsserver () {
4422     local dir=$1
4423
4424     local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
4425                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -1)
4426
4427     [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
4428
4429     do_nodev $nfsserver lfs setstripe "$@"
4430 }
4431
4432 # Check and add a test group.
4433 add_group() {
4434         local group_id=$1
4435         local group_name=$2
4436         local rc=0
4437
4438         local gid=$(getent group $group_name | cut -d: -f3)
4439         if [[ -n "$gid" ]]; then
4440                 [[ "$gid" -eq "$group_id" ]] || {
4441                         error_noexit "inconsistent group ID:" \
4442                                      "new: $group_id, old: $gid"
4443                         rc=1
4444                 }
4445         else
4446                 groupadd -g $group_id $group_name
4447                 rc=${PIPESTATUS[0]}
4448         fi
4449
4450         return $rc
4451 }
4452
4453 # Check and add a test user.
4454 add_user() {
4455         local user_id=$1
4456         shift
4457         local user_name=$1
4458         shift
4459         local group_name=$1
4460         shift
4461         local home=$1
4462         shift
4463         local opts="$@"
4464         local rc=0
4465
4466         local uid=$(getent passwd $user_name | cut -d: -f3)
4467         if [[ -n "$uid" ]]; then
4468                 if [[ "$uid" -eq "$user_id" ]]; then
4469                         local dir=$(getent passwd $user_name | cut -d: -f6)
4470                         if [[ "$dir" != "$home" ]]; then
4471                                 mkdir -p $home
4472                                 usermod -d $home $user_name
4473                                 rc=${PIPESTATUS[0]}
4474                         fi
4475                 else
4476                         error_noexit "inconsistent user ID:" \
4477                                      "new: $user_id, old: $uid"
4478                         rc=1
4479                 fi
4480         else
4481                 mkdir -p $home
4482                 useradd -M -u $user_id -d $home -g $group_name $opts $user_name
4483                 rc=${PIPESTATUS[0]}
4484         fi
4485
4486         return $rc
4487 }
4488
4489 check_runas_id_ret() {
4490     local myRC=0
4491     local myRUNAS_UID=$1
4492     local myRUNAS_GID=$2
4493     shift 2
4494     local myRUNAS=$@
4495     if [ -z "$myRUNAS" ]; then
4496         error_exit "myRUNAS command must be specified for check_runas_id"
4497     fi
4498     if $GSS_KRB5; then
4499         $myRUNAS krb5_login.sh || \
4500             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
4501     fi
4502     mkdir $DIR/d0_runas_test
4503     chmod 0755 $DIR
4504     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
4505     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
4506     rm -rf $DIR/d0_runas_test
4507     return $myRC
4508 }
4509
4510 check_runas_id() {
4511     local myRUNAS_UID=$1
4512     local myRUNAS_GID=$2
4513     shift 2
4514     local myRUNAS=$@
4515     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
4516         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
4517         Please set RUNAS_ID to some UID which exists on MDS and client or
4518         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
4519 }
4520
4521 # obtain the UID/GID for MPI_USER
4522 get_mpiuser_id() {
4523     local mpi_user=$1
4524
4525     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
4526 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
4527
4528     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
4529 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
4530 }
4531
4532 # obtain and cache Kerberos ticket-granting ticket
4533 refresh_krb5_tgt() {
4534     local myRUNAS_UID=$1
4535     local myRUNAS_GID=$2
4536     shift 2
4537     local myRUNAS=$@
4538     if [ -z "$myRUNAS" ]; then
4539         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
4540     fi
4541
4542     CLIENTS=${CLIENTS:-$HOSTNAME}
4543     do_nodes $CLIENTS "set -x
4544 if ! $myRUNAS krb5_login.sh; then
4545     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
4546     exit 1
4547 fi"
4548 }
4549
4550 # Run multiop in the background, but wait for it to print
4551 # "PAUSING" to its stdout before returning from this function.
4552 multiop_bg_pause() {
4553     MULTIOP_PROG=${MULTIOP_PROG:-$MULTIOP}
4554     FILE=$1
4555     ARGS=$2
4556
4557     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
4558     mkfifo $TMPPIPE
4559
4560     echo "$MULTIOP_PROG $FILE v$ARGS"
4561     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
4562
4563     echo "TMPPIPE=${TMPPIPE}"
4564     read -t 60 multiop_output < $TMPPIPE
4565     if [ $? -ne 0 ]; then
4566         rm -f $TMPPIPE
4567         return 1
4568     fi
4569     rm -f $TMPPIPE
4570     if [ "$multiop_output" != "PAUSING" ]; then
4571         echo "Incorrect multiop output: $multiop_output"
4572         kill -9 $PID
4573         return 1
4574     fi
4575
4576     return 0
4577 }
4578
4579 do_and_time () {
4580     local cmd=$1
4581     local rc
4582
4583     SECONDS=0
4584     eval '$cmd'
4585     
4586     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
4587
4588     echo $SECONDS
4589     return $rc
4590 }
4591
4592 inodes_available () {
4593     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
4594     echo $IFree
4595 }
4596
4597 mdsrate_inodes_available () {
4598     local min_inodes=$(inodes_available)
4599     echo $((min_inodes * 99 / 100))
4600 }
4601
4602 # reset llite stat counters
4603 clear_llite_stats(){
4604         lctl set_param -n llite.*.stats 0
4605 }
4606
4607 # sum llite stat items
4608 calc_llite_stats() {
4609         local res=$(lctl get_param -n llite.*.stats |
4610                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
4611         echo $res
4612 }
4613
4614 # reset osc stat counters
4615 clear_osc_stats(){
4616         lctl set_param -n osc.*.osc_stats 0
4617 }
4618
4619 # sum osc stat items
4620 calc_osc_stats() {
4621         local res=$(lctl get_param -n osc.*.osc_stats |
4622                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
4623         echo $res
4624 }
4625
4626 calc_sum () {
4627         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
4628 }
4629
4630 calc_osc_kbytes () {
4631         df $MOUNT > /dev/null
4632         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
4633 }
4634
4635 # save_lustre_params(node, parameter_mask)
4636 # generate a stream of formatted strings (<node> <param name>=<param value>)
4637 save_lustre_params() {
4638         local s
4639         do_nodesv $1 "lctl get_param $2 | while read s; do echo \\\$s; done"
4640 }
4641
4642 # restore lustre parameters from input stream, produces by save_lustre_params
4643 restore_lustre_params() {
4644         local node
4645         local name
4646         local val
4647         while IFS=" =" read node name val; do
4648                 do_node ${node//:/} "lctl set_param -n $name $val"
4649         done
4650 }
4651
4652 check_catastrophe() {
4653     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
4654     local C=$CATASTROPHE
4655     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
4656
4657     if [ $rnodes ]; then
4658         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
4659 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
4660 exit \\\$rc;"
4661     fi 
4662 }
4663
4664 # CMD: determine mds index where directory inode presents
4665 get_mds_dir () {
4666     local dir=$1
4667     local file=$dir/f0.get_mds_dir_tmpfile
4668
4669     mkdir -p $dir
4670     rm -f $file
4671     sleep 1
4672     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
4673     local -a oldused=($iused)
4674
4675     openfile -f O_CREAT:O_LOV_DELAY_CREATE -m 0644 $file > /dev/null
4676     sleep 1
4677     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
4678     local -a newused=($iused)
4679
4680     local num=0
4681     for ((i=0; i<${#newused[@]}; i++)); do
4682          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
4683              echo $(( i + 1 ))
4684              rm -f $file
4685              return 0
4686          fi
4687     done
4688     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
4689 }
4690
4691 mdsrate_cleanup () {
4692     if [ -d $4 ]; then
4693         mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
4694         rmdir $4
4695     fi
4696 }
4697
4698 delayed_recovery_enabled () {
4699     local var=${SINGLEMDS}_svc
4700     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
4701 }
4702
4703 ########################
4704
4705 convert_facet2label() { 
4706     local facet=$1
4707
4708     if [ x$facet = xost ]; then
4709        facet=ost1
4710     fi
4711
4712     local varsvc=${facet}_svc
4713
4714     if [ -n ${!varsvc} ]; then
4715         echo ${!varsvc}
4716     else  
4717         error "No lablel for $facet!"
4718     fi
4719 }
4720
4721 get_clientosc_proc_path() {
4722     echo "${1}-osc-[^M]*"
4723 }
4724
4725 get_lustre_version () {
4726     local facet=${1:-"$SINGLEMDS"}    
4727     do_facet $facet $LCTL get_param -n version | awk '/^lustre:/ {print $2}'
4728 }
4729
4730 lustre_version_code() {
4731     local facet=${1:-"$SINGLEMDS"}
4732     version_code $(get_lustre_version $1)
4733 }
4734
4735 # If the 2.0 MDS was mounted on 1.8 device, then the OSC and LOV names
4736 # used by MDT would not be changed.
4737 # mdt lov: fsname-mdtlov
4738 # mdt osc: fsname-OSTXXXX-osc
4739 mds_on_old_device() {
4740     local mds=${1:-"$SINGLEMDS"}
4741
4742     if [ $(lustre_version_code $mds) -gt $(version_code 1.9.0) ]; then
4743         do_facet $mds "lctl list_param osc.$FSNAME-OST*-osc \
4744             > /dev/null 2>&1" && return 0
4745     fi
4746     return 1
4747 }
4748
4749 get_mdtosc_proc_path() {
4750     local mds_facet=$1
4751     local ost_label=${2:-"*OST*"}
4752
4753     [ "$mds_facet" = "mds" ] && mds_facet=$SINGLEMDS
4754     local mdt_label=$(convert_facet2label $mds_facet)
4755     local mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')
4756
4757     if [ $(lustre_version_code $mds_facet) -le $(version_code 1.8.0) ] ||
4758        mds_on_old_device $mds_facet; then
4759         echo "${ost_label}-osc"
4760     else
4761         echo "${ost_label}-osc-${mdt_index}"
4762     fi
4763 }
4764
4765 get_osc_import_name() {
4766     local facet=$1
4767     local ost=$2
4768     local label=$(convert_facet2label $ost)
4769
4770     if [ "${facet:0:3}" = "mds" ]; then
4771         get_mdtosc_proc_path $facet $label
4772         return 0
4773     fi
4774
4775     get_clientosc_proc_path $label
4776     return 0
4777 }
4778
4779 _wait_import_state () {
4780     local expected=$1
4781     local CONN_PROC=$2
4782     local maxtime=${3:-$(max_recovery_time)}
4783     local CONN_STATE
4784     local i=0
4785
4786     CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
4787     while [ "${CONN_STATE}" != "${expected}" ]; do
4788         if [ "${expected}" == "DISCONN" ]; then
4789             # for disconn we can check after proc entry is removed
4790             [ "x${CONN_STATE}" == "x" ] && return 0
4791             #  with AT enabled, we can have connect request timeout near of
4792             # reconnect timeout and test can't see real disconnect
4793             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
4794         fi
4795         [ $i -ge $maxtime ] && \
4796             error "can't put import for $CONN_PROC into ${expected} state after $i sec, have ${CONN_STATE}" && \
4797             return 1
4798         sleep 1
4799         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
4800         i=$(($i + 1))
4801     done
4802
4803     log "$CONN_PROC in ${CONN_STATE} state after $i sec"
4804     return 0
4805 }
4806
4807 wait_import_state() {
4808     local state=$1
4809     local params=$2
4810     local maxtime=${3:-$(max_recovery_time)}
4811     local param
4812
4813     for param in ${params//,/ }; do
4814         _wait_import_state $state $param $maxtime || return
4815     done
4816 }
4817
4818 # One client request could be timed out because server was not ready
4819 # when request was sent by client.
4820 # The request timeout calculation details :
4821 # ptl_send_rpc ()
4822 #      /* We give the server rq_timeout secs to process the req, and
4823 #      add the network latency for our local timeout. */
4824 #      request->rq_deadline = request->rq_sent + request->rq_timeout +
4825 #           ptlrpc_at_get_net_latency(request) ;
4826 #
4827 # ptlrpc_connect_import ()
4828 #      request->rq_timeout = INITIAL_CONNECT_TIMEOUT
4829 #
4830 # init_imp_at () ->
4831 #   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0
4832 # ptlrpc_at_get_net_latency(request) ->
4833 #       at_get (max (iat_net_latency=0, at_min)) = at_min
4834 #
4835 # i.e.:
4836 # request->rq_timeout + ptlrpc_at_get_net_latency(request) =
4837 # INITIAL_CONNECT_TIMEOUT + at_min
4838 #
4839 # We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT
4840 # because we can not get this value in runtime,
4841 # the value depends on configure options, and it is not stored in /proc.
4842 # obd_support.h:
4843 # #define CONNECTION_SWITCH_MIN 5U
4844 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
4845
4846 request_timeout () {
4847     local facet=$1
4848
4849     # request->rq_timeout = INITIAL_CONNECT_TIMEOUT
4850     local init_connect_timeout=$TIMEOUT
4851     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
4852
4853     local at_min=$(at_get $facet at_min)
4854
4855     echo $(( init_connect_timeout + at_min ))
4856 }
4857
4858 wait_osc_import_state() {
4859     local facet=$1
4860     local ost_facet=$2
4861     local expected=$3
4862     local ost=$(get_osc_import_name $facet $ost_facet)
4863
4864     local param="osc.${ost}.ost_server_uuid"
4865
4866     # 1. wait the deadline of client 1st request (it could be skipped)
4867     # 2. wait the deadline of client 2nd request
4868     local maxtime=$(( 2 * $(request_timeout $facet)))
4869
4870     if ! do_rpc_nodes $(facet_host $facet) \
4871                 _wait_import_state $expected $param $maxtime; then
4872         error "import is not in ${expected} state"
4873         return 1
4874     fi
4875
4876     return 0
4877 }
4878
4879 get_clientmdc_proc_path() {
4880     echo "${1}-mdc-*"
4881 }
4882
4883 do_rpc_nodes () {
4884     local list=$1
4885     shift
4886
4887     # Add paths to lustre tests for 32 and 64 bit systems.
4888     local RPATH="PATH=$RLUSTRE/tests:/usr/lib/lustre/tests:/usr/lib64/lustre/tests:$PATH"
4889     do_nodesv $list "${RPATH} NAME=${NAME} sh rpc.sh $@ "
4890 }
4891
4892 wait_clients_import_state () {
4893     local list=$1
4894     local facet=$2
4895     local expected=$3
4896
4897     local facets=$facet
4898
4899     if [ "$FAILURE_MODE" = HARD ]; then
4900         facets=$(facets_on_host $(facet_active_host $facet))
4901     fi
4902
4903     for facet in ${facets//,/ }; do
4904     local label=$(convert_facet2label $facet)
4905     local proc_path
4906     case $facet in
4907         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
4908         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
4909         *) error "unknown facet!" ;;
4910     esac
4911     local params=$(expand_list $params $proc_path)
4912     done
4913
4914     if ! do_rpc_nodes $list wait_import_state $expected $params; then
4915         error "import is not in ${expected} state"
4916         return 1
4917     fi
4918 }
4919
4920 oos_full() {
4921         local -a AVAILA
4922         local -a GRANTA
4923         local -a TOTALA
4924         local OSCFULL=1
4925         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
4926                   $LCTL get_param obdfilter.*.kbytesavail))
4927         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
4928                   $LCTL get_param -n obdfilter.*.tot_granted))
4929         TOTALA=($(do_nodes $(comma_list $(osts_nodes)) \
4930                   $LCTL get_param -n obdfilter.*.kbytestotal))
4931         for ((i=0; i<${#AVAILA[@]}; i++)); do
4932                 local -a AVAIL1=(${AVAILA[$i]//=/ })
4933                 local -a TOTAL=(${TOTALA[$i]//=/ })
4934                 GRANT=$((${GRANTA[$i]}/1024))
4935                 # allow 1% of total space in bavail because of delayed
4936                 # allocation with ZFS which might release some free space after
4937                 # txg commit.  For small devices, we set a mininum of 8MB
4938                 local LIMIT=$((${TOTAL} / 100 + 8000))
4939                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} \
4940                         grnt=$GRANT diff=$((AVAIL1[1] - GRANT)) limit=${LIMIT}
4941                 [ $((AVAIL1[1] - GRANT)) -lt $LIMIT ] && OSCFULL=0 && \
4942                         echo " FULL" || echo
4943         done
4944         return $OSCFULL
4945 }
4946
4947 pool_list () {
4948    do_facet mgs lctl pool_list $1
4949 }
4950
4951 create_pool() {
4952     local fsname=${1%%.*}
4953     local poolname=${1##$fsname.}
4954
4955     do_facet mgs lctl pool_new $1
4956     local RC=$?
4957     # get param should return err unless pool is created
4958     [[ $RC -ne 0 ]] && return $RC
4959
4960     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
4961         2>/dev/null || echo foo" "" || RC=1
4962     if [[ $RC -eq 0 ]]; then
4963         add_pool_to_list $1
4964     else
4965         error "pool_new failed $1"
4966     fi
4967     return $RC
4968 }
4969
4970 add_pool_to_list () {
4971     local fsname=${1%%.*}
4972     local poolname=${1##$fsname.}
4973
4974     local listvar=${fsname}_CREATED_POOLS
4975     eval export ${listvar}=$(expand_list ${!listvar} $poolname)
4976 }
4977
4978 remove_pool_from_list () {
4979     local fsname=${1%%.*}
4980     local poolname=${1##$fsname.}
4981
4982     local listvar=${fsname}_CREATED_POOLS
4983     eval export ${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
4984 }
4985
4986 destroy_pool_int() {
4987     local ost
4988     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
4989         awk '$1 !~ /^Pool:/ {print $1}')
4990     for ost in $OSTS; do
4991         do_facet mgs lctl pool_remove $1 $ost
4992     done
4993     do_facet mgs lctl pool_destroy $1
4994 }
4995
4996 # <fsname>.<poolname> or <poolname>
4997 destroy_pool() {
4998     local fsname=${1%%.*}
4999     local poolname=${1##$fsname.}
5000
5001     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
5002
5003     local RC
5004
5005     pool_list $fsname.$poolname || return $?
5006
5007     destroy_pool_int $fsname.$poolname
5008     RC=$?
5009     [[ $RC -ne 0 ]] && return $RC
5010
5011     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
5012       2>/dev/null || echo foo" "foo" || RC=1
5013
5014     if [[ $RC -eq 0 ]]; then
5015         remove_pool_from_list $fsname.$poolname
5016     else
5017         error "destroy pool failed $1"
5018     fi
5019     return $RC
5020 }
5021
5022 destroy_pools () {
5023     local fsname=${1:-$FSNAME}
5024     local poolname
5025     local listvar=${fsname}_CREATED_POOLS
5026
5027     pool_list $fsname
5028
5029     [ x${!listvar} = x ] && return 0
5030
5031     echo destroy the created pools: ${!listvar}
5032     for poolname in ${!listvar//,/ }; do
5033         destroy_pool $fsname.$poolname
5034     done
5035 }
5036
5037 cleanup_pools () {
5038     local fsname=${1:-$FSNAME}
5039     trap 0
5040     destroy_pools $fsname
5041 }
5042
5043 gather_logs () {
5044     local list=$1
5045
5046     local ts=$(date +%s)
5047     local docp=true
5048
5049     if [[ ! -f "$YAML_LOG" ]]; then
5050         # init_logging is not performed before gather_logs,
5051         # so the $LOGDIR needs to be checked here
5052         check_shared_dir $LOGDIR && touch $LOGDIR/shared
5053     fi
5054
5055     [ -f $LOGDIR/shared ] && docp=false
5056
5057     # dump lustre logs, dmesg
5058
5059     prefix="$TESTLOG_PREFIX.$TESTNAME"
5060     suffix="$ts.log"
5061     echo "Dumping lctl log to ${prefix}.*.${suffix}"
5062
5063     if [ "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
5064         echo "Dumping logs only on local client."
5065         $LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}
5066         dmesg > ${prefix}.dmesg.$(hostname -s).${suffix}
5067         return
5068     fi
5069
5070     do_nodesv $list \
5071         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname -s).${suffix};
5072          dmesg > ${prefix}.dmesg.\\\$(hostname -s).${suffix}"
5073     if [ ! -f $LOGDIR/shared ]; then
5074         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
5075     fi
5076 }
5077
5078 do_ls () {
5079     local mntpt_root=$1
5080     local num_mntpts=$2
5081     local dir=$3
5082     local i
5083     local cmd
5084     local pids
5085     local rc=0
5086
5087     for i in $(seq 0 $num_mntpts); do
5088         cmd="ls -laf ${mntpt_root}$i/$dir"
5089         echo + $cmd;
5090         $cmd > /dev/null &
5091         pids="$pids $!"
5092     done
5093     echo pids=$pids
5094     for pid in $pids; do
5095         wait $pid || rc=$?
5096     done
5097
5098     return $rc
5099 }
5100
5101 # target_start_and_reset_recovery_timer()
5102 #        service_time = at_est2timeout(service_time);
5103 #        service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC +
5104 #                             INITIAL_CONNECT_TIMEOUT);
5105 # CONNECTION_SWITCH_MAX : min(25U, max(CONNECTION_SWITCH_MIN,obd_timeout))
5106 #define CONNECTION_SWITCH_INC 1
5107 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
5108 #define CONNECTION_SWITCH_MIN 5U
5109
5110 max_recovery_time () {
5111     local init_connect_timeout=$(( TIMEOUT / 20 ))
5112     [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
5113
5114     local service_time=$(( $(at_max_get client) + $(( 2 * $(( 25 + 1  + init_connect_timeout)) )) ))
5115
5116     echo $service_time 
5117 }
5118
5119 get_clients_mount_count () {
5120     local clients=${CLIENTS:-`hostname`}
5121
5122     # we need to take into account the clients mounts and
5123     # exclude mds/ost mounts if any;
5124     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
5125 }
5126
5127 # gss functions
5128 PROC_CLI="srpc_info"
5129
5130 combination()
5131 {
5132     local M=$1
5133     local N=$2
5134     local R=1
5135
5136     if [ $M -lt $N ]; then
5137         R=0
5138     else
5139         N=$((N + 1))
5140         while [ $N -lt $M ]; do
5141             R=$((R * N))
5142             N=$((N + 1))
5143         done
5144     fi
5145
5146     echo $R
5147     return 0
5148 }
5149
5150 calc_connection_cnt() {
5151     local dir=$1
5152
5153     # MDT->MDT = 2 * C(M, 2)
5154     # MDT->OST = M * O
5155     # CLI->OST = C * O
5156     # CLI->MDT = C * M
5157     comb_m2=$(combination $MDSCOUNT 2)
5158
5159     local num_clients=$(get_clients_mount_count)
5160
5161     local cnt_mdt2mdt=$((comb_m2 * 2))
5162     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
5163     local cnt_cli2ost=$((num_clients * OSTCOUNT))
5164     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
5165     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
5166     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
5167     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
5168
5169     local var=cnt_$dir
5170     local res=${!var}
5171
5172     echo $res
5173 }
5174
5175 set_rule()
5176 {
5177     local tgt=$1
5178     local net=$2
5179     local dir=$3
5180     local flavor=$4
5181     local cmd="$tgt.srpc.flavor"
5182
5183     if [ $net == "any" ]; then
5184         net="default"
5185     fi
5186     cmd="$cmd.$net"
5187
5188     if [ $dir != "any" ]; then
5189         cmd="$cmd.$dir"
5190     fi
5191
5192     cmd="$cmd=$flavor"
5193     log "Setting sptlrpc rule: $cmd"
5194     do_facet mgs "$LCTL conf_param $cmd"
5195 }
5196
5197 count_flvr()
5198 {
5199     local output=$1
5200     local flavor=$2
5201     local count=0
5202
5203     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
5204     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
5205
5206     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
5207
5208     if [ "x$bulkspec" != "x" ]; then
5209         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
5210
5211         if [ "x$algs" != "x" ]; then
5212             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
5213         else
5214             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
5215             if [ $bulk == "bulkn" ]; then
5216                 bulk_count=`echo "$output" | grep "bulk flavor" \
5217                             | grep "null/null" | wc -l`
5218             elif [ $bulk == "bulki" ]; then
5219                 bulk_count=`echo "$output" | grep "bulk flavor" \
5220                             | grep "/null" | grep -v "null/" | wc -l`
5221             else
5222                 bulk_count=`echo "$output" | grep "bulk flavor" \
5223                             | grep -v "/null" | grep -v "null/" | wc -l`
5224             fi
5225         fi
5226
5227         [ $bulk_count -lt $count ] && count=$bulk_count
5228     fi
5229
5230     echo $count
5231 }
5232
5233 flvr_cnt_cli2mdt()
5234 {
5235     local flavor=$1
5236     local cnt
5237
5238     local clients=${CLIENTS:-`hostname`}
5239
5240     for c in ${clients//,/ }; do
5241         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
5242         tmpcnt=`count_flvr "$output" $flavor`
5243         cnt=$((cnt + tmpcnt))
5244     done
5245     echo $cnt
5246 }
5247
5248 flvr_cnt_cli2ost()
5249 {
5250     local flavor=$1
5251     local cnt
5252
5253     local clients=${CLIENTS:-`hostname`}
5254
5255     for c in ${clients//,/ }; do
5256         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
5257         tmpcnt=`count_flvr "$output" $flavor`
5258         cnt=$((cnt + tmpcnt))
5259     done
5260     echo $cnt
5261 }
5262
5263 flvr_cnt_mdt2mdt()
5264 {
5265     local flavor=$1
5266     local cnt=0
5267
5268     if [ $MDSCOUNT -le 1 ]; then
5269         echo 0
5270         return
5271     fi
5272
5273     for num in `seq $MDSCOUNT`; do
5274         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
5275         tmpcnt=`count_flvr "$output" $flavor`
5276         cnt=$((cnt + tmpcnt))
5277     done
5278     echo $cnt;
5279 }
5280
5281 flvr_cnt_mdt2ost()
5282 {
5283     local flavor=$1
5284     local cnt=0
5285     local mdtosc
5286
5287     for num in `seq $MDSCOUNT`; do
5288         mdtosc=$(get_mdtosc_proc_path mds$num)
5289         mdtosc=${mdtosc/-MDT*/-MDT\*}
5290         output=$(do_facet mds$num lctl get_param -n \
5291             osc.$mdtosc.$PROC_CLI 2>/dev/null)
5292         tmpcnt=`count_flvr "$output" $flavor`
5293         cnt=$((cnt + tmpcnt))
5294     done
5295     echo $cnt;
5296 }
5297
5298 flvr_cnt_mgc2mgs()
5299 {
5300     local flavor=$1
5301
5302     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
5303     count_flvr "$output" $flavor
5304 }
5305
5306 do_check_flavor()
5307 {
5308     local dir=$1        # from to
5309     local flavor=$2     # flavor expected
5310     local res=0
5311
5312     if [ $dir == "cli2mdt" ]; then
5313         res=`flvr_cnt_cli2mdt $flavor`
5314     elif [ $dir == "cli2ost" ]; then
5315         res=`flvr_cnt_cli2ost $flavor`
5316     elif [ $dir == "mdt2mdt" ]; then
5317         res=`flvr_cnt_mdt2mdt $flavor`
5318     elif [ $dir == "mdt2ost" ]; then
5319         res=`flvr_cnt_mdt2ost $flavor`
5320     elif [ $dir == "all2ost" ]; then
5321         res1=`flvr_cnt_mdt2ost $flavor`
5322         res2=`flvr_cnt_cli2ost $flavor`
5323         res=$((res1 + res2))
5324     elif [ $dir == "all2mdt" ]; then
5325         res1=`flvr_cnt_mdt2mdt $flavor`
5326         res2=`flvr_cnt_cli2mdt $flavor`
5327         res=$((res1 + res2))
5328     elif [ $dir == "all2all" ]; then
5329         res1=`flvr_cnt_mdt2ost $flavor`
5330         res2=`flvr_cnt_cli2ost $flavor`
5331         res3=`flvr_cnt_mdt2mdt $flavor`
5332         res4=`flvr_cnt_cli2mdt $flavor`
5333         res=$((res1 + res2 + res3 + res4))
5334     fi
5335
5336     echo $res
5337 }
5338
5339 wait_flavor()
5340 {
5341     local dir=$1        # from to
5342     local flavor=$2     # flavor expected
5343     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
5344
5345     local res=0
5346
5347     for ((i=0;i<20;i++)); do
5348         echo -n "checking $dir..."
5349         res=$(do_check_flavor $dir $flavor)
5350         echo "found $res/$expect $flavor connections"
5351         [ $res -ge $expect ] && return 0
5352         sleep 4
5353     done
5354
5355     echo "Error checking $flavor of $dir: expect $expect, actual $res"
5356     return 1
5357 }
5358
5359 restore_to_default_flavor()
5360 {
5361     local proc="mgs.MGS.live.$FSNAME"
5362
5363     echo "restoring to default flavor..."
5364
5365     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
5366
5367     # remove all existing rules if any
5368     if [ $nrule -ne 0 ]; then
5369         echo "$nrule existing rules"
5370         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
5371             echo "remove rule: $rule"
5372             spec=`echo $rule | awk -F = '{print $1}'`
5373             do_facet mgs "$LCTL conf_param -d $spec"
5374         done
5375     fi
5376
5377     # verify no rules left
5378     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
5379     [ $nrule -ne 0 ] && error "still $nrule rules left"
5380
5381     # wait for default flavor to be applied
5382     # currently default flavor for all connections are 'null'
5383     wait_flavor all2all null
5384     echo "now at default flavor settings"
5385 }
5386
5387 set_flavor_all()
5388 {
5389     local flavor=${1:-null}
5390
5391     echo "setting all flavor to $flavor"
5392
5393     # FIXME need parameter to this fn
5394     # and remove global vars
5395     local cnt_all2all=$(calc_connection_cnt all2all)
5396
5397     local res=$(do_check_flavor all2all $flavor)
5398     if [ $res -eq $cnt_all2all ]; then
5399         echo "already have total $res $flavor connections"
5400         return
5401     fi
5402
5403     echo "found $res $flavor out of total $cnt_all2all connections"
5404     restore_to_default_flavor
5405
5406     [[ $flavor = null ]] && return 0
5407
5408     set_rule $FSNAME any any $flavor
5409     wait_flavor all2all $flavor
5410 }
5411
5412
5413 check_logdir() {
5414     local dir=$1
5415     # Checking for shared logdir
5416     if [ ! -d $dir ]; then
5417         # Not found. Create local logdir
5418         mkdir -p $dir
5419     else
5420         touch $dir/check_file.$(hostname -s)
5421     fi
5422     return 0
5423 }
5424
5425 check_write_access() {
5426     local dir=$1
5427     local node
5428     local file
5429
5430     for node in $(nodes_list); do
5431         file=$dir/check_file.$(short_hostname $node)
5432         if [[ ! -f "$file" ]]; then
5433             # Logdir not accessible/writable from this node.
5434             return 1
5435         fi
5436         rm -f $file || return 1
5437     done
5438     return 0
5439 }
5440
5441 init_logging() {
5442     if [[ -n $YAML_LOG ]]; then
5443         return
5444     fi
5445     local SAVE_UMASK=`umask`
5446     umask 0000
5447
5448     export YAML_LOG=${LOGDIR}/results.yml
5449     mkdir -p $LOGDIR
5450     init_clients_lists
5451
5452     if [ ! -f $YAML_LOG ]; then       # If the yaml log already exists then we will just append to it
5453       if check_shared_dir $LOGDIR; then
5454           touch $LOGDIR/shared
5455           echo "Logging to shared log directory: $LOGDIR"
5456       else
5457           echo "Logging to local directory: $LOGDIR"
5458       fi
5459
5460       yml_nodes_file $LOGDIR >> $YAML_LOG
5461       yml_results_file >> $YAML_LOG
5462     fi
5463
5464     umask $SAVE_UMASK
5465 }
5466
5467 log_test() {
5468     yml_log_test $1 >> $YAML_LOG
5469 }
5470
5471 log_test_status() {
5472      yml_log_test_status $@ >> $YAML_LOG
5473 }
5474
5475 log_sub_test_begin() {
5476     yml_log_sub_test_begin "$@" >> $YAML_LOG
5477 }
5478
5479 log_sub_test_end() {
5480     yml_log_sub_test_end "$@" >> $YAML_LOG
5481 }
5482
5483 run_llverdev()
5484 {
5485         local dev=$1
5486         local llverdev_opts=$2
5487         local devname=$(basename $1)
5488         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
5489         # loop devices aren't in /proc/partitions
5490         [ "x$size" == "x" ] && local size=$(ls -l $dev | awk '{print $5}')
5491
5492         size=$(($size / 1024 / 1024)) # Gb
5493
5494         local partial_arg=""
5495         # Run in partial (fast) mode if the size
5496         # of a partition > 1 GB
5497         [ $size -gt 1 ] && partial_arg="-p"
5498
5499         llverdev --force $partial_arg $llverdev_opts $dev
5500 }
5501
5502 run_llverfs()
5503 {
5504         local dir=$1
5505         local llverfs_opts=$2
5506         local partial_arg=""
5507         local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB
5508
5509         # Run in partial (fast) mode if the size
5510         # of a partition > 1 GB
5511         [ $size -gt 1 ] && partial_arg="-p"
5512
5513         llverfs $partial_arg $llverfs_opts $dir
5514 }
5515
5516 remove_mdt_files() {
5517         local facet=$1
5518         local mdtdev=$2
5519         shift 2
5520         local files="$@"
5521         local mntpt=$(facet_mntpt $facet)
5522         local opts=$MDS_MOUNT_OPTS
5523
5524         echo "removing files from $mdtdev on $facet: $files"
5525         if [ $(facet_fstype $facet) == ldiskfs ] &&
5526            ! do_facet $facet test -b ${!dev}; then
5527                 opts=$(csa_add "$opts" -o loop)
5528         fi
5529         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
5530                 return $?
5531         rc=0;
5532         for f in $files; do
5533                 rm $mntpt/ROOT/$f || { rc=$?; break; }
5534         done
5535         umount -f $mntpt || return $?
5536         return $rc
5537 }
5538
5539 duplicate_mdt_files() {
5540         local facet=$1
5541         local mdtdev=$2
5542         shift 2
5543         local files="$@"
5544         local mntpt=$(facet_mntpt $facet)
5545         local opts=$MDS_MOUNT_OPTS
5546
5547         echo "duplicating files on $mdtdev on $facet: $files"
5548         mkdir -p $mntpt || return $?
5549         if [ $(facet_fstype $facet) == ldiskfs ] &&
5550            ! do_facet $facet test -b ${!dev}; then
5551                 opts=$(csa_add "$opts" -o loop)
5552         fi
5553         mount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||
5554                 return $?
5555
5556     do_umount() {
5557         trap 0
5558         popd > /dev/null
5559         rm $tmp
5560         umount -f $mntpt
5561     }
5562     trap do_umount EXIT
5563
5564     tmp=$(mktemp $TMP/setfattr.XXXXXXXXXX)
5565     pushd $mntpt/ROOT > /dev/null || return $?
5566     rc=0
5567     for f in $files; do
5568         touch $f.bad || return $?
5569         getfattr -n trusted.lov $f | sed "s#$f#&.bad#" > $tmp
5570         rc=${PIPESTATUS[0]}
5571         [ $rc -eq 0 ] || return $rc
5572         setfattr --restore $tmp || return $?
5573     done
5574     do_umount
5575 }
5576
5577 run_sgpdd () {
5578     local devs=${1//,/ }
5579     shift
5580     local params=$@
5581     local rslt=$TMP/sgpdd_survey
5582
5583     # sgpdd-survey cleanups ${rslt}.* files
5584
5585     local cmd="rslt=$rslt $params scsidevs=\"$devs\" $SGPDDSURVEY"
5586     echo + $cmd
5587     eval $cmd
5588     cat ${rslt}.detail
5589 }
5590
5591 # returns the canonical name for an ldiskfs device
5592 ldiskfs_canon() {
5593         local dev="$1"
5594         local facet="$2"
5595
5596         do_facet $facet "dv=\\\$(lctl get_param -n $dev);
5597 if foo=\\\$(lvdisplay -c \\\$dv 2>/dev/null); then
5598     echo dm-\\\${foo##*:};
5599 else
5600     echo \\\$(basename \\\$dv);
5601 fi;"
5602 }
5603
5604 is_sanity_benchmark() {
5605     local benchmarks="dbench bonnie iozone fsx"
5606     local suite=$1
5607     for b in $benchmarks; do
5608         if [ "$b" == "$suite" ]; then
5609             return 0
5610         fi
5611     done
5612     return 1
5613 }
5614
5615 min_ost_size () {
5616     $LCTL get_param -n osc.*.kbytesavail | sort -n | head -n1
5617 }
5618
5619 # Get the block size of the filesystem.
5620 get_block_size() {
5621     local facet=$1
5622     local device=$2
5623     local size
5624
5625     size=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
5626            awk '/^Block size:/ {print $3}')
5627     echo $size
5628 }
5629
5630 # Check whether the "large_xattr" feature is enabled or not.
5631 large_xattr_enabled() {
5632     local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
5633
5634     do_facet $SINGLEMDS "$DUMPE2FS -h $mds_dev 2>&1 | grep -q large_xattr"
5635     return ${PIPESTATUS[0]}
5636 }
5637
5638 # Get the maximum xattr size supported by the filesystem.
5639 max_xattr_size() {
5640     local size
5641
5642     if large_xattr_enabled; then
5643         # include/linux/limits.h: #define XATTR_SIZE_MAX 65536
5644         size=65536
5645     else
5646         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
5647         local block_size=$(get_block_size $SINGLEMDS $mds_dev)
5648
5649         # maximum xattr size = size of block - size of header -
5650         #                      size of 1 entry - 4 null bytes
5651         size=$((block_size - 32 - 32 - 4))
5652     fi
5653
5654     echo $size
5655 }
5656
5657 # Dump the value of the named xattr from a file.
5658 get_xattr_value() {
5659     local xattr_name=$1
5660     local file=$2
5661
5662     echo "$(getfattr -n $xattr_name --absolute-names --only-values $file)"
5663 }
5664
5665 # Generate a string with size of $size bytes.
5666 generate_string() {
5667     local size=${1:-1024} # in bytes
5668
5669     echo "$(head -c $size < /dev/zero | tr '\0' y)"
5670 }
5671
5672 reformat_external_journal() {
5673         if [ ! -z ${EJOURNAL} ]; then
5674                 local rcmd="do_facet ${SINGLEMDS}"
5675
5676                 echo "reformat external journal on ${SINGLEMDS}:${EJOURNAL}"
5677                 ${rcmd} mke2fs -O journal_dev ${EJOURNAL} || return 1
5678         fi
5679 }
5680
5681 # MDT file-level backup/restore
5682 mds_backup_restore() {
5683         local devname=$(mdsdevname ${SINGLEMDS//mds/})
5684         local mntpt=$(facet_mntpt brpt)
5685         local rcmd="do_facet ${SINGLEMDS}"
5686         local metaea=${TMP}/backup_restore.ea
5687         local metadata=${TMP}/backup_restore.tgz
5688         local opts=${MDS_MOUNT_OPTS}
5689
5690         if ! ${rcmd} test -b ${devname}; then
5691                 opts=$(csa_add "$opts" -o loop)
5692         fi
5693
5694         echo "file-level backup/restore on ${SINGLEMDS}:${devname}"
5695
5696         # step 1: build mount point
5697         ${rcmd} mkdir -p $mntpt
5698         # step 2: cleanup old backup
5699         ${rcmd} rm -f $metaea $metadata
5700         # step 3: mount dev
5701         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
5702         # step 4: backup metaea
5703         echo "backup EA"
5704         ${rcmd} "cd $mntpt && getfattr -R -d -m '.*' -P . > $metaea && cd -" ||
5705                 return 2
5706         # step 5: backup metadata
5707         echo "backup data"
5708         ${rcmd} tar zcf $metadata -C $mntpt/ . > /dev/null 2>&1 || return 3
5709         # step 6: umount
5710         ${rcmd} umount -d $mntpt || return 4
5711         # step 7: reformat external journal if needed
5712         reformat_external_journal || return 5
5713         # step 8: reformat dev
5714         echo "reformat new device"
5715         add ${SINGLEMDS} $(mkfs_opts ${SINGLEMDS}) --backfstype ldiskfs \
5716                 --reformat $devname > /dev/null || return 6
5717         # step 9: mount dev
5718         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 7
5719         # step 10: restore metadata
5720         echo "restore data"
5721         ${rcmd} tar zxfp $metadata -C $mntpt > /dev/null 2>&1 || return 8
5722         # step 11: restore metaea
5723         echo "restore EA"
5724         ${rcmd} "cd $mntpt && setfattr --restore=$metaea && cd - " || return 9
5725         # step 12: remove recovery logs
5726         echo "remove recovery logs"
5727         ${rcmd} rm -fv $mntpt/OBJECTS/* $mntpt/CATALOGS
5728         # step 13: umount dev
5729         ${rcmd} umount -d $mntpt || return 10
5730         # step 14: cleanup tmp backup
5731         ${rcmd} rm -f $metaea $metadata
5732 }
5733
5734 # remove OI files
5735 mds_remove_ois() {
5736         local devname=$(mdsdevname ${SINGLEMDS//mds/})
5737         local mntpt=$(facet_mntpt brpt)
5738         local rcmd="do_facet ${SINGLEMDS}"
5739         local idx=$1
5740         local opts=${MDS_MOUNT_OPTS}
5741
5742         if ! ${rcmd} test -b ${devname}; then
5743                 opts=$(csa_add "$opts" -o loop)
5744         fi
5745
5746         echo "remove OI files: idx=${idx}"
5747
5748         # step 1: build mount point
5749         ${rcmd} mkdir -p $mntpt
5750         # step 2: mount dev
5751         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
5752         if [ -z $idx ]; then
5753                 # step 3: remove all OI files
5754                 ${rcmd} rm -fv $mntpt/oi.16*
5755         elif [ $idx -lt 2 ]; then
5756                 ${rcmd} rm -fv $mntpt/oi.16.${idx}
5757         else
5758                 local i
5759
5760                 # others, rm oi.16.[idx, idx * idx, idx ** ...]
5761                 for ((i=${idx}; i<64; i=$((i * idx)))); do
5762                         ${rcmd} rm -fv $mntpt/oi.16.${i}
5763                 done
5764         fi
5765         # step 4: umount
5766         ${rcmd} umount -d $mntpt || return 2
5767         # OI files will be recreated when mounted as lustre next time.
5768 }