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