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