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