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