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