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