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