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