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