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