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