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