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