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