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