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