Whamcloud - gitweb
b=22312 write_bytes are missing in obdfilter stats
[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 && echo "test-framework exiting on error"' ERR
5 set -e
6 #set -x
7
8
9 export REFORMAT=${REFORMAT:-""}
10 export WRITECONF=${WRITECONF:-""}
11 export VERBOSE=false
12 export GMNALNID=${GMNALNID:-/usr/sbin/gmlndnid}
13 export CATASTROPHE=${CATASTROPHE:-/proc/sys/lnet/catastrophe}
14 export GSS=false
15 export GSS_KRB5=false
16 export GSS_PIPEFS=false
17 export IDENTITY_UPCALL=default
18 export QUOTA_AUTO=1
19
20 #export PDSH="pdsh -S -Rssh -w"
21
22 # function used by scripts run on remote nodes
23 LUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}
24 . $LUSTRE/tests/functions.sh
25 . $LUSTRE/tests/yaml.sh
26
27 LUSTRE_TESTS_CFG_DIR=${LUSTRE_TESTS_CFG_DIR:-${LUSTRE}/tests/cfg}
28
29 EXCEPT_LIST_FILE=${EXCEPT_LIST_FILE:-${LUSTRE_TESTS_CFG_DIR}/tests-to-skip.sh}
30
31 if [ -f "$EXCEPT_LIST_FILE" ]; then
32     echo "Reading test skip list from $EXCEPT_LIST_FILE"
33     cat $EXCEPT_LIST_FILE
34     . $EXCEPT_LIST_FILE
35 fi
36
37 if [[ -x $LUSTRE/utils/llobdstat ]]; then
38         LLOBDSTAT=$LUSTRE/utils/llobdstat
39 elif [[ -x /usr/bin/llobdstat ]]; then
40         LLOBDSTAT=/usr/bin/llobdstat
41 else
42         # Good luck
43         LLOBDSTAT=llobdstat
44 fi
45
46 [ -z "$MODPROBECONF" -a -f /etc/modprobe.conf ] && MODPROBECONF=/etc/modprobe.conf
47 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/Lustre ] && MODPROBECONF=/etc/modprobe.d/Lustre
48
49 assert_DIR () {
50     local failed=""
51     [[ $DIR/ = $MOUNT/* ]] || \
52         { failed=1 && echo "DIR=$DIR not in $MOUNT. Aborting."; }
53     [[ $DIR1/ = $MOUNT1/* ]] || \
54         { failed=1 && echo "DIR1=$DIR1 not in $MOUNT1. Aborting."; }
55     [[ $DIR2/ = $MOUNT2/* ]] || \
56         { failed=1 && echo "DIR2=$DIR2 not in $MOUNT2. Aborting"; }
57
58     [ -n "$failed" ] && exit 99 || true
59 }
60
61 usage() {
62     echo "usage: $0 [-r] [-f cfgfile]"
63     echo "       -r: reformat"
64
65     exit
66 }
67
68 print_summary () {
69     trap 0
70     [ "$TESTSUITE" == "lfsck" ] && return 0
71     [ -n "$ONLY" ] && echo "WARNING: ONLY is set to ${ONLY}."
72     local form="%-13s %-17s %s\n"
73     printf "$form" "status" "script" "skipped tests E(xcluded) S(low)"
74     echo "------------------------------------------------------------------------------------"
75     for O in $DEFAULT_SUITES; do
76         local skipped=""
77         local slow=""
78         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
79         local o=$(echo $O  | tr "[:upper:]" "[:lower:]")
80         o=${o//_/-}
81         local log=${TMP}/${o}.log
82         [ -f $log ] && skipped=$(grep excluded $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
83         [ -f $log ] && slow=$(grep SLOW $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
84         [ "${!O}" = "done" ] && \
85             printf "$form" "Done" "$O" "E=$skipped" && \
86             [ -n "$slow" ] && printf "$form" "-" "-" "S=$slow"
87
88     done
89
90     for O in $DEFAULT_SUITES; do
91         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
92         if [ "${!O}" = "no" ]; then
93             # FIXME.
94             # only for those tests suits which are run directly from acc-sm script:
95             # bonnie, iozone, etc.
96             if [ -f "$TESTSUITELOG" ] && grep FAIL $TESTSUITELOG | grep -q ' '$O  ; then
97                printf "$form" "UNFINISHED" "$O" ""  
98             else
99                printf "$form" "Skipped" "$O" ""
100             fi
101         fi
102     done
103
104     for O in $DEFAULT_SUITES; do
105         O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
106         [ "${!O}" = "done" -o "${!O}" = "no" ] || \
107             printf "$form" "UNFINISHED" "$O" ""
108     done
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
124     #[ -d /r ] && export ROOT=${ROOT:-/r}
125     export TMP=${TMP:-$ROOT/tmp}
126     export TESTSUITELOG=${TMP}/${TESTSUITE}.log
127     if [[ -z $LOGDIRSET ]]; then
128         export LOGDIR=${LOGDIR:-${TMP}/test_logs/}/$(date +%s)
129         export LOGDIRSET=true
130     fi
131     export HOSTNAME=${HOSTNAME:-`hostname`}
132     if ! echo $PATH | grep -q $LUSTRE/utils; then
133         export PATH=$PATH:$LUSTRE/utils
134     fi
135     if ! echo $PATH | grep -q $LUSTRE/utils/gss; then
136         export PATH=$PATH:$LUSTRE/utils/gss
137     fi
138     if ! echo $PATH | grep -q $LUSTRE/tests; then
139         export PATH=$PATH:$LUSTRE/tests
140     fi
141     export LST=${LST:-"$LUSTRE/../lnet/utils/lst"}
142     [ ! -f "$LST" ] && export LST=$(which lst)
143     export MDSRATE=${MDSRATE:-"$LUSTRE/tests/mpi/mdsrate"}
144     [ ! -f "$MDSRATE" ] && export MDSRATE=$(which mdsrate 2> /dev/null)
145     if ! echo $PATH | grep -q $LUSTRE/tests/racer; then
146         export PATH=$LUSTRE/tests/racer:$PATH:
147     fi
148     if ! echo $PATH | grep -q $LUSTRE/tests/mpi; then
149         export PATH=$PATH:$LUSTRE/tests/mpi
150     fi
151     export RSYNC_RSH=${RSYNC_RSH:-rsh}
152     export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
153     [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
154     export LFS=${LFS:-"$LUSTRE/utils/lfs"}
155     [ ! -f "$LFS" ] && export LFS=$(which lfs)
156     export L_GETIDENTITY=${L_GETIDENTITY:-"$LUSTRE/utils/l_getidentity"}
157     if [ ! -f "$L_GETIDENTITY" ]; then
158         if `which l_getidentity > /dev/null 2>&1`; then
159             export L_GETIDENTITY=$(which l_getidentity)
160         else
161             export L_GETIDENTITY=NONE
162         fi
163     fi
164     export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
165     [ ! -f "$MKFS" ] && export MKFS=$(which mkfs.lustre)
166     export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
167     [ ! -f "$TUNEFS" ] && export TUNEFS=$(which tunefs.lustre)
168     export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
169     export LUSTRE_RMMOD=${LUSTRE_RMMOD:-$LUSTRE/scripts/lustre_rmmod}
170     [ ! -f "$LUSTRE_RMMOD" ] && export LUSTRE_RMMOD=$(which lustre_rmmod 2> /dev/null)
171     export FSTYPE=${FSTYPE:-"ldiskfs"}
172     export NAME=${NAME:-local}
173     export LGSSD=${LGSSD:-"$LUSTRE/utils/gss/lgssd"}
174     [ "$GSS_PIPEFS" = "true" ] && [ ! -f "$LGSSD" ] && \
175         export LGSSD=$(which lgssd)
176     export LSVCGSSD=${LSVCGSSD:-"$LUSTRE/utils/gss/lsvcgssd"}
177     [ ! -f "$LSVCGSSD" ] && export LSVCGSSD=$(which lsvcgssd 2> /dev/null)
178     export KRB5DIR=${KRB5DIR:-"/usr/kerberos"}
179     export DIR2
180     export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
181     export AT_MAX_PATH
182
183     if [ "$ACCEPTOR_PORT" ]; then
184         export PORT_OPT="--port $ACCEPTOR_PORT"
185     fi
186
187     case "x$SEC" in
188         xkrb5*)
189             echo "Using GSS/krb5 ptlrpc security flavor"
190             which lgss_keyring > /dev/null 2>&1 || \
191                 error_exit "built with gss disabled! SEC=$SEC"
192             GSS=true
193             GSS_KRB5=true
194             ;;
195     esac
196
197     case "x$IDUP" in
198         xtrue)
199             IDENTITY_UPCALL=true
200             ;;
201         xfalse)
202             IDENTITY_UPCALL=false
203             ;;
204     esac
205     export LOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}
206
207     # Paths on remote nodes, if different
208     export RLUSTRE=${RLUSTRE:-$LUSTRE}
209     export RPWD=${RPWD:-$PWD}
210     export I_MOUNTED=${I_MOUNTED:-"no"}
211     if [ ! -f /lib/modules/$(uname -r)/kernel/fs/lustre/mds.ko -a \
212         ! -f `dirname $0`/../mds/mds.ko ]; then
213         export CLIENTMODSONLY=yes
214     fi
215
216     # command line
217
218     while getopts "rvwf:" opt $*; do
219         case $opt in
220             f) CONFIG=$OPTARG;;
221             r) REFORMAT=--reformat;;
222             v) VERBOSE=true;;
223             w) WRITECONF=writeconf;;
224             \?) usage;;
225         esac
226     done
227
228     shift $((OPTIND - 1))
229     ONLY=${ONLY:-$*}
230
231     [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
232     rm -f $TMP/*active
233 }
234
235 case `uname -r` in
236 2.4.*) EXT=".o"; USE_QUOTA=no; [ ! "$CLIENTONLY" ] && FSTYPE=ext3;;
237     *) EXT=".ko"; USE_QUOTA=yes;;
238 esac
239
240
241 module_loaded () {
242    /sbin/lsmod | grep -q $1
243 }
244
245 # Load a module on the system where this is running.
246 #
247 # Synopsis: load_module module_name [module arguments for insmod/modprobe]
248 #
249 # If module arguments are not given but MODOPTS_<MODULE> is set, then its value
250 # will be used as the arguments.  Otherwise arguments will be obtained from
251 # /etc/modprobe.conf, from /etc/modprobe.d/Lustre, or else none will be used.
252 #
253 load_module() {
254     local optvar
255     EXT=".ko"
256     module=$1
257     shift
258     BASE=`basename $module $EXT`
259
260     # If no module arguments were passed, get them from $MODOPTS_<MODULE>, else from
261     # modprobe.conf
262     if [ $# -eq 0 ]; then
263         # $MODOPTS_<MODULE>; we could use associative arrays, but that's not in
264         # Bash until 4.x, so we resort to eval.
265         optvar="MODOPTS_$(basename $module | tr a-z A-Z)"
266         eval set -- \$$optvar
267         if [ $# -eq 0 -a -n "$MODPROBECONF" ]; then
268             # Nothing in $MODOPTS_<MODULE>; try modprobe.conf
269             set -- $(grep "^options\\s*\<${module}\>" $MODPROBECONF)
270             # Get rid of "options $module"
271             (($# > 0)) && shift 2
272
273             # Ensure we have accept=all for lnet
274             if [ $module = lnet ]; then
275                 # OK, this is a bit wordy...
276                 local arg accept_all_present=false
277                 for arg in "$@"; do
278                     [ "$arg" = accept=all ] && accept_all_present=true
279                 done
280                 $accept_all_present || set -- "$@" accept=all
281             fi
282         fi
283     fi
284
285     [ $# -gt 0 ] && echo "${module} options: '$*'"
286
287     module_loaded ${BASE} && return
288
289     # Note that insmod will ignore anything in modprobe.conf, which is why we're
290     # passing options on the command-line.
291     if [ "$BASE" == "lnet_selftest" ] && \
292             [ -f ${LUSTRE}/../lnet/selftest/${module}${EXT} ]; then
293         insmod ${LUSTRE}/../lnet/selftest/${module}${EXT}
294     elif [ -f ${LUSTRE}/${module}${EXT} ]; then
295         insmod ${LUSTRE}/${module}${EXT} "$@"
296     else
297         # must be testing a "make install" or "rpm" installation
298         # note failed to load ptlrpc_gss is considered not fatal
299         if [ "$BASE" == "ptlrpc_gss" ]; then
300             modprobe $BASE "$@" 2>/dev/null || echo "gss/krb5 is not supported"
301         else
302             modprobe $BASE "$@"
303         fi
304     fi
305 }
306
307 load_modules_local() {
308     if [ -n "$MODPROBE" ]; then
309         # use modprobe
310         echo "Using modprobe to load modules"
311         return 0
312     fi
313     if [ "$HAVE_MODULES" = true ]; then
314         # we already loaded
315         echo "Modules already loaded"
316         return 0
317     fi
318     HAVE_MODULES=true
319
320     echo Loading modules from $LUSTRE
321     load_module ../libcfs/libcfs/libcfs
322     [ "$PTLDEBUG" ] && lctl set_param debug="$PTLDEBUG"
323     [ "$SUBSYSTEM" ] && lctl set_param subsystem_debug="${SUBSYSTEM# }"
324     load_module ../lnet/lnet/lnet
325     LNETLND=${LNETLND:-"socklnd/ksocklnd"}
326     load_module ../lnet/klnds/$LNETLND
327     load_module lvfs/lvfs
328     load_module obdclass/obdclass
329     load_module ptlrpc/ptlrpc
330     load_module ptlrpc/gss/ptlrpc_gss
331     [ "$USE_QUOTA" = "yes" -a "$LQUOTA" != "no" ] && load_module quota/lquota
332     load_module fld/fld
333     load_module fid/fid
334     load_module lmv/lmv
335     load_module mdc/mdc
336     load_module osc/osc
337     load_module lov/lov
338     load_module mgc/mgc
339     if ! client_only; then
340         grep -q crc16 /proc/kallsyms || { modprobe crc16 2>/dev/null || true; }
341         grep -q jbd /proc/kallsyms || { modprobe jbd 2>/dev/null || true; }
342         [ "$FSTYPE" = "ldiskfs" ] && load_module ../ldiskfs/ldiskfs/ldiskfs
343         load_module mgs/mgs
344         load_module mds/mds
345         load_module mdd/mdd
346         load_module mdt/mdt
347         load_module lvfs/fsfilt_$FSTYPE
348         load_module cmm/cmm
349         load_module osd/osd
350         load_module ost/ost
351         load_module obdfilter/obdfilter
352     fi
353
354     load_module llite/lustre
355     load_module llite/llite_lloop
356     [ -d /r ] && OGDB=${OGDB:-"/r/tmp"}
357     OGDB=${OGDB:-$TMP}
358     rm -f $OGDB/ogdb-$HOSTNAME
359     $LCTL modules > $OGDB/ogdb-$HOSTNAME
360
361     # 'mount' doesn't look in $PATH, just sbin
362     [ -f $LUSTRE/utils/mount.lustre ] && cp $LUSTRE/utils/mount.lustre /sbin/. || true
363 }
364
365 load_modules () {
366     load_modules_local
367     # bug 19124
368     # load modules on remote nodes optionally
369     # lustre-tests have to be installed on these nodes
370     if $LOAD_MODULES_REMOTE ; then
371         local list=$(comma_list $(remote_nodes_list))
372         echo loading modules on $list
373         do_rpc_nodes $list load_modules 
374     fi
375 }
376
377 check_mem_leak () {
378     LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
379     LEAK_PORTALS=$(dmesg | tail -n 20 | grep "Portals memory leaked" || true)
380     if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
381         echo "$LEAK_LUSTRE" 1>&2
382         echo "$LEAK_PORTALS" 1>&2
383         mv $TMP/debug $TMP/debug-leak.`date +%s` || true
384         echo "Memory leaks detected"
385         [ -n "$IGNORE_LEAK" ] && { echo "ignoring leaks" && return 0; } || true
386         return 1
387     fi
388 }
389
390 unload_modules() {
391     wait_exit_ST client # bug 12845
392
393     $LUSTRE_RMMOD $FSTYPE || return 2
394
395     if $LOAD_MODULES_REMOTE ; then
396         local list=$(comma_list $(remote_nodes_list))
397         if [ ! -z $list ]; then
398             echo unloading modules on $list
399             do_rpc_nodes $list $LUSTRE_RMMOD $FSTYPE
400             do_rpc_nodes $list check_mem_leak
401         fi
402     fi
403
404     HAVE_MODULES=false
405
406     check_mem_leak || return 254
407
408     echo "modules unloaded."
409     return 0
410 }
411
412 check_gss_daemon_nodes() {
413     local list=$1
414     dname=$2
415
416     do_nodesv $list "num=\\\$(ps -o cmd -C $dname | grep $dname | wc -l);
417 if [ \\\"\\\$num\\\" -ne 1 ]; then
418     echo \\\$num instance of $dname;
419     exit 1;
420 fi; "
421 }
422
423 check_gss_daemon_facet() {
424     facet=$1
425     dname=$2
426
427     num=`do_facet $facet ps -o cmd -C $dname | grep $dname | wc -l`
428     if [ $num -ne 1 ]; then
429         echo "$num instance of $dname on $facet"
430         return 1
431     fi
432     return 0
433 }
434
435 send_sigint() {
436     local list=$1
437     shift
438     echo Stopping $@ on $list
439     do_nodes $list "killall -2 $@ 2>/dev/null || true"
440 }
441
442 # start gss daemons on all nodes, or
443 # "daemon" on "list" if set
444 start_gss_daemons() {
445     local list=$1
446     local daemon=$2
447
448     if [ "$list" ] && [ "$daemon" ] ; then
449         echo "Starting gss daemon on nodes: $list"
450         do_nodes $list "$daemon" || return 8
451         return 0
452     fi
453
454     local list=$(comma_list $(mdts_nodes))
455
456     echo "Starting gss daemon on mds: $list"
457     do_nodes $list "$LSVCGSSD -v" || return 1
458     if $GSS_PIPEFS; then
459         do_nodes $list "$LGSSD -v" || return 2
460     fi
461
462     list=$(comma_list $(osts_nodes))
463     echo "Starting gss daemon on ost: $list"
464     do_nodes $list "$LSVCGSSD -v" || return 3
465     # starting on clients
466
467     local clients=${CLIENTS:-`hostname`}
468     if $GSS_PIPEFS; then
469         echo "Starting $LGSSD on clients $clients "
470         do_nodes $clients  "$LGSSD -v" || return 4
471     fi
472
473     # wait daemons entering "stable" status
474     sleep 5
475
476     #
477     # check daemons are running
478     #
479     list=$(comma_list $(mdts_nodes) $(osts_nodes))
480     check_gss_daemon_nodes $list lsvcgssd || return 5
481     if $GSS_PIPEFS; then
482         list=$(comma_list $(mdts_nodes))
483         check_gss_daemon_nodes $list lgssd || return 6
484     fi
485     if $GSS_PIPEFS; then
486         check_gss_daemon_nodes $clients lgssd || return 7
487     fi
488 }
489
490 stop_gss_daemons() {
491     local list=$(comma_list $(mdts_nodes))
492     
493     send_sigint $list lsvcgssd lgssd
494
495     list=$(comma_list $(osts_nodes))
496     send_sigint $list lsvcgssd
497
498     list=${CLIENTS:-`hostname`}
499     send_sigint $list lgssd
500 }
501
502 init_gss() {
503     if $GSS; then
504         if ! module_loaded ptlrpc_gss; then
505             load_module ptlrpc/gss/ptlrpc_gss
506             module_loaded ptlrpc_gss ||
507                 error_exit "init_gss : GSS=$GSS, but gss/krb5 is not supported!"
508         fi
509         start_gss_daemons || error_exit "start gss daemon failed! rc=$?"
510
511         if [ -n "$LGSS_KEYRING_DEBUG" ]; then
512             echo $LGSS_KEYRING_DEBUG > /proc/fs/lustre/sptlrpc/gss/lgss_keyring/debug_level
513         fi
514     fi
515 }
516
517 cleanup_gss() {
518     if $GSS; then
519         stop_gss_daemons
520         # maybe cleanup credential cache?
521     fi
522 }
523
524 mdsdevlabel() {
525     local num=$1
526     local device=`mdsdevname $num`
527     local label=`do_facet mds$num "e2label ${device}" | grep -v "CMD: "`
528     echo -n $label
529 }
530
531 ostdevlabel() {
532     local num=$1
533     local device=`ostdevname $num`
534     local label=`do_facet ost$num "e2label ${device}" | grep -v "CMD: "`
535     echo -n $label
536 }
537
538 # Facet functions
539 mount_facet() {
540     local facet=$1
541     shift
542     local dev=$(facet_active $facet)_dev
543     local opt=${facet}_opt
544     echo "Starting ${facet}: ${!opt} $@ ${!dev} ${MOUNT%/*}/${facet}"
545     do_facet ${facet} mount -t lustre ${!opt} $@ ${!dev} ${MOUNT%/*}/${facet}
546     RC=${PIPESTATUS[0]}
547     if [ $RC -ne 0 ]; then
548         echo "mount -t lustre $@ ${!dev} ${MOUNT%/*}/${facet}"
549         echo "Start of ${!dev} on ${facet} failed ${RC}"
550     else
551         do_facet ${facet} "lctl set_param debug=\\\"$PTLDEBUG\\\"; \
552             lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\"; \
553             lctl set_param debug_mb=${DEBUG_SIZE}; \
554             sync"
555
556         label=$(do_facet ${facet} "$E2LABEL ${!dev}")
557         [ -z "$label" ] && echo no label for ${!dev} && exit 1
558         eval export ${facet}_svc=${label}
559         echo Started ${label}
560     fi
561     return $RC
562 }
563
564 # start facet device options
565 start() {
566     local facet=$1
567     shift
568     local device=$1
569     shift
570     eval export ${facet}_dev=${device}
571     eval export ${facet}_opt=\"$@\"
572
573     local varname=${facet}failover_dev
574     if [ -n "${!varname}" ] ; then
575         eval export ${facet}failover_dev=${!varname}
576     else
577         eval export ${facet}failover_dev=$device
578     fi
579
580     do_facet ${facet} mkdir -p ${MOUNT%/*}/${facet}
581     mount_facet ${facet}
582     RC=$?
583     return $RC
584 }
585
586 stop() {
587     local running
588     local facet=$1
589     shift
590     HOST=`facet_active_host $facet`
591     [ -z $HOST ] && echo stop: no host for $facet && return 0
592
593     running=$(do_facet ${facet} "grep -c ${MOUNT%/*}/${facet}' ' /proc/mounts") || true
594     if [ ${running} -ne 0 ]; then
595         echo "Stopping ${MOUNT%/*}/${facet} (opts:$@)"
596         do_facet ${facet} umount -d $@ ${MOUNT%/*}/${facet}
597     fi
598
599     # umount should block, but we should wait for unrelated obd's
600     # like the MGS or MGC to also stop.
601     wait_exit_ST ${facet}
602 }
603
604 # save quota version (both administrative and operational quotas)
605 # add an additional parameter if mountpoint is ever different from $MOUNT
606 quota_save_version() {
607     local fsname=${2:-$FSNAME}
608     local spec=$1
609     local ver=$(tr -c -d "123" <<< $spec)
610     local type=$(tr -c -d "ug" <<< $spec)
611
612     [ -n "$ver" -a "$ver" != "3" ] && error "wrong quota version specifier"
613
614     [ -n "$type" ] && { $LFS quotacheck -$type $MOUNT || error "quotacheck has failed"; }
615
616     do_facet mgs "lctl conf_param ${fsname}-MDT*.mdd.quota_type=$spec"
617     local varsvc
618     local osts=$(get_facets OST)
619     for ost in ${osts//,/ }; do
620         varsvc=${ost}_svc
621         do_facet mgs "lctl conf_param ${!varsvc}.ost.quota_type=$spec"
622     done
623 }
624
625 # client could mount several lustre 
626 quota_type () {
627     local fsname=${1:-$FSNAME}
628     local rc=0
629     do_facet mgs lctl get_param mdd.${fsname}-MDT*.quota_type || rc=$?
630     do_nodes $(comma_list $(osts_nodes)) \
631         lctl get_param obdfilter.${fsname}-OST*.quota_type || rc=$?
632     return $rc 
633 }
634
635 restore_quota_type () {
636    local mntpt=${1:-$MOUNT}
637    local quota_type=$(quota_type $FSNAME | grep MDT | cut -d "=" -f2)
638    if [ ! "$old_QUOTA_TYPE" ] || [ "$quota_type" = "$old_QUOTA_TYPE" ]; then
639         return
640    fi
641    quota_save_version $old_QUOTA_TYPE
642 }
643
644 setup_quota(){
645     local mntpt=$1
646
647     # We need save the original quota_type params, and restore them after testing
648
649     # Suppose that quota type the same on mds and ost
650     local quota_type=$(quota_type | grep MDT | cut -d "=" -f2)
651     [ ${PIPESTATUS[0]} -eq 0 ] || error "quota_type failed!"
652     echo "[HOST:$HOSTNAME] [old_quota_type:$quota_type] [new_quota_type:$QUOTA_TYPE]"
653     if [ "$quota_type" != "$QUOTA_TYPE" ]; then
654         export old_QUOTA_TYPE=$quota_type
655         quota_save_version $QUOTA_TYPE
656     else
657         qtype=$(tr -c -d "ug" <<< $QUOTA_TYPE)
658         $LFS quotacheck -$qtype $mntpt || error "quotacheck has failed for $type"
659     fi
660
661     local quota_usrs=$QUOTA_USERS
662
663     # get_filesystem_size
664     local disksz=$(lfs df $mntpt | grep "filesystem summary:"  | awk '{print $3}')
665     local blk_soft=$((disksz + 1024))
666     local blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over
667
668     local Inodes=$(lfs df -i $mntpt | grep "filesystem summary:"  | awk '{print $3}')
669     local i_soft=$Inodes
670     local i_hard=$((i_soft + i_soft / 20))
671
672     echo "Total disk size: $disksz  block-softlimit: $blk_soft block-hardlimit:
673         $blk_hard inode-softlimit: $i_soft inode-hardlimit: $i_hard"
674
675     local cmd
676     for usr in $quota_usrs; do
677         echo "Setting up quota on $HOSTNAME:$mntpt for $usr..."
678         for type in u g; do
679             cmd="$LFS setquota -$type $usr -b $blk_soft -B $blk_hard -i $i_soft -I $i_hard $mntpt"
680             echo "+ $cmd"
681             eval $cmd || error "$cmd FAILED!"
682         done
683         # display the quota status
684         echo "Quota settings for $usr : "
685         $LFS quota -v -u $usr $mntpt || true
686     done
687 }
688
689 zconf_mount() {
690     local OPTIONS
691     local client=$1
692     local mnt=$2
693     # Only supply -o to mount if we have options
694     if [ -n "$MOUNTOPT" ]; then
695         OPTIONS="-o $MOUNTOPT"
696     fi
697     local device=$MGSNID:/$FSNAME
698     if [ -z "$mnt" -o -z "$FSNAME" ]; then
699         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
700         exit 1
701     fi
702
703     echo "Starting client: $client: $OPTIONS $device $mnt"
704     do_node $client mkdir -p $mnt
705     do_node $client mount -t lustre $OPTIONS $device $mnt || return 1
706
707     do_node $client "lctl set_param debug=\\\"$PTLDEBUG\\\";
708         lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
709         lctl set_param debug_mb=${DEBUG_SIZE}"
710
711     return 0
712 }
713
714 zconf_umount() {
715     local client=$1
716     local mnt=$2
717     local force
718     local busy 
719     local need_kill
720
721     [ "$3" ] && force=-f
722     local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
723     if [ $running -ne 0 ]; then
724         echo "Stopping client $client $mnt (opts:$force)"
725         do_node $client lsof -t $mnt || need_kill=no
726         if [ "x$force" != "x" -a "x$need_kill" != "xno" ]; then
727             pids=$(do_node $client lsof -t $mnt | sort -u);
728             if [ -n $pids ]; then
729                 do_node $client kill -9 $pids || true
730             fi
731         fi
732
733         busy=$(do_node $client "umount $force $mnt 2>&1" | grep -c "busy") || true
734         if [ $busy -ne 0 ] ; then
735             echo "$mnt is still busy, wait one second" && sleep 1
736             do_node $client umount $force $mnt
737         fi
738     fi
739 }
740
741 # nodes is comma list
742 sanity_mount_check_nodes () {
743     local nodes=$1
744     shift
745     local mnts="$@"
746     local mnt
747
748     # FIXME: assume that all cluster nodes run the same os
749     [ "$(uname)" = Linux ] || return 0
750
751     local rc=0
752     for mnt in $mnts ; do
753         do_nodes $nodes "running=\\\$(grep -c $mnt' ' /proc/mounts);
754 mpts=\\\$(mount | grep -w -c $mnt);
755 if [ \\\$running -ne \\\$mpts ]; then
756     echo \\\$(hostname) env are INSANE!;
757     exit 1;
758 fi"
759     [ $? -eq 0 ] || rc=1 
760     done
761     return $rc
762 }
763
764 sanity_mount_check_servers () {
765     [ "$CLIENTONLY" ] && 
766         { echo "CLIENTONLY mode, skip mount_check_servers"; return 0; } || true
767     echo Checking servers environments
768
769     # FIXME: modify get_facets to display all facets wo params
770     local facets="$(get_facets OST),$(get_facets MDS),mgs"
771     local node
772     local mnt
773     local facet
774     for facet in ${facets//,/ }; do
775         node=$(facet_host ${facet})
776         mnt=${MOUNT%/*}/${facet}
777         sanity_mount_check_nodes $node $mnt ||
778             { error "server $node environments are insane!"; return 1; }
779     done
780 }
781
782 sanity_mount_check_clients () {
783     local clients=${1:-$CLIENTS}
784     local mntpt=${2:-$MOUNT}
785     local mntpt2=${3:-$MOUNT2}
786
787     [ -z $clients ] && clients=$(hostname)
788     echo Checking clients $clients environments
789
790     sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
791        error "clients environments are insane!"
792 }
793
794 sanity_mount_check () {
795     sanity_mount_check_servers || return 1
796     sanity_mount_check_clients || return 2
797 }
798
799 # mount clients if not mouted
800 zconf_mount_clients() {
801     local clients=$1
802     local mnt=$2
803     local OPTIONS=${3:-$MOUNTOPT}
804
805     # Only supply -o to mount if we have options
806     if [ "$OPTIONS" ]; then
807         OPTIONS="-o $OPTIONS"
808     fi
809     local device=$MGSNID:/$FSNAME
810     if [ -z "$mnt" -o -z "$FSNAME" ]; then
811         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
812         exit 1
813     fi
814
815     echo "Starting client $clients: $OPTIONS $device $mnt"
816
817     do_nodes $clients "
818 running=\\\$(mount | grep -c $mnt' ');
819 rc=0;
820 if [ \\\$running -eq 0 ] ; then
821     mkdir -p $mnt;
822     mount -t lustre $OPTIONS $device $mnt;
823     rc=\\\$?;
824 fi;
825 exit \\\$rc" || return ${PIPESTATUS[0]}
826
827     echo "Started clients $clients: "
828     do_nodes $clients "mount | grep -w $mnt"
829
830     do_nodes $clients "lctl set_param debug=\\\"$PTLDEBUG\\\";
831         lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
832         lctl set_param debug_mb=${DEBUG_SIZE};"
833
834     return 0
835 }
836
837 zconf_umount_clients() {
838     local clients=$1
839     local mnt=$2
840     local force
841
842     [ "$3" ] && force=-f
843
844     echo "Stopping clients: $clients $mnt (opts:$force)"
845     do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
846 if [ \\\$running -ne 0 ] ; then
847 echo Stopping client \\\$(hostname) $mnt opts:$force;
848 lsof -t $mnt || need_kill=no;
849 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
850     pids=\\\$(lsof -t $mnt | sort -u);
851     if [ -n \\\"\\\$pids\\\" ]; then
852              kill -9 \\\$pids;
853     fi
854 fi;
855 busy=\\\$(umount $force $mnt 2>&1 | grep -c "busy");
856 if [ \\\$busy -ne 0 ] ; then
857     echo "$mnt is still busy, wait one second" && sleep 1;
858     umount $force $mnt;
859 fi
860 fi"
861 }
862
863 shudown_node_hard () {
864     local host=$1
865     local attempts=3
866
867     for i in $(seq $attempts) ; do
868         $POWER_DOWN $host
869         sleep 1
870         ping -w 3 -c 1 $host > /dev/null 2>&1 || return 0
871         echo "waiting for $host to fail attempts=$attempts"
872         [ $i -lt $attempts ] || \
873             { echo "$host still pingable after power down! attempts=$attempts" && return 1; } 
874     done
875 }
876
877 shutdown_client() {
878     local client=$1
879     local mnt=${2:-$MOUNT}
880     local attempts=3
881
882     if [ "$FAILURE_MODE" = HARD ]; then
883         shudown_node_hard $client 
884     else
885        zconf_umount_clients $client $mnt -f
886     fi
887 }
888
889 shutdown_facet() {
890     local facet=$1
891     if [ "$FAILURE_MODE" = HARD ]; then
892         shudown_node_hard $(facet_active_host $facet)
893     elif [ "$FAILURE_MODE" = SOFT ]; then
894         stop $facet
895     fi
896 }
897
898 reboot_facet() {
899     facet=$1
900     if [ "$FAILURE_MODE" = HARD ]; then
901         $POWER_UP `facet_active_host $facet`
902     else
903         sleep 10
904     fi
905 }
906
907 boot_node() {
908     local node=$1
909     if [ "$FAILURE_MODE" = HARD ]; then
910        $POWER_UP $node
911        wait_for_host $node
912     fi
913 }
914
915 # recovery-scale functions
916 check_progs_installed () {
917     local clients=$1
918     shift
919     local progs=$@
920
921     do_nodes $clients "PATH=:$PATH; status=true;
922 for prog in $progs; do
923     if ! [ \\\"\\\$(which \\\$prog)\\\"  -o  \\\"\\\${!prog}\\\" ]; then
924        echo \\\$prog missing on \\\$(hostname);
925        status=false;
926     fi
927 done;
928 eval \\\$status"
929 }
930
931 client_var_name() {
932     echo __$(echo $1 | tr '-' 'X')
933 }
934
935 start_client_load() {
936     local client=$1
937     local load=$2
938     local var=$(client_var_name $client)_load
939     eval export ${var}=$load
940
941     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
942                               BREAK_ON_ERROR=$BREAK_ON_ERROR \
943                               END_RUN_FILE=$END_RUN_FILE \
944                               LOAD_PID_FILE=$LOAD_PID_FILE \
945                               TESTSUITELOG=$TESTSUITELOG \
946                               run_${load}.sh" &
947     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $!"
948     log "Started client load: ${load} on $client"
949
950     return 0
951 }
952
953 start_client_loads () {
954     local -a clients=(${1//,/ })
955     local numloads=${#CLIENT_LOADS[@]}
956     local testnum
957
958     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
959         testnum=$((nodenum % numloads))
960         start_client_load ${clients[nodenum]} ${CLIENT_LOADS[testnum]}
961     done
962     # bug 22169: wait the background threads to start
963     sleep 2
964 }
965
966 # only for remote client 
967 check_client_load () {
968     local client=$1
969     local var=$(client_var_name $client)_load
970     local TESTLOAD=run_${!var}.sh
971
972     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
973     
974     # bug 18914: try to connect several times not only when
975     # check ps, but  while check_catastrophe also
976     local tries=3
977     local RC=254
978     while [ $RC = 254 -a $tries -gt 0 ]; do
979         let tries=$tries-1
980         # assume success
981         RC=0
982         if ! check_catastrophe $client; then
983             RC=${PIPESTATUS[0]}
984             if [ $RC -eq 254 ]; then
985                 # FIXME: not sure how long we shuold sleep here
986                 sleep 10
987                 continue
988             fi
989             echo "check catastrophe failed: RC=$RC "
990             return $RC
991         fi
992     done
993     # We can continue try to connect if RC=254
994     # Just print the warning about this
995     if [ $RC = 254 ]; then
996         echo "got a return status of $RC from do_node while checking catastrophe on $client"
997     fi
998
999     # see if the load is still on the client
1000     tries=3
1001     RC=254
1002     while [ $RC = 254 -a $tries -gt 0 ]; do
1003         let tries=$tries-1
1004         # assume success
1005         RC=0
1006         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
1007             RC=${PIPESTATUS[0]}
1008             sleep 30
1009         fi
1010     done
1011     if [ $RC = 254 ]; then
1012         echo "got a return status of $RC from do_node while checking (catastrophe and 'ps') the client load on $client"
1013         # see if we can diagnose a bit why this is
1014     fi
1015
1016     return $RC
1017 }
1018 check_client_loads () {
1019    local clients=${1//,/ }
1020    local client=
1021    local rc=0
1022
1023    for client in $clients; do
1024       check_client_load $client
1025       rc=${PIPESTATUS[0]}
1026       if [ "$rc" != 0 ]; then
1027         log "Client load failed on node $client, rc=$rc"
1028         return $rc
1029       fi
1030    done
1031 }
1032
1033 restart_client_loads () {
1034     local clients=${1//,/ }
1035     local expectedfail=${2:-""}
1036     local client=
1037     local rc=0
1038
1039     for client in $clients; do
1040         check_client_load $client
1041         rc=${PIPESTATUS[0]}
1042         if [ "$rc" != 0 -a "$expectedfail" ]; then
1043             local var=$(client_var_name $client)_load
1044             start_client_load $client ${!var}
1045             echo "Restarted client load ${!var}: on $client. Checking ..."
1046             check_client_load $client
1047             rc=${PIPESTATUS[0]}
1048             if [ "$rc" != 0 ]; then
1049                 log "Client load failed to restart on node $client, rc=$rc"
1050                 # failure one client load means test fail
1051                 # we do not need to check other 
1052                 return $rc
1053             fi
1054         else
1055             return $rc
1056         fi
1057     done
1058 }
1059 # End recovery-scale functions
1060
1061 # verify that lustre actually cleaned up properly
1062 cleanup_check() {
1063     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
1064         error "LBUG/LASSERT detected"
1065     BUSY=`dmesg | grep -i destruct || true`
1066     if [ "$BUSY" ]; then
1067         echo "$BUSY" 1>&2
1068         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
1069         exit 205
1070     fi
1071
1072     check_mem_leak || exit 204
1073
1074     [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl && \
1075         echo "$0: lustre didn't clean up..." 1>&2 && return 202 || true
1076
1077     if module_loaded lnet || module_loaded libcfs; then
1078         echo "$0: modules still loaded..." 1>&2
1079         /sbin/lsmod 1>&2
1080         return 203
1081     fi
1082     return 0
1083 }
1084
1085 wait_update () {
1086     local node=$1
1087     local TEST=$2
1088     local FINAL=$3
1089     local MAX=${4:-90}
1090
1091         local RESULT
1092         local WAIT=0
1093         local sleep=5
1094         while [ true ]; do
1095             RESULT=$(do_node $node "$TEST")
1096             if [ "$RESULT" == "$FINAL" ]; then
1097                 echo "Updated after $WAIT sec: wanted '$FINAL' got '$RESULT'"
1098                 return 0
1099             fi
1100             [ $WAIT -ge $MAX ] && break
1101             echo "Waiting $((MAX - WAIT)) secs for update"
1102             WAIT=$((WAIT + sleep))
1103             sleep $sleep
1104         done
1105         echo "Update not seen after $MAX sec: wanted '$FINAL' got '$RESULT'"
1106         return 3
1107 }
1108
1109 wait_update_facet () {
1110     local facet=$1
1111     wait_update  $(facet_active_host $facet) "$@"
1112 }
1113
1114 wait_delete_completed () {
1115     local TOTALPREV=`lctl get_param -n osc.*.kbytesavail | \
1116                      awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1117
1118     local WAIT=0
1119     local MAX_WAIT=20
1120     while [ "$WAIT" -ne "$MAX_WAIT" ]; do
1121         sleep 1
1122         TOTAL=`lctl get_param -n osc.*.kbytesavail | \
1123                awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
1124         [ "$TOTAL" -eq "$TOTALPREV" ] && return 0
1125         echo "Waiting delete completed ... prev: $TOTALPREV current: $TOTAL "
1126         TOTALPREV=$TOTAL
1127         WAIT=$(( WAIT + 1))
1128     done
1129     echo "Delete is not completed in $MAX_WAIT sec"
1130     return 1
1131 }
1132
1133 wait_for_host() {
1134     local host=$1
1135     check_network "$host" 900
1136     while ! do_node $host hostname  > /dev/null; do sleep 5; done
1137 }
1138
1139 wait_for() {
1140     local facet=$1
1141     local host=`facet_active_host $facet`
1142     wait_for_host $host
1143 }
1144
1145 wait_recovery_complete () {
1146     local facet=$1
1147
1148     # Use default policy if $2 is not passed by caller.
1149     #define OBD_RECOVERY_TIMEOUT (obd_timeout * 5 / 2)
1150     # as we are in process of changing obd_timeout in different ways
1151     # let's set MAX longer than that
1152     local MAX=${2:-$(( TIMEOUT * 4 ))}
1153
1154     local var_svc=${facet}_svc
1155     local procfile="*.${!var_svc}.recovery_status"
1156     local WAIT=0
1157     local STATUS=
1158
1159     while [ $WAIT -lt $MAX ]; do
1160         STATUS=$(do_facet $facet lctl get_param -n $procfile | grep status)
1161         [[ $STATUS = "status: COMPLETE" ]] && return 0
1162         sleep 5
1163         WAIT=$((WAIT + 5))
1164         echo "Waiting $((MAX - WAIT)) secs for $facet recovery done. $STATUS"
1165     done
1166     echo "$facet recovery not done in $MAX sec. $STATUS"
1167     return 1
1168 }
1169
1170 wait_mds_ost_sync () {
1171     # just because recovery is done doesn't mean we've finished
1172     # orphan cleanup. Wait for llogs to get synchronized.
1173     echo "Waiting for orphan cleanup..."
1174     # MAX value includes time needed for MDS-OST reconnection
1175     local MAX=$(( TIMEOUT * 2 ))
1176     local WAIT=0
1177     while [ $WAIT -lt $MAX ]; do
1178         local -a sync=($(do_nodes $(comma_list $(osts_nodes)) \
1179             "$LCTL get_param -n obdfilter.*.mds_sync"))
1180         local con=1
1181         for ((i=0; i<${#sync[@]}; i++)); do
1182             [ ${sync[$i]} -eq 0 ] && continue
1183             # there is a not finished MDS-OST synchronization
1184             con=0
1185             break;
1186         done
1187         sleep 2 # increase waiting time and cover statfs cache
1188         [ ${con} -eq 1 ] && return 0
1189         echo "Waiting $WAIT secs for $facet mds-ost sync done."
1190         WAIT=$((WAIT + 2))
1191     done
1192     echo "$facet recovery not done in $MAX sec. $STATUS"
1193     return 1
1194 }
1195
1196 wait_destroy_complete () {
1197     echo "Waiting for destroy to be done..."
1198     # MAX value shouldn't be big as this mean server responsiveness
1199     # never increase this just to make test pass but investigate
1200     # why it takes so long time
1201     local MAX=5
1202     local WAIT=0
1203     while [ $WAIT -lt $MAX ]; do
1204         local -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))
1205         local con=1
1206         for ((i=0; i<${#RPCs[@]}; i++)); do
1207             [ ${RPCs[$i]} -eq 0 ] && continue
1208             # there are still some destroy RPCs in flight
1209             con=0
1210             break;
1211         done
1212         sleep 1
1213         [ ${con} -eq 1 ] && return 0 # done waiting
1214         echo "Waiting $WAIT secs for destroys to be done."
1215         WAIT=$((WAIT + 1))
1216     done
1217     echo "Destroys weren't done in $MAX sec."
1218     return 1
1219 }
1220
1221 wait_exit_ST () {
1222     local facet=$1
1223
1224     local WAIT=0
1225     local INTERVAL=1
1226     local running
1227     # conf-sanity 31 takes a long time cleanup
1228     while [ $WAIT -lt 300 ]; do
1229         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
1230         [ -z "${running}" ] && return 0
1231         echo "waited $WAIT for${running}"
1232         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
1233         sleep $INTERVAL
1234         WAIT=$((WAIT + INTERVAL))
1235     done
1236     echo "service didn't stop after $WAIT seconds.  Still running:"
1237     echo ${running}
1238     return 1
1239 }
1240
1241 wait_remote_prog () {
1242    local prog=$1
1243    local WAIT=0
1244    local INTERVAL=5
1245    local rc=0
1246
1247    [ "$PDSH" = "no_dsh" ] && return 0
1248
1249    while [ $WAIT -lt $2 ]; do
1250         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
1251         [ -z "${running}" ] && return 0 || true
1252         echo "waited $WAIT for: "
1253         echo "$running"
1254         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
1255         sleep $INTERVAL
1256         WAIT=$((WAIT + INTERVAL))
1257     done
1258     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
1259     [ -z "$pids" ] && return 0
1260     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
1261     # FIXME: not portable
1262     for pid in $pids; do
1263         cat /proc/${pid}/status || true
1264         cat /proc/${pid}/wchan || true
1265         echo "Killing $pid"
1266         kill -9 $pid || true
1267         sleep 1
1268         ps -P $pid && rc=1
1269     done
1270
1271     return $rc
1272 }
1273
1274 clients_up() {
1275     # not every config has many clients
1276     sleep 1
1277     if [ ! -z "$CLIENTS" ]; then
1278         $PDSH $CLIENTS "stat -f $MOUNT" > /dev/null
1279     else
1280         stat -f $MOUNT > /dev/null
1281     fi
1282 }
1283
1284 client_up() {
1285     local client=$1
1286     # usually checked on particular client or locally
1287     sleep 1
1288     if [ ! -z "$client" ]; then
1289         $PDSH $client "stat -f $MOUNT" > /dev/null
1290     else
1291         stat -f $MOUNT > /dev/null
1292     fi
1293 }
1294
1295 client_evicted() {
1296     ! client_up $1
1297 }
1298
1299 client_reconnect() {
1300     uname -n >> $MOUNT/recon
1301     if [ -z "$CLIENTS" ]; then
1302         df $MOUNT; uname -n >> $MOUNT/recon
1303     else
1304         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
1305     fi
1306     echo Connected clients:
1307     cat $MOUNT/recon
1308     ls -l $MOUNT/recon > /dev/null
1309     rm $MOUNT/recon
1310 }
1311
1312 facet_failover() {
1313     local facet=$1
1314     local sleep_time=$2
1315     echo "Failing $facet on node `facet_active_host $facet`"
1316     shutdown_facet $facet
1317     [ -n "$sleep_time" ] && sleep $sleep_time
1318     reboot_facet $facet
1319     change_active $facet
1320     local TO=`facet_active_host $facet`
1321     echo "Failover $facet to $TO"
1322     wait_for $facet
1323     mount_facet $facet || error "Restart of $facet failed"
1324 }
1325
1326 obd_name() {
1327     local facet=$1
1328 }
1329
1330 replay_barrier() {
1331     local facet=$1
1332     do_facet $facet sync
1333     df $MOUNT
1334     local svc=${facet}_svc
1335     do_facet $facet $LCTL --device %${!svc} notransno
1336     do_facet $facet $LCTL --device %${!svc} readonly
1337     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1338     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1339 }
1340
1341 replay_barrier_nodf() {
1342     local facet=$1    echo running=${running}
1343     do_facet $facet sync
1344     local svc=${facet}_svc
1345     echo Replay barrier on ${!svc}
1346     do_facet $facet $LCTL --device %${!svc} notransno
1347     do_facet $facet $LCTL --device %${!svc} readonly
1348     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1349     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1350 }
1351
1352 replay_barrier_nosync() {
1353     local facet=$1    echo running=${running}
1354     local svc=${facet}_svc
1355     echo Replay barrier on ${!svc}
1356     do_facet $facet $LCTL --device %${!svc} notransno
1357     do_facet $facet $LCTL --device %${!svc} readonly
1358     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
1359     $LCTL mark "local REPLAY BARRIER on ${!svc}"
1360 }
1361
1362 mds_evict_client() {
1363     UUID=`lctl get_param -n mdc.${mds1_svc}-mdc-*.uuid`
1364     do_facet mds1 "lctl set_param -n mdt.${mds1_svc}.evict_client $UUID"
1365 }
1366
1367 ost_evict_client() {
1368     UUID=`lctl get_param -n devices| grep ${ost1_svc}-osc- | egrep -v 'MDT' | awk '{print $5}'`
1369     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
1370 }
1371
1372 fail() {
1373     facet_failover $* || error "failover: $?"
1374     clients_up || error "post-failover df: $?"
1375 }
1376
1377 fail_nodf() {
1378         local facet=$1
1379         facet_failover $facet
1380 }
1381
1382 fail_abort() {
1383     local facet=$1
1384     stop $facet
1385     change_active $facet
1386     mount_facet $facet -o abort_recovery
1387     clients_up || echo "first df failed: $?"
1388     clients_up || error "post-failover df: $?"
1389 }
1390
1391 do_lmc() {
1392     echo There is no lmc.  This is mountconf, baby.
1393     exit 1
1394 }
1395
1396 h2gm () {
1397     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1398         ID=`$PDSH $1 $GMNALNID -l | cut -d\  -f2`
1399         echo $ID"@gm"
1400     fi
1401 }
1402
1403 h2name_or_ip() {
1404     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1405         echo $1"@$2"
1406     fi
1407 }
1408
1409 h2ptl() {
1410    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1411        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
1412        if [ -z "$ID" ]; then
1413            echo "Could not get a ptl id for $1..."
1414            exit 1
1415        fi
1416        echo $ID"@ptl"
1417    fi
1418 }
1419 declare -fx h2ptl
1420
1421 h2tcp() {
1422     h2name_or_ip "$1" "tcp"
1423 }
1424 declare -fx h2tcp
1425
1426 h2elan() {
1427     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
1428         if type __h2elan >/dev/null 2>&1; then
1429             ID=$(__h2elan $1)
1430         else
1431             ID=`echo $1 | sed 's/[^0-9]*//g'`
1432         fi
1433         echo $ID"@elan"
1434     fi
1435 }
1436 declare -fx h2elan
1437
1438 h2openib() {
1439     h2name_or_ip "$1" "openib"
1440 }
1441 declare -fx h2openib
1442
1443 h2o2ib() {
1444     h2name_or_ip "$1" "o2ib"
1445 }
1446 declare -fx h2o2ib
1447
1448 facet_host() {
1449     local facet=$1
1450
1451     [ "$facet" == client ] && echo -n $HOSTNAME && return
1452     varname=${facet}_HOST
1453     if [ -z "${!varname}" ]; then
1454         if [ "${facet:0:3}" == "ost" ]; then
1455             eval ${facet}_HOST=${ost_HOST}
1456         fi
1457     fi
1458     echo -n ${!varname}
1459 }
1460
1461 facet_active() {
1462     local facet=$1
1463     local activevar=${facet}active
1464
1465     if [ -f $TMP/${facet}active ] ; then
1466         source $TMP/${facet}active
1467     fi
1468
1469     active=${!activevar}
1470     if [ -z "$active" ] ; then
1471         echo -n ${facet}
1472     else
1473         echo -n ${active}
1474     fi
1475 }
1476
1477 facet_active_host() {
1478     local facet=$1
1479     local active=`facet_active $facet`
1480     if [ "$facet" == client ]; then
1481         echo $HOSTNAME
1482     else
1483         echo `facet_host $active`
1484     fi
1485 }
1486
1487 change_active() {
1488     local facet=$1
1489     local failover=${facet}failover
1490     host=`facet_host $failover`
1491     [ -z "$host" ] && return
1492     local curactive=`facet_active $facet`
1493     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
1494         eval export ${facet}active=$facet
1495     else
1496         eval export ${facet}active=$failover
1497     fi
1498     # save the active host for this facet
1499     local activevar=${facet}active
1500     echo "$activevar=${!activevar}" > $TMP/$activevar
1501 }
1502
1503 do_node() {
1504     local verbose=false
1505     # do not stripe off hostname if verbose, bug 19215
1506     if [ x$1 = x--verbose ]; then
1507         shift
1508         verbose=true
1509     fi
1510
1511     local HOST=$1
1512     shift
1513     local myPDSH=$PDSH
1514     if [ "$HOST" = "$HOSTNAME" ]; then
1515         myPDSH="no_dsh"
1516     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
1517         echo "cannot run remote command on $HOST with $myPDSH"
1518         return 128
1519     fi
1520     if $VERBOSE; then
1521         echo "CMD: $HOST $@" >&2
1522         $myPDSH $HOST $LCTL mark "$@" > /dev/null 2>&1 || :
1523     fi
1524
1525     if [ "$myPDSH" = "rsh" ]; then
1526 # we need this because rsh does not return exit code of an executed command
1527         local command_status="$TMP/cs"
1528         rsh $HOST ":> $command_status"
1529         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
1530                     cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\") ||
1531                     echo command failed >$command_status"
1532         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
1533         return 0
1534     fi
1535
1536     if $verbose ; then
1537         # print HOSTNAME for myPDSH="no_dsh"
1538         if [[ $myPDSH = no_dsh ]]; then
1539             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed -e "s/^/${HOSTNAME}: /"
1540         else
1541             $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")"
1542         fi
1543     else
1544         $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" sh -c \"$@\")" | sed "s/^${HOST}: //"
1545     fi
1546     return ${PIPESTATUS[0]}
1547 }
1548
1549 do_nodev() {
1550     do_node --verbose "$@"
1551 }
1552
1553 single_local_node () {
1554    [ "$1" = "$HOSTNAME" ]
1555 }
1556
1557 # Outputs environment variable assignments that should be passed to remote nodes
1558 get_env_vars() {
1559     local var
1560     local value
1561
1562     for var in ${!MODOPTS_*}; do
1563         value=${!var}
1564         echo "${var}=\"$value\""
1565     done
1566 }
1567
1568 do_nodes() {
1569     local verbose=false
1570     # do not stripe off hostname if verbose, bug 19215
1571     if [ x$1 = x--verbose ]; then
1572         shift
1573         verbose=true
1574     fi
1575
1576     local rnodes=$1
1577     shift
1578
1579     if single_local_node $rnodes; then
1580         if $verbose; then
1581            do_nodev $rnodes "$@"
1582         else
1583            do_node $rnodes "$@"
1584         fi
1585         return $?
1586     fi
1587
1588     # This is part from do_node
1589     local myPDSH=$PDSH
1590
1591     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
1592         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
1593
1594     if $VERBOSE; then
1595         echo "CMD: $rnodes $@" >&2
1596         $myPDSH $rnodes $LCTL mark "$@" > /dev/null 2>&1 || :
1597     fi
1598
1599     if $verbose ; then
1600         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")"
1601     else
1602         $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) sh -c \"$@\")" | sed -re "s/\w+:\s//g"
1603     fi
1604     return ${PIPESTATUS[0]}
1605 }
1606
1607 do_facet() {
1608     local facet=$1
1609     shift
1610     local HOST=`facet_active_host $facet`
1611     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
1612     do_node $HOST "$@"
1613 }
1614
1615 do_nodesv() {
1616     do_nodes --verbose "$@"
1617 }
1618
1619 add() {
1620     local facet=$1
1621     shift
1622     # make sure its not already running
1623     stop ${facet} -f
1624     rm -f $TMP/${facet}active
1625     do_facet ${facet} $MKFS $*
1626 }
1627
1628 ostdevname() {
1629     num=$1
1630     DEVNAME=OSTDEV$num
1631     #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
1632     eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}}
1633     echo -n $DEVPTR
1634 }
1635
1636 mdsdevname() {
1637     num=$1
1638     DEVNAME=MDSDEV$num
1639     #if $MDSDEVn isn't defined, default is $MDSDEVBASE + num
1640     eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}}
1641     echo -n $DEVPTR
1642 }
1643
1644 ########
1645 ## MountConf setup
1646
1647 stopall() {
1648     # make sure we are using the primary server, so test-framework will
1649     # be able to clean up properly.
1650     activemds=`facet_active mds1`
1651     if [ $activemds != "mds1" ]; then
1652         fail mds1
1653     fi
1654
1655     local clients=$CLIENTS
1656     [ -z $clients ] && clients=$(hostname)
1657
1658     zconf_umount_clients $clients $MOUNT "$*" || true
1659     [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
1660
1661     [ "$CLIENTONLY" ] && return
1662     # The add fn does rm ${facet}active file, this would be enough
1663     # if we use do_facet <facet> only after the facet added, but
1664     # currently we use do_facet mds in local.sh
1665     for num in `seq $MDSCOUNT`; do
1666         stop mds$num -f
1667         rm -f ${TMP}/mds${num}active
1668     done
1669
1670     for num in `seq $OSTCOUNT`; do
1671         stop ost$num -f
1672         rm -f $TMP/ost${num}active
1673     done
1674
1675     if ! combined_mgs_mds ; then
1676         stop mgs
1677     fi
1678
1679     return 0
1680 }
1681
1682 cleanupall() {
1683     nfs_client_mode && return
1684
1685     stopall $*
1686     unload_modules
1687     cleanup_gss
1688 }
1689
1690 mdsmkfsopts()
1691 {
1692     local nr=$1
1693     test $nr = 1 && echo -n $MDS_MKFS_OPTS || echo -n $MDSn_MKFS_OPTS
1694 }
1695
1696 combined_mgs_mds () {
1697     [[ $MDSDEV1 = $MGSDEV ]] && [[ $mds1_HOST = $mgs_HOST ]]
1698 }
1699
1700 formatall() {
1701     if [ "$IAMDIR" == "yes" ]; then
1702         MDS_MKFS_OPTS="$MDS_MKFS_OPTS --iam-dir"
1703         MDSn_MKFS_OPTS="$MDSn_MKFS_OPTS --iam-dir"
1704     fi
1705
1706     [ "$FSTYPE" ] && FSTYPE_OPT="--backfstype $FSTYPE"
1707
1708     stopall
1709     # We need ldiskfs here, may as well load them all
1710     load_modules
1711     [ "$CLIENTONLY" ] && return
1712     echo Formatting mgs, mds, osts
1713     if ! combined_mgs_mds ; then
1714         add mgs $mgs_MKFS_OPTS $FSTYPE_OPT --reformat $MGSDEV || exit 10
1715     fi
1716
1717     for num in `seq $MDSCOUNT`; do
1718         echo "Format mds$num: $(mdsdevname $num)"
1719         if $VERBOSE; then
1720             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` || exit 9
1721         else
1722             add mds$num `mdsmkfsopts $num` $FSTYPE_OPT --reformat `mdsdevname $num` > /dev/null || exit 9
1723         fi
1724     done
1725
1726     for num in `seq $OSTCOUNT`; do
1727         echo "Format ost$num: $(ostdevname $num)"
1728         if $VERBOSE; then
1729             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` || exit 10
1730         else
1731             add ost$num $OST_MKFS_OPTS --reformat `ostdevname $num` > /dev/null || exit 10
1732         fi
1733     done
1734 }
1735
1736 mount_client() {
1737     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
1738 }
1739
1740 umount_client() {
1741     grep " $1 " /proc/mounts && zconf_umount `hostname` $*
1742 }
1743
1744 # return value:
1745 # 0: success, the old identity set already.
1746 # 1: success, the old identity does not set.
1747 # 2: fail.
1748 switch_identity() {
1749     local num=$1
1750     local switch=$2
1751     local j=`expr $num - 1`
1752     local MDT="`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d"." -f2 2>/dev/null) || true`"
1753
1754     if [ -z "$MDT" ]; then
1755         return 2
1756     fi
1757
1758     local old="`do_facet mds$num "lctl get_param -n mdt.$MDT.identity_upcall"`"
1759
1760     if $switch; then
1761         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"$L_GETIDENTITY\""
1762     else
1763         do_facet mds$num "lctl set_param -n mdt.$MDT.identity_upcall \"NONE\""
1764     fi
1765
1766     do_facet mds$num "lctl set_param -n mdt/$MDT/identity_flush \"-1\""
1767
1768     if [ $old = "NONE" ]; then
1769         return 1
1770     else
1771         return 0
1772     fi
1773 }
1774
1775 remount_client()
1776 {
1777         zconf_umount `hostname` $1 || error "umount failed"
1778         zconf_mount `hostname` $1 || error "mount failed"
1779 }
1780
1781 writeconf_facet () {
1782     local facet=$1
1783     local dev=$2
1784
1785     do_facet $facet "$TUNEFS --writeconf $dev"
1786 }
1787
1788 writeconf_all () {
1789     for num in `seq $MDSCOUNT`; do
1790         DEVNAME=$(mdsdevname $num)
1791         writeconf_facet mds$num $DEVNAME
1792     done
1793
1794     for num in `seq $OSTCOUNT`; do
1795         DEVNAME=$(ostdevname $num)
1796         writeconf_facet ost$num $DEVNAME
1797     done
1798 }
1799
1800 setupall() {
1801     nfs_client_mode && return
1802
1803     sanity_mount_check ||
1804         error "environments are insane!"
1805
1806     load_modules
1807
1808     if [ -z "$CLIENTONLY" ]; then
1809         echo Setup mgs, mdt, osts
1810         echo $WRITECONF | grep -q "writeconf" && \
1811             writeconf_all
1812         if ! combined_mgs_mds ; then
1813             start mgs $MGSDEV $mgs_MOUNT_OPTS
1814         fi
1815
1816         for num in `seq $MDSCOUNT`; do
1817             DEVNAME=$(mdsdevname $num)
1818             start mds$num $DEVNAME $MDS_MOUNT_OPTS
1819
1820             # We started mds, now we should set failover variables properly.
1821             # Set mds${num}failover_HOST if it is not set (the default failnode).
1822             local varname=mds${num}failover_HOST
1823             if [ -z "${!varname}" ]; then
1824                 eval mds${num}failover_HOST=$(facet_host mds$num)
1825             fi
1826
1827             if [ $IDENTITY_UPCALL != "default" ]; then
1828                 switch_identity $num $IDENTITY_UPCALL
1829             fi
1830         done
1831         for num in `seq $OSTCOUNT`; do
1832             DEVNAME=$(ostdevname $num)
1833             start ost$num $DEVNAME $OST_MOUNT_OPTS
1834
1835             # We started ost$num, now we should set ost${num}failover variable properly.
1836             # Set ost${num}failover_HOST if it is not set (the default failnode).
1837             varname=ost${num}failover_HOST
1838             if [ -z "${!varname}" ]; then
1839                 eval ost${num}failover_HOST=$(facet_host ost${num})
1840             fi
1841
1842         done
1843     fi
1844
1845     init_gss
1846
1847     # wait a while to allow sptlrpc configuration be propogated to targets,
1848     # only needed when mounting new target devices.
1849     if $GSS; then
1850         sleep 10
1851     fi
1852
1853     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
1854     mount_client $MOUNT
1855     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
1856
1857     if [ "$MOUNT_2" ]; then
1858         mount_client $MOUNT2
1859         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
1860     fi
1861
1862     init_param_vars
1863
1864     # by remounting mdt before ost, initial connect from mdt to ost might
1865     # timeout because ost is not ready yet. wait some time to its fully
1866     # recovery. initial obd_connect timeout is 5s; in GSS case it's preceeded
1867     # by a context negotiation rpc with $TIMEOUT.
1868     # FIXME better by monitoring import status.
1869     if $GSS; then
1870         set_flavor_all $SEC
1871         sleep $((TIMEOUT + 5))
1872     else
1873         sleep 5
1874     fi
1875 }
1876
1877 mounted_lustre_filesystems() {
1878         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
1879 }
1880
1881 init_facet_vars () {
1882     [ "$CLIENTONLY" ] && return 0
1883     local facet=$1
1884     shift
1885     local device=$1
1886
1887     shift
1888
1889     eval export ${facet}_dev=${device}
1890     eval export ${facet}_opt=\"$@\"
1891
1892     local dev=${facet}_dev
1893     local label=$(do_facet ${facet} "$E2LABEL ${!dev}")
1894     [ -z "$label" ] && echo no label for ${!dev} && exit 1
1895
1896     eval export ${facet}_svc=${label}
1897
1898     local varname=${facet}failover_HOST
1899     if [ -z "${!varname}" ]; then
1900        eval $varname=$(facet_host $facet) 
1901     fi
1902
1903     # ${facet}failover_dev is set in cfg file
1904     varname=${facet}failover_dev
1905     if [ -n "${!varname}" ] ; then
1906         eval export ${facet}failover_dev=${!varname}
1907     else
1908         eval export ${facet}failover_dev=$device
1909     fi
1910 }
1911
1912 init_facets_vars () {
1913     local DEVNAME
1914
1915     if ! remote_mds_nodsh; then 
1916         for num in `seq $MDSCOUNT`; do
1917             DEVNAME=`mdsdevname $num`
1918             init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
1919         done
1920     fi
1921
1922     remote_ost_nodsh && return
1923
1924     for num in `seq $OSTCOUNT`; do
1925         DEVNAME=`ostdevname $num`
1926         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
1927     done
1928 }
1929
1930 osc_ensure_active () {
1931     local facet=$1
1932     local type=$2
1933     local timeout=$3
1934     local period=0
1935
1936     while [ $period -lt $timeout ]; do
1937         count=$(do_facet $facet "lctl dl | grep '${FSNAME}-OST.*-osc-${type}' | grep ' IN ' 2>/dev/null | wc -l")
1938         if [ $count -eq 0 ]; then
1939             break
1940         fi
1941
1942         echo "There are $count OST are inactive, wait $period seconds, and try again"
1943         sleep 3
1944         period=$((period+3))
1945     done
1946
1947     [ $period -lt $timeout ] || log "$count OST are inactive after $timeout seconds, give up"
1948 }
1949
1950 init_param_vars () {
1951     if ! remote_ost_nodsh && ! remote_mds_nodsh; then
1952         export MDSVER=$(do_facet $SINGLEMDS "lctl get_param version" | cut -d. -f1,2)
1953         export OSTVER=$(do_facet ost1 "lctl get_param version" | cut -d. -f1,2)
1954         export CLIVER=$(lctl get_param version | cut -d. -f 1,2)
1955     fi
1956
1957     remote_mds_nodsh ||
1958         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
1959
1960     log "Using TIMEOUT=$TIMEOUT"
1961
1962     osc_ensure_active $SINGLEMDS M $TIMEOUT
1963     osc_ensure_active client c $TIMEOUT
1964
1965     if [ $QUOTA_AUTO -ne 0 ]; then
1966         if [ "$ENABLE_QUOTA" ]; then
1967             echo "enable quota as required"
1968             setup_quota $MOUNT || return 2
1969         else
1970             echo "disable quota as required"
1971             $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
1972         fi
1973     fi
1974
1975     return 0
1976 }
1977
1978 nfs_client_mode () {
1979     if [ "$NFSCLIENT" ]; then
1980         echo "NFSCLIENT mode: setup, cleanup, check config skipped"
1981         local clients=$CLIENTS
1982         [ -z $clients ] && clients=$(hostname)
1983
1984         # FIXME: remove hostname when 19215 fixed
1985         do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
1986         declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
1987         do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
1988         return
1989     fi
1990     return 1
1991 }
1992
1993 check_config_client () {
1994     local mntpt=$1
1995
1996     local mounted=$(mount | grep " $mntpt ")
1997     if [ "$CLIENTONLY" ]; then
1998         # bug 18021
1999         # CLIENTONLY should not depend on *_HOST settings
2000         local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
2001         # in theory someone could create a new,
2002         # client-only config file that assumed lustre was already
2003         # configured and didn't set the MGSNID. If MGSNID is not set,
2004         # then we should use the mgs nid currently being used 
2005         # as the default value. bug 18021
2006         [[ x$MGSNID = x ]] &&
2007             MGSNID=${mgc//MGC/}
2008
2009         if [[ x$mgc != xMGC$MGSNID ]]; then
2010             if [ "$mgs_HOST" ]; then
2011                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e "s/(//g" -e "s/)//g")
2012 #                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
2013 #                    error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
2014             fi
2015         fi
2016         return 0
2017     fi
2018
2019     local myMGS_host=$mgs_HOST   
2020     if [ "$NETTYPE" = "ptl" ]; then
2021         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
2022     fi
2023
2024     echo Checking config lustre mounted on $mntpt
2025     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
2026     mgshost=$(echo $mgshost | awk -F: '{print $1}')
2027
2028 #    if [ "$mgshost" != "$myMGS_host" ]; then
2029 #            log "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
2030 #                   Please use correct config or set mds_HOST correctly!"
2031 #    fi
2032
2033 }
2034
2035 check_config_clients () {
2036     local clients=${CLIENTS:-$HOSTNAME}
2037     local mntpt=$1
2038
2039     nfs_client_mode && return
2040
2041     do_rpc_nodes $clients check_config_client $mntpt
2042
2043     sanity_mount_check ||
2044         error "environments are insane!"
2045 }
2046
2047 check_timeout () {
2048     local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
2049     local cltimeout=$(lctl get_param -n timeout)
2050     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
2051         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
2052         return 1
2053     fi
2054 }
2055
2056 is_mounted () {
2057     local mntpt=$1
2058     local mounted=$(mounted_lustre_filesystems)
2059
2060     echo $mounted' ' | grep -w -q $mntpt' '
2061 }
2062
2063 check_and_setup_lustre() {
2064     nfs_client_mode && return
2065
2066     local MOUNTED=$(mounted_lustre_filesystems)
2067
2068     local do_check=true
2069     # 1.
2070     # both MOUNT and MOUNT2 are not mounted
2071     if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
2072         [ "$REFORMAT" ] && formatall
2073         # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
2074         setupall
2075         is_mounted $MOUNT || error "NAME=$NAME not mounted"
2076         export I_MOUNTED=yes
2077         do_check=false
2078     # 2.
2079     # MOUNT2 is mounted
2080     elif is_mounted $MOUNT2; then
2081             # 3.
2082             # MOUNT2 is mounted, while MOUNT_2 is not set
2083             if ! [ "$MOUNT_2" ]; then
2084                 cleanup_mount $MOUNT2
2085                 export I_UMOUNTED2=yes
2086
2087             # 4.
2088             # MOUNT2 is mounted, MOUNT_2 is set
2089             else
2090                 # FIXME: what to do if check_config failed?
2091                 # i.e. if:
2092                 # 1) remote client has mounted other Lustre fs ?
2093                 # 2) it has insane env ?
2094                 # let's try umount MOUNT2 on all clients and mount it again:
2095                 if ! check_config_clients $MOUNT2; then
2096                     cleanup_mount $MOUNT2
2097                     restore_mount $MOUNT2
2098                     export I_MOUNTED2=yes
2099                 fi
2100             fi 
2101
2102     # 5.
2103     # MOUNT is mounted MOUNT2 is not mounted
2104     elif [ "$MOUNT_2" ]; then
2105         restore_mount $MOUNT2
2106         export I_MOUNTED2=yes
2107     fi
2108
2109     if $do_check; then
2110         # FIXME: what to do if check_config failed?
2111         # i.e. if:
2112         # 1) remote client has mounted other Lustre fs?
2113         # 2) lustre is mounted on remote_clients atall ?
2114         check_config_clients $MOUNT
2115         init_facets_vars
2116         init_param_vars
2117
2118         do_nodes $(comma_list $(nodes_list)) "lctl set_param debug=\\\"$PTLDEBUG\\\";
2119             lctl set_param subsystem_debug=\\\"${SUBSYSTEM# }\\\";
2120             lctl set_param debug_mb=${DEBUG_SIZE};
2121             sync"
2122     fi
2123
2124     init_gss
2125     set_flavor_all $SEC
2126
2127     if [ "$ONLY" == "setup" ]; then
2128         exit 0
2129     fi
2130 }
2131
2132 restore_mount () {
2133    local clients=${CLIENTS:-$HOSTNAME}
2134    local mntpt=$1
2135
2136    zconf_mount_clients $clients $mntpt
2137 }
2138
2139 cleanup_mount () {
2140     local clients=${CLIENTS:-$HOSTNAME}
2141     local mntpt=$1
2142
2143     zconf_umount_clients $clients $mntpt    
2144 }
2145
2146 cleanup_and_setup_lustre() {
2147     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
2148         lctl set_param debug=0 || true
2149         cleanupall
2150         if [ "$ONLY" == "cleanup" ]; then
2151             exit 0
2152         fi
2153     fi
2154     check_and_setup_lustre
2155 }
2156
2157 check_and_cleanup_lustre() {
2158     if is_mounted $MOUNT; then
2159         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
2160         [ "$ENABLE_QUOTA" ] && restore_quota_type || true
2161     fi
2162
2163     if [ "$I_UMOUNTED2" = "yes" ]; then
2164         restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
2165     fi
2166
2167     if [ "$I_MOUNTED2" = "yes" ]; then
2168         cleanup_mount $MOUNT2
2169     fi
2170
2171     if [ "$I_MOUNTED" = "yes" ]; then
2172         cleanupall -f || error "cleanup failed"
2173         unset I_MOUNTED
2174     fi
2175 }
2176
2177 #######
2178 # General functions
2179
2180 check_network() {
2181     local NETWORK=0
2182     local WAIT=0
2183     local MAX=$2
2184     while [ $NETWORK -eq 0 ]; do
2185         if ping -c 1 -w 3 $1 > /dev/null; then
2186             NETWORK=1
2187         else
2188             WAIT=$((WAIT + 5))
2189             echo "waiting for $1, $((MAX - WAIT)) secs left"
2190             sleep 5
2191         fi
2192         if [ $WAIT -gt $MAX ]; then
2193             echo "Network not available"
2194             exit 1
2195         fi
2196     done
2197 }
2198 check_port() {
2199     while( !($DSH2 $1 "netstat -tna | grep -q $2") ) ; do
2200         sleep 9
2201     done
2202 }
2203
2204 no_dsh() {
2205     shift
2206     eval $@
2207 }
2208
2209 comma_list() {
2210     # the sed converts spaces to commas, but leaves the last space
2211     # alone, so the line doesn't end with a comma.
2212     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
2213 }
2214
2215 # list, excluded are the comma separated lists
2216 exclude_items_from_list () {
2217     local list=$1
2218     local excluded=$2
2219     local item
2220
2221     list=${list//,/ }
2222     for item in ${excluded//,/ }; do
2223         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
2224     done
2225     echo $(comma_list $list) 
2226 }
2227
2228 # list, expand  are the comma separated lists
2229 expand_list () {
2230     local list=${1//,/ }
2231     local expand=${2//,/ }
2232     local expanded=
2233
2234     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
2235     echo $(comma_list $expanded)
2236 }
2237
2238 testslist_filter () {
2239     local script=$LUSTRE/tests/${TESTSUITE}.sh
2240
2241     [ -f $script ] || return 0
2242
2243     local start_at=$START_AT
2244     local stop_at=$STOP_AT
2245
2246     local var=${TESTSUITE//-/_}_START_AT
2247     [ x"${!var}" != x ] && start_at=${!var}
2248     var=${TESTSUITE//-/_}_STOP_AT
2249     [ x"${!var}" != x ] && stop_at=${!var}
2250
2251     sed -n 's/^test_\([^ (]*\).*/\1/p' $script | \
2252         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
2253             /^'${start_at}'$/ {flag = 0}
2254             {if (flag == 1) print $0}
2255             /^'${stop_at}'$/ { flag = 1 }'
2256 }
2257
2258 absolute_path() {
2259     (cd `dirname $1`; echo $PWD/`basename $1`)
2260 }
2261
2262 get_facets () {
2263     local name=$(echo $1 | tr "[:upper:]" "[:lower:]")
2264     local type=$(echo $1 | tr "[:lower:]" "[:upper:]")
2265
2266     local list=""
2267     local count=${type}COUNT
2268     for ((i=1; i<=${!count}; i++)) do
2269         list="$list ${name}$i"
2270     done
2271     echo $(comma_list $list)
2272 }
2273
2274 ##################################
2275 # Adaptive Timeouts funcs
2276
2277 at_is_enabled() {
2278     # only check mds, we assume at_max is the same on all nodes
2279     local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
2280     if [ $at_max -eq 0 ]; then
2281         return 1
2282     else
2283         return 0
2284     fi
2285 }
2286
2287 at_max_get() {
2288     local facet=$1
2289
2290     # suppose that all ost-s has the same at_max set
2291     if [ $facet == "ost" ]; then
2292         do_facet ost1 "lctl get_param -n at_max"
2293     else
2294         do_facet $facet "lctl get_param -n at_max"
2295     fi
2296 }
2297
2298 at_max_set() {
2299     local at_max=$1
2300     shift
2301
2302     local facet
2303     for facet in $@; do
2304         if [ $facet == "ost" ]; then
2305             for i in `seq $OSTCOUNT`; do
2306                 do_facet ost$i "lctl set_param at_max=$at_max"
2307
2308             done
2309         elif [ $facet == "mds" ]; then
2310             for i in `seq $MDSCOUNT`; do
2311                 do_facet mds$i "lctl set_param at_max=$at_max"
2312             done
2313         else
2314             do_facet $facet "lctl set_param at_max=$at_max"
2315         fi
2316     done
2317 }
2318
2319 ##################################
2320 # OBD_FAIL funcs
2321
2322 drop_request() {
2323 # OBD_FAIL_MDS_ALL_REQUEST_NET
2324     RC=0
2325     do_facet $SINGLEMDS lctl set_param fail_loc=0x123
2326     do_facet client "$1" || RC=$?
2327     do_facet $SINGLEMDS lctl set_param fail_loc=0
2328     return $RC
2329 }
2330
2331 drop_reply() {
2332 # OBD_FAIL_MDS_ALL_REPLY_NET
2333     RC=0
2334     do_facet $SINGLEMDS lctl set_param fail_loc=0x122
2335     do_facet client "$@" || RC=$?
2336     do_facet $SINGLEMDS lctl set_param fail_loc=0
2337     return $RC
2338 }
2339
2340 drop_reint_reply() {
2341 # OBD_FAIL_MDS_REINT_NET_REP
2342     RC=0
2343     do_facet $SINGLEMDS lctl set_param fail_loc=0x119
2344     do_facet client "$@" || RC=$?
2345     do_facet $SINGLEMDS lctl set_param fail_loc=0
2346     return $RC
2347 }
2348
2349 pause_bulk() {
2350 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
2351     RC=0
2352     do_facet ost1 lctl set_param fail_loc=0x214
2353     do_facet client "$1" || RC=$?
2354     do_facet client "sync"
2355     do_facet ost1 lctl set_param fail_loc=0
2356     return $RC
2357 }
2358
2359 drop_ldlm_cancel() {
2360 #define OBD_FAIL_LDLM_CANCEL             0x304
2361     RC=0
2362     do_facet client lctl set_param fail_loc=0x304
2363     do_facet client "$@" || RC=$?
2364     do_facet client lctl set_param fail_loc=0
2365     return $RC
2366 }
2367
2368 drop_bl_callback() {
2369 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
2370     RC=0
2371     do_facet client lctl set_param fail_loc=0x305
2372     do_facet client "$@" || RC=$?
2373     do_facet client lctl set_param fail_loc=0
2374     return $RC
2375 }
2376
2377 drop_ldlm_reply() {
2378 #define OBD_FAIL_LDLM_REPLY              0x30c
2379     RC=0
2380     do_facet $SINGLEMDS lctl set_param fail_loc=0x30c
2381     do_facet client "$@" || RC=$?
2382     do_facet $SINGLEMDS lctl set_param fail_loc=0
2383     return $RC
2384 }
2385
2386 clear_failloc() {
2387     facet=$1
2388     pause=$2
2389     sleep $pause
2390     echo "clearing fail_loc on $facet"
2391     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
2392 }
2393
2394 set_nodes_failloc () {
2395     do_nodes $(comma_list $1)  lctl set_param fail_loc=$2
2396 }
2397
2398 cancel_lru_locks() {
2399     $LCTL mark "cancel_lru_locks $1 start"
2400     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
2401         $LCTL set_param -n $d=clear
2402     done
2403     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
2404     $LCTL mark "cancel_lru_locks $1 stop"
2405 }
2406
2407 default_lru_size()
2408 {
2409         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
2410         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
2411         echo "$DEFAULT_LRU_SIZE"
2412 }
2413
2414 lru_resize_enable()
2415 {
2416     lctl set_param ldlm.namespaces.*$1*.lru_size=0
2417 }
2418
2419 lru_resize_disable()
2420 {
2421     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
2422 }
2423
2424 pgcache_empty() {
2425     local FILE
2426     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
2427         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
2428             echo there is still data in page cache $FILE ?
2429             lctl get_param -n $FILE
2430             return 1
2431         fi
2432     done
2433     return 0
2434 }
2435
2436 debugsave() {
2437     DEBUGSAVE="$(lctl get_param -n debug)"
2438 }
2439
2440 debugrestore() {
2441     [ -n "$DEBUGSAVE" ] && \
2442         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\";"
2443     DEBUGSAVE=""
2444 }
2445
2446 debug_size_save() {
2447     DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
2448 }
2449
2450 debug_size_restore() {
2451     [ -n "$DEBUG_SIZE_SAVED" ] && \
2452         do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
2453     DEBUG_SIZE_SAVED=""
2454 }
2455
2456 start_full_debug_logging() {
2457     debugsave
2458     debug_size_save
2459
2460     local FULLDEBUG=-1
2461     local DEBUG_SIZE=150
2462
2463     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE"
2464     do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug=$FULLDEBUG;"
2465 }
2466
2467 stop_full_debug_logging() {
2468     debug_size_restore
2469     debugrestore
2470 }
2471
2472 ##################################
2473 # Test interface
2474 ##################################
2475
2476 error_noexit() {
2477     local TYPE=${TYPE:-"FAIL"}
2478
2479     local dump=true
2480     # do not dump logs if $1=false
2481     if [ "x$1" = "xfalse" ]; then
2482         shift
2483         dump=false
2484     fi
2485
2486     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
2487
2488     # We need to dump the logs on all nodes
2489     if $dump; then
2490         gather_logs $(comma_list $(nodes_list))
2491     fi
2492
2493     debugrestore
2494     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
2495     echo "$@" > $LOGDIR/err
2496 }
2497
2498 error() {
2499     error_noexit "$@"
2500     exit 1
2501 }
2502
2503 error_exit() {
2504     error "$@"
2505 }
2506
2507 # use only if we are ignoring failures for this test, bugno required.
2508 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
2509 # e.g. error_ignore 5494 "your message"
2510 error_ignore() {
2511     local TYPE="IGNORE (bz$1)"
2512     shift
2513     error_noexit "$@"
2514 }
2515
2516 skip_env () {
2517     $FAIL_ON_SKIP_ENV && error false $@ || skip $@
2518 }
2519
2520 skip () {
2521     echo
2522     log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
2523     [ "$TESTSUITELOG" ] && \
2524         echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
2525 }
2526
2527 build_test_filter() {
2528     EXCEPT="$EXCEPT $(testslist_filter)"
2529
2530     [ "$ONLY" ] && log "only running test `echo $ONLY`"
2531     for O in $ONLY; do
2532         eval ONLY_${O}=true
2533     done
2534     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
2535         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
2536     [ "$EXCEPT_SLOW" ] && \
2537         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
2538     for E in $EXCEPT $ALWAYS_EXCEPT; do
2539         eval EXCEPT_${E}=true
2540     done
2541     for E in $EXCEPT_SLOW; do
2542         eval EXCEPT_SLOW_${E}=true
2543     done
2544     for G in $GRANT_CHECK_LIST; do
2545         eval GCHECK_ONLY_${G}=true
2546         done
2547 }
2548
2549 basetest() {
2550     if [[ $1 = [a-z]* ]]; then
2551         echo $1
2552     else
2553         echo ${1%%[a-z]*}
2554     fi
2555 }
2556
2557 # print a newline if the last test was skipped
2558 export LAST_SKIPPED=
2559 #
2560 # Main entry into test-framework. This is called with the name and
2561 # description of a test. The name is used to find the function to run
2562 # the test using "test_$name".
2563 #
2564 # This supports a variety of methods of specifying specific test to
2565 # run or not run.  These need to be documented...
2566 #
2567 run_test() {
2568     assert_DIR
2569
2570     export base=`basetest $1`
2571     if [ ! -z "$ONLY" ]; then
2572         testname=ONLY_$1
2573         if [ ${!testname}x != x ]; then
2574             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2575             run_one_logged $1 "$2"
2576             return $?
2577         fi
2578         testname=ONLY_$base
2579         if [ ${!testname}x != x ]; then
2580             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
2581             run_one_logged $1 "$2"
2582             return $?
2583         fi
2584         LAST_SKIPPED="y"
2585         echo -n "."
2586         return 0
2587     fi
2588     testname=EXCEPT_$1
2589     if [ ${!testname}x != x ]; then
2590         LAST_SKIPPED="y"
2591         TESTNAME=test_$1 skip "skipping excluded test $1"
2592         return 0
2593     fi
2594     testname=EXCEPT_$base
2595     if [ ${!testname}x != x ]; then
2596         LAST_SKIPPED="y"
2597         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
2598         return 0
2599     fi
2600     testname=EXCEPT_SLOW_$1
2601     if [ ${!testname}x != x ]; then
2602         LAST_SKIPPED="y"
2603         TESTNAME=test_$1 skip "skipping SLOW test $1"
2604         return 0
2605     fi
2606     testname=EXCEPT_SLOW_$base
2607     if [ ${!testname}x != x ]; then
2608         LAST_SKIPPED="y"
2609         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
2610         return 0
2611     fi
2612
2613     LAST_SKIPPED=
2614     run_one_logged $1 "$2"
2615
2616     return $?
2617 }
2618
2619 EQUALS="======================================================================"
2620 equals_msg() {
2621     msg="$@"
2622
2623     local suffixlen=$((${#EQUALS} - ${#msg}))
2624     [ $suffixlen -lt 5 ] && suffixlen=5
2625     log `echo $(printf '===== %s %.*s\n' "$msg" $suffixlen $EQUALS)`
2626 }
2627
2628 log() {
2629     echo "$*"
2630     module_loaded lnet || load_modules
2631
2632     local MSG="$*"
2633     # Get rid of '
2634     MSG=${MSG//\'/\\\'}
2635     MSG=${MSG//\(/\\\(}
2636     MSG=${MSG//\)/\\\)}
2637     MSG=${MSG//\;/\\\;}
2638     MSG=${MSG//\|/\\\|}
2639     MSG=${MSG//\>/\\\>}
2640     MSG=${MSG//\</\\\<}
2641     MSG=${MSG//\//\\\/}
2642     do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
2643 }
2644
2645 trace() {
2646         log "STARTING: $*"
2647         strace -o $TMP/$1.strace -ttt $*
2648         RC=$?
2649         log "FINISHED: $*: rc $RC"
2650         return 1
2651 }
2652
2653 pass() {
2654     # Set TEST_STATUS here; will be used for logging the result
2655     if [ -f $LOGDIR/err ]; then
2656         TEST_STATUS="FAIL"
2657     else
2658         TEST_STATUS="PASS"
2659     fi
2660     echo $TEST_STATUS " " $@
2661 }
2662
2663 check_mds() {
2664     FFREE=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filesfree | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2665     FTOTAL=$(do_node $SINGLEMDS lctl get_param -n osd.*MDT*.filestotal | awk 'BEGIN{avail=0}; {avail+=$1}; END{print avail}')
2666     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
2667 }
2668
2669 reset_fail_loc () {
2670     echo -n "Resetting fail_loc on all nodes..."
2671     do_nodes $(comma_list $(nodes_list)) "lctl set_param -n fail_loc=0 2>/dev/null || true"
2672     echo done.
2673 }
2674
2675
2676 #
2677 # Log a message (on all nodes) padded with "=" before and after. 
2678 # Also appends a timestamp and prepends the testsuite name.
2679
2680 banner() {
2681     msg="== ${TESTSUITE} $*"
2682     # pad the message out to 70 with "="
2683     last=${msg: -1:1}
2684     [[ $last != "=" && $last != " " ]] && msg+=" "
2685     for i in $(seq $((68 - ${#msg})) ); do
2686         msg+="="
2687     done
2688     # always include at least == after the message
2689     msg+="=="
2690
2691     log "$msg $(date +"%H:%M:%S (%s)")"
2692 }
2693
2694 #
2695 # Run a single test function and cleanup after it.  
2696 #
2697 # This function should be run in a subshell so the test func can
2698 # exit() without stopping the whole script.
2699 #
2700 run_one() {
2701     local testnum=$1
2702     local message=$2
2703     tfile=f${testnum}
2704     export tdir=d0.${TESTSUITE}/d${base}
2705     export TESTNAME=test_$testnum
2706     local SAVE_UMASK=`umask`
2707     umask 0022
2708
2709     banner "test $testnum: $message"
2710     test_${testnum} || error "test_$testnum failed with $?"
2711     cd $SAVE_PWD
2712     reset_fail_loc
2713     check_grant ${testnum} || error "check_grant $testnum failed with $?"
2714     check_catastrophe || error "LBUG/LASSERT detected"
2715     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
2716     unset TESTNAME
2717     unset tdir
2718     umask $SAVE_UMASK
2719     return 0
2720 }
2721
2722 #
2723 # Wrapper around run_one to ensure:
2724 #  - test runs in subshell
2725 #  - output of test is saved to separate log file for error reporting
2726 #  - test result is saved to data file
2727 #
2728 run_one_logged() {
2729     local BEFORE=`date +%s`
2730     local TEST_ERROR
2731     local name=${TESTSUITE}.test_${1}.test_log.$(hostname).log
2732     local test_log=$LOGDIR/$name
2733     rm -rf $LOGDIR/err
2734
2735     echo
2736     (run_one $1 "$2") 2>&1 | tee $test_log
2737     local RC=${PIPESTATUS[0]}
2738
2739     [ $RC -ne 0 ] && [ ! -f $LOGDIR/err ] && \
2740         echo "test_$1 returned $RC" | tee $LOGDIR/err
2741
2742     duration=$((`date +%s` - $BEFORE))
2743     pass "(${duration}s)"
2744     [ -f $LOGDIR/err ] && TEST_ERROR=$(cat $LOGDIR/err)
2745     log_sub_test test_${1} $TEST_STATUS $duration "$RC" "$TEST_ERROR"
2746
2747     if [ -f $LOGDIR/err ]; then
2748         $FAIL_ON_ERROR && exit $RC
2749     fi
2750
2751     return 0
2752 }
2753
2754 canonical_path() {
2755     (cd `dirname $1`; echo $PWD/`basename $1`)
2756 }
2757
2758 sync_clients() {
2759     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
2760     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
2761         cd $SAVE_PWD
2762 }
2763
2764 check_grant() {
2765     export base=`basetest $1`
2766     [ "$CHECK_GRANT" == "no" ] && return 0
2767
2768         testname=GCHECK_ONLY_${base}
2769         [ ${!testname}x == x ] && return 0
2770
2771     echo -n "checking grant......"
2772         cd $SAVE_PWD
2773         # write some data to sync client lost_grant
2774         rm -f $DIR1/${tfile}_check_grant_* 2>&1
2775         for i in `seq $OSTCOUNT`; do
2776                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
2777                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
2778                                               count=1 > /dev/null 2>&1
2779         done
2780         # sync all the data and make sure no pending data on server
2781         sync_clients
2782         
2783         #get client grant and server grant
2784         client_grant=0
2785     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
2786                 client_grant=$((client_grant + $d))
2787         done
2788         server_grant=0
2789         for d in `lctl get_param -n obdfilter.*.tot_granted`; do
2790                 server_grant=$((server_grant + $d))
2791         done
2792
2793         # cleanup the check_grant file
2794         for i in `seq $OSTCOUNT`; do
2795                 rm $DIR1/${tfile}_check_grant_$i
2796         done
2797
2798         #check whether client grant == server grant
2799         if [ $client_grant != $server_grant ]; then
2800                 echo "failed: client:${client_grant} server: ${server_grant}"
2801                 return 1
2802         else
2803                 echo "pass"
2804         fi
2805 }
2806
2807 ########################
2808 # helper functions
2809
2810 osc_to_ost()
2811 {
2812     osc=$1
2813     ost=`echo $1 | awk -F_ '{print $3}'`
2814     if [ -z $ost ]; then
2815         ost=`echo $1 | sed 's/-osc.*//'`
2816     fi
2817     echo $ost
2818 }
2819
2820 remote_node () {
2821     local node=$1
2822     [ "$node" != "$(hostname)" ]
2823 }
2824
2825 remote_mds ()
2826 {
2827     local node
2828     for node in $(mdts_nodes); do
2829         remote_node $node && return 0
2830     done
2831     return 1
2832 }
2833
2834 remote_mds_nodsh()
2835 {
2836     [ "$CLIENTONLY" ] && return 0 || true
2837     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
2838 }
2839
2840 require_dsh_mds()
2841 {
2842         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" && \
2843             MSKIPPED=1 && return 1
2844         return 0
2845 }
2846
2847 remote_ost ()
2848 {
2849     local node
2850     for node in $(osts_nodes) ; do
2851         remote_node $node && return 0
2852     done
2853     return 1
2854 }
2855
2856 remote_ost_nodsh()
2857 {
2858     [ "$CLIENTONLY" ] && return 0 || true 
2859     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2860 }
2861
2862 require_dsh_ost()
2863 {
2864         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" && \
2865             OSKIPPED=1 && return 1
2866         return 0
2867 }
2868
2869 remote_mgs_nodsh()
2870 {
2871     local MGS 
2872     MGS=$(facet_host mgs)
2873     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
2874 }
2875
2876 local_mode ()
2877 {
2878     remote_mds_nodsh || remote_ost_nodsh || \
2879         $(single_local_node $(comma_list $(nodes_list)))
2880 }
2881
2882 mdts_nodes () {
2883     local MDSNODES
2884     local NODES_sort
2885     for num in `seq $MDSCOUNT`; do
2886         MDSNODES="$MDSNODES $(facet_host mds$num)"
2887     done
2888     NODES_sort=$(for i in $MDSNODES; do echo $i; done | sort -u)
2889
2890     echo $NODES_sort
2891 }
2892
2893 remote_servers () {
2894     remote_ost && remote_mds
2895 }
2896
2897 osts_nodes () {
2898     local OSTNODES=$(facet_host ost1)
2899     local NODES_sort
2900
2901     for num in `seq $OSTCOUNT`; do
2902         local myOST=$(facet_host ost$num)
2903         OSTNODES="$OSTNODES $myOST"
2904     done
2905     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
2906
2907     echo $NODES_sort
2908 }
2909
2910 nodes_list () {
2911     # FIXME. We need a list of clients
2912     local myNODES=$HOSTNAME
2913     local myNODES_sort
2914
2915     # CLIENTS (if specified) contains the local client
2916     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
2917
2918     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
2919         myNODES="$myNODES $(osts_nodes) $(mdts_nodes)"
2920     fi
2921
2922     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
2923
2924     echo $myNODES_sort
2925 }
2926
2927 remote_nodes_list () {
2928     local rnodes=$(nodes_list)
2929     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2930     echo $rnodes
2931 }
2932
2933 init_clients_lists () {
2934     # Sanity check: exclude the local client from RCLIENTS
2935     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
2936
2937     # Sanity check: exclude the dup entries
2938     rclients=$(for i in $rclients; do echo $i; done | sort -u)
2939
2940     local clients="$SINGLECLIENT $HOSTNAME $rclients"
2941
2942     # Sanity check: exclude the dup entries from CLIENTS
2943     # for those configs which has SINGLCLIENT set to local client
2944     clients=$(for i in $clients; do echo $i; done | sort -u)
2945
2946     CLIENTS=`comma_list $clients`
2947     local -a remoteclients=($rclients)
2948     for ((i=0; $i<${#remoteclients[@]}; i++)); do
2949             varname=CLIENT$((i + 2))
2950             eval $varname=${remoteclients[i]}
2951     done
2952
2953     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
2954 }
2955
2956 get_random_entry () {
2957     local rnodes=$1
2958
2959     rnodes=${rnodes//,/ }
2960
2961     local -a nodes=($rnodes)
2962     local num=${#nodes[@]} 
2963     local i=$((RANDOM * num * 2 / 65536))
2964
2965     echo ${nodes[i]}
2966 }
2967
2968 client_only () {
2969     [ "$CLIENTONLY" ] || [ "$CLIENTMODSONLY" = yes ]
2970 }
2971
2972 is_patchless ()
2973 {
2974     lctl get_param version | grep -q patchless
2975 }
2976
2977 check_versions () {
2978     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
2979 }
2980
2981 get_node_count() {
2982     local nodes="$@"
2983     echo $nodes | wc -w || true
2984 }
2985
2986 mixed_ost_devs () {
2987     local nodes=$(osts_nodes)
2988     local osscount=$(get_node_count "$nodes")
2989     [ ! "$OSTCOUNT" = "$osscount" ]
2990 }
2991
2992 mixed_mdt_devs () {
2993     local nodes=$(mdts_nodes)
2994     local mdtcount=$(get_node_count "$nodes")
2995     [ ! "$MDSCOUNT" = "$mdtcount" ]
2996 }
2997
2998 generate_machine_file() {
2999     local nodes=${1//,/ }
3000     local machinefile=$2
3001     rm -f $machinefile
3002     for node in $nodes; do
3003         echo $node >>$machinefile || \
3004             { echo "can not generate machinefile $machinefile" && return 1; }
3005     done
3006 }
3007
3008 get_stripe () {
3009     local file=$1/stripe
3010     touch $file
3011     $LFS getstripe -v $file || error
3012     rm -f $file
3013 }
3014
3015 setstripe_nfsserver () {
3016     local dir=$1
3017
3018     local nfsserver=$(awk '"'$dir'" ~ $2 && $3 ~ "nfs" && $2 != "/" \
3019                 { print $1 }' /proc/mounts | cut -f 1 -d : | head -1)
3020
3021     [ -z $nfsserver ] && echo "$dir is not nfs mounted" && return 1
3022
3023     do_nodev $nfsserver lfs setstripe "$@"
3024 }
3025
3026 check_runas_id_ret() {
3027     local myRC=0
3028     local myRUNAS_UID=$1
3029     local myRUNAS_GID=$2
3030     shift 2
3031     local myRUNAS=$@
3032     if [ -z "$myRUNAS" ]; then
3033         error_exit "myRUNAS command must be specified for check_runas_id"
3034     fi
3035     if $GSS_KRB5; then
3036         $myRUNAS krb5_login.sh || \
3037             error "Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID."
3038     fi
3039     mkdir $DIR/d0_runas_test
3040     chmod 0755 $DIR
3041     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
3042     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
3043     rm -rf $DIR/d0_runas_test
3044     return $myRC
3045 }
3046
3047 check_runas_id() {
3048     local myRUNAS_UID=$1
3049     local myRUNAS_GID=$2
3050     shift 2
3051     local myRUNAS=$@
3052     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
3053         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
3054         Please set RUNAS_ID to some UID which exists on MDS and client or
3055         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
3056 }
3057
3058 # obtain the UID/GID for MPI_USER
3059 get_mpiuser_id() {
3060     local mpi_user=$1
3061
3062     MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
3063 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
3064
3065     MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
3066 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
3067 }
3068
3069 # obtain and cache Kerberos ticket-granting ticket
3070 refresh_krb5_tgt() {
3071     local myRUNAS_UID=$1
3072     local myRUNAS_GID=$2
3073     shift 2
3074     local myRUNAS=$@
3075     if [ -z "$myRUNAS" ]; then
3076         error_exit "myRUNAS command must be specified for refresh_krb5_tgt"
3077     fi
3078
3079     CLIENTS=${CLIENTS:-$HOSTNAME}
3080     do_nodes $CLIENTS "set -x
3081 if ! $myRUNAS krb5_login.sh; then
3082     echo "Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID."
3083     exit 1
3084 fi"
3085 }
3086
3087 # Run multiop in the background, but wait for it to print
3088 # "PAUSING" to its stdout before returning from this function.
3089 multiop_bg_pause() {
3090     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
3091     FILE=$1
3092     ARGS=$2
3093
3094     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
3095     mkfifo $TMPPIPE
3096
3097     echo "$MULTIOP_PROG $FILE v$ARGS"
3098     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
3099
3100     echo "TMPPIPE=${TMPPIPE}"
3101     read -t 60 multiop_output < $TMPPIPE
3102     if [ $? -ne 0 ]; then
3103         rm -f $TMPPIPE
3104         return 1
3105     fi
3106     rm -f $TMPPIPE
3107     if [ "$multiop_output" != "PAUSING" ]; then
3108         echo "Incorrect multiop output: $multiop_output"
3109         kill -9 $PID
3110         return 1
3111     fi
3112
3113     return 0
3114 }
3115
3116 do_and_time () {
3117     local cmd=$1
3118     local rc
3119
3120     SECONDS=0
3121     eval '$cmd'
3122     
3123     [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
3124
3125     echo $SECONDS
3126     return $rc
3127 }
3128
3129 inodes_available () {
3130     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
3131     echo $IFree
3132 }
3133
3134 mdsrate_inodes_available () {
3135     echo $(($(inodes_available) - 1))
3136 }
3137
3138 # reset llite stat counters
3139 clear_llite_stats(){
3140         lctl set_param -n llite.*.stats 0
3141 }
3142
3143 # sum llite stat items
3144 calc_llite_stats() {
3145         local res=$(lctl get_param -n llite.*.stats |
3146                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
3147         echo $res
3148 }
3149
3150 # reset osc stat counters
3151 clear_osc_stats(){
3152         lctl set_param -n osc.*.osc_stats 0
3153 }
3154
3155 # sum osc stat items
3156 calc_osc_stats() {
3157         local res=$(lctl get_param -n osc.*.osc_stats |
3158                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
3159         echo $res
3160 }
3161
3162 calc_sum () {
3163         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
3164 }
3165
3166 calc_osc_kbytes () {
3167         df $MOUNT > /dev/null
3168         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
3169 }
3170
3171 # save_lustre_params(node, parameter_mask)
3172 # generate a stream of formatted strings (<node> <param name>=<param value>)
3173 save_lustre_params() {
3174         local s
3175         do_nodesv $1 "lctl get_param $2 | while read s; do echo \\\$s; done"
3176 }
3177
3178 # restore lustre parameters from input stream, produces by save_lustre_params
3179 restore_lustre_params() {
3180         local node
3181         local name
3182         local val
3183         while IFS=" =" read node name val; do
3184                 do_node ${node//:/} "lctl set_param -n $name $val"
3185         done
3186 }
3187
3188 check_catastrophe() {
3189     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
3190     local C=$CATASTROPHE
3191     [ -f $C ] && [ $(cat $C) -ne 0 ] && return 1
3192
3193     if [ $rnodes ]; then
3194         do_nodes $rnodes "rc=\\\$([ -f $C ] && echo \\\$(< $C) || echo 0);
3195 if [ \\\$rc -ne 0 ]; then echo \\\$(hostname): \\\$rc; fi
3196 exit \\\$rc;"
3197     fi 
3198 }
3199
3200 # $1 node
3201 # $2 file
3202 # $3 $RUNAS
3203 get_stripe_info() {
3204         local tmp_file
3205
3206         stripe_size=0
3207         stripe_count=0
3208         stripe_index=0
3209         tmp_file=$(mktemp)
3210
3211         do_facet $1 $3 lfs getstripe -v $2 > $tmp_file
3212
3213         stripe_size=`awk '$1 ~ /size/ {print $2}' $tmp_file`
3214         stripe_count=`awk '$1 ~ /count/ {print $2}' $tmp_file`
3215         stripe_index=`awk '$1 ~ /stripe_offset/ {print $2}' $tmp_file`
3216         rm -f $tmp_file
3217 }
3218
3219 # CMD: determine mds index where directory inode presents
3220 get_mds_dir () {
3221     local dir=$1
3222     local file=$dir/f0.get_mds_dir_tmpfile
3223
3224     mkdir -p $dir
3225     rm -f $file
3226     sleep 1
3227     local iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
3228     local -a oldused=($iused)
3229
3230     openfile -f O_CREAT:O_LOV_DELAY_CREATE -m 0644 $file > /dev/null
3231     sleep 1
3232     iused=$(lfs df -i $dir | grep MDT | awk '{print $3}')
3233     local -a newused=($iused)
3234
3235     local num=0
3236     for ((i=0; i<${#newused[@]}; i++)); do
3237          if [ ${oldused[$i]} -lt ${newused[$i]} ];  then
3238              echo $(( i + 1 ))
3239              rm -f $file
3240              return 0
3241          fi
3242     done
3243     error "mdt-s : inodes count OLD ${oldused[@]} NEW ${newused[@]}"
3244 }
3245
3246 mdsrate_cleanup () {
3247     if [ -d $4 ]; then
3248         mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5 $6
3249         rmdir $4
3250     fi
3251 }
3252
3253 delayed_recovery_enabled () {
3254     local var=${SINGLEMDS}_svc
3255     do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1
3256 }
3257
3258 ########################
3259
3260 convert_facet2label() { 
3261     local facet=$1
3262
3263     if [ x$facet = xost ]; then
3264        facet=ost1
3265     fi
3266
3267     local varsvc=${facet}_svc
3268
3269     if [ -n ${!varsvc} ]; then
3270         echo ${!varsvc}
3271     else  
3272         error "No lablel for $facet!"
3273     fi
3274 }
3275
3276 get_clientosc_proc_path() {
3277     local ost=$1
3278
3279     echo "{$1}-osc-*"
3280 }
3281
3282 get_lustre_version () {
3283     local node=${1:-"mds"}    
3284     do_facet $node $LCTL get_param -n version |  awk '/^lustre:/ {print $2}'
3285 }
3286
3287 get_mds_version_major () {
3288     local version=$(get_lustre_version mds)
3289     echo $version | awk -F. '{print $1}'
3290 }
3291
3292 get_mds_version_minor () {
3293     local version=$(get_lustre_version mds)
3294     echo $version | awk -F. '{print $2}'
3295 }
3296
3297 get_mdtosc_proc_path() {
3298     local ost=$1
3299     local major=$(get_mds_version_major)
3300     local minor=$(get_mds_version_minor)
3301     if [ $major -le 1 -a $minor -le 8 ] ; then
3302         echo "${ost}-osc"
3303     else
3304         echo "${ost}-osc-MDT0000"
3305     fi
3306 }
3307
3308 get_osc_import_name() {
3309     local facet=$1
3310     local ost=$2
3311     local label=$(convert_facet2label $ost)
3312
3313     if [ "$facet" == "mds" ]; then
3314         get_mdtosc_proc_path $label
3315         return 0
3316     fi
3317
3318     get_clientosc_proc_path $label
3319     return 0
3320 }
3321
3322 wait_import_state () {
3323     local expected=$1
3324     local CONN_PROC=$2
3325     local CONN_STATE
3326     local i=0
3327
3328     CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3329     while [ "${CONN_STATE}" != "${expected}" ]; do
3330         if [ "${expected}" == "DISCONN" ]; then
3331             # for disconn we can check after proc entry is removed
3332             [ "x${CONN_STATE}" == "x" ] && return 0
3333             #  with AT we can have connect request timeout ~ reconnect timeout
3334             # and test can't see real disconnect
3335             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
3336         fi
3337         # disconnect rpc should be wait not more obd_timeout
3338         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
3339             error "can't put import for $CONN_PROC into ${expected} state" && return 1
3340         sleep 1
3341         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3342         i=$(($i + 1))
3343     done
3344
3345     log "$CONN_PROC now in ${CONN_STATE} state"
3346     return 0
3347 }
3348
3349 wait_osc_import_state() {
3350     local facet=$1
3351     local ost_facet=$2
3352     local expected=$3
3353     local ost=$(get_osc_import_name $facet $ost_facet)
3354     local CONN_PROC
3355     local CONN_STATE
3356     local i=0
3357
3358     CONN_PROC="osc.${ost}.ost_server_uuid"
3359     CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3360     while [ "${CONN_STATE}" != "${expected}" ]; do
3361         if [ "${expected}" == "DISCONN" ]; then 
3362             # for disconn we can check after proc entry is removed
3363             [ "x${CONN_STATE}" == "x" ] && return 0
3364             #  with AT we can have connect request timeout ~ reconnect timeout
3365             # and test can't see real disconnect
3366             [ "${CONN_STATE}" == "CONNECTING" ] && return 0
3367         fi
3368         # disconnect rpc should be wait not more obd_timeout
3369         [ $i -ge $(($TIMEOUT * 3 / 2)) ] && \
3370             error "can't put import for ${ost}(${ost_facet}) into ${expected} state" && return 1
3371         sleep 1
3372         CONN_STATE=$(do_facet $facet lctl get_param -n $CONN_PROC 2>/dev/null | cut -f2)
3373         i=$(($i + 1))
3374     done
3375
3376     log "${ost_facet} now in ${CONN_STATE} state"
3377     return 0
3378 }
3379 get_clientmdc_proc_path() {
3380     echo "${1}-mdc-*"
3381 }
3382
3383 do_rpc_nodes () {
3384     local list=$1
3385     shift
3386
3387     # Add paths to lustre tests for 32 and 64 bit systems.
3388     local RPATH="$RLUSTRE/tests:/usr/lib/lustre/tests:/usr/lib64/lustre/tests:$PATH"
3389     do_nodesv $list "PATH=$RPATH sh rpc.sh $@ "
3390 }
3391
3392 wait_clients_import_state () {
3393     local list=$1
3394     local facet=$2
3395     local expected=$3
3396     shift
3397
3398     local label=$(convert_facet2label $facet)
3399     local proc_path
3400     case $facet in
3401         ost* ) proc_path="osc.$(get_clientosc_proc_path $label).ost_server_uuid" ;;
3402         mds* ) proc_path="mdc.$(get_clientmdc_proc_path $label).mds_server_uuid" ;;
3403         *) error "unknown facet!" ;;
3404     esac
3405
3406     if ! do_rpc_nodes $list wait_import_state $expected $proc_path; then
3407         error "import is not in ${expected} state"
3408         return 1
3409     fi
3410 }
3411
3412 oos_full() {
3413         local -a AVAILA
3414         local -a GRANTA
3415         local OSCFULL=1
3416         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
3417                   $LCTL get_param obdfilter.*.kbytesavail))
3418         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
3419                   $LCTL get_param -n obdfilter.*.tot_granted))
3420         for ((i=0; i<${#AVAILA[@]}; i++)); do
3421                 local -a AVAIL1=(${AVAILA[$i]//=/ })
3422                 GRANT=$((${GRANTA[$i]}/1024))
3423                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} grnt=$GRANT diff=$((AVAIL1[1] - GRANT))
3424                 [ $((AVAIL1[1] - GRANT)) -lt 400 ] && OSCFULL=0 && echo " FULL" || echo
3425         done
3426         return $OSCFULL
3427 }
3428
3429 pool_list () {
3430    do_facet mgs lctl pool_list $1
3431 }
3432
3433 create_pool() {
3434     local fsname=${1%%.*}
3435     local poolname=${1##$fsname.}
3436
3437     do_facet mgs lctl pool_new $1
3438     local RC=$?
3439     # get param should return err unless pool is created
3440     [[ $RC -ne 0 ]] && return $RC
3441
3442     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
3443         2>/dev/null || echo foo" "" || RC=1
3444     if [[ $RC -eq 0 ]]; then
3445         add_pool_to_list $1
3446     else
3447         error "pool_new failed $1"
3448     fi
3449     return $RC
3450 }
3451
3452 add_pool_to_list () {
3453     local fsname=${1%%.*}
3454     local poolname=${1##$fsname.}
3455
3456     local listvar=${fsname}_CREATED_POOLS
3457     eval export ${listvar}=$(expand_list ${!listvar} $poolname)
3458 }
3459
3460 remove_pool_from_list () {
3461     local fsname=${1%%.*}
3462     local poolname=${1##$fsname.}
3463
3464     local listvar=${fsname}_CREATED_POOLS
3465     eval export ${listvar}=$(exclude_items_from_list ${!listvar} $poolname)
3466 }
3467
3468 destroy_pool_int() {
3469     local ost
3470     local OSTS=$(do_facet $SINGLEMDS lctl pool_list $1 | \
3471         awk '$1 !~ /^Pool:/ {print $1}')
3472     for ost in $OSTS; do
3473         do_facet mgs lctl pool_remove $1 $ost
3474     done
3475     do_facet mgs lctl pool_destroy $1
3476 }
3477
3478 # <fsname>.<poolname> or <poolname>
3479 destroy_pool() {
3480     local fsname=${1%%.*}
3481     local poolname=${1##$fsname.}
3482
3483     [[ x$fsname = x$poolname ]] && fsname=$FSNAME
3484
3485     local RC
3486
3487     pool_list $fsname.$poolname || return $?
3488
3489     destroy_pool_int $fsname.$poolname
3490     RC=$?
3491     [[ $RC -ne 0 ]] && return $RC
3492
3493     wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
3494       2>/dev/null || echo foo" "foo" || RC=1
3495
3496     if [[ $RC -eq 0 ]]; then
3497         remove_pool_from_list $fsname.$poolname
3498     else
3499         error "destroy pool failed $1"
3500     fi
3501     return $RC
3502 }
3503
3504 destroy_pools () {
3505     local fsname=${1:-$FSNAME}
3506     local poolname
3507     local listvar=${fsname}_CREATED_POOLS
3508
3509     pool_list $fsname
3510
3511     [ x${!listvar} = x ] && return 0
3512
3513     echo destroy the created pools: ${!listvar}
3514     for poolname in ${!listvar//,/ }; do
3515         destroy_pool $fsname.$poolname 
3516     done
3517 }
3518
3519 cleanup_pools () {
3520     local fsname=${1:-$FSNAME}
3521     trap 0
3522     destroy_pools $fsname
3523 }
3524
3525 gather_logs () {
3526     local list=$1
3527
3528     local ts=$(date +%s)
3529
3530     # bug 20237, comment 11
3531     # It would also be useful to provide the option
3532     # of writing the file to an NFS directory so it doesn't need to be copied.
3533     local tmp=$TMP
3534     local docp=true
3535     [ -f $LOGDIR/shared ] && docp=false
3536  
3537     # dump lustre logs, dmesg
3538
3539     prefix="$LOGDIR/${TESTSUITE}.${TESTNAME}"
3540     suffix="$ts.log"
3541     echo "Dumping lctl log to ${prefix}.*.${suffix}"
3542
3543     if [ "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
3544         echo "Dumping logs only on local client."
3545         $LCTL dk > ${prefix}.debug_log.$(hostname).${suffix}
3546         dmesg > ${prefix}.dmesg.$(hostname).${suffix}
3547         return
3548     fi
3549
3550     do_nodesv $list \
3551         "$LCTL dk > ${prefix}.debug_log.\\\$(hostname).${suffix};
3552          dmesg > ${prefix}.dmesg.\\\$(hostname).${suffix}"
3553     if [ ! -f $LOGDIR/shared ]; then
3554         do_nodes $list rsync -az "${prefix}.*.${suffix}" $HOSTNAME:$LOGDIR
3555       fi
3556
3557     local archive=$LOGDIR/${TESTSUITE}-$ts.tar.bz2
3558     tar -jcf $archive $LOGDIR/*$ts* $LOGDIR/*${TESTSUITE}*
3559
3560     echo $archive
3561 }
3562
3563 cleanup_logs () {
3564     local list=${1:-$(comma_list $(nodes_list))}
3565
3566     [ -n ${TESTSUITE} ] && do_nodes $list "rm -f $TMP/*${TESTSUITE}*" || true
3567 }
3568
3569 do_ls () {
3570     local mntpt_root=$1
3571     local num_mntpts=$2
3572     local dir=$3
3573     local i
3574     local cmd
3575     local pids
3576     local rc=0
3577
3578     for i in $(seq 0 $num_mntpts); do
3579         cmd="ls -laf ${mntpt_root}$i/$dir"
3580         echo + $cmd;
3581         $cmd > /dev/null &
3582         pids="$pids $!"
3583     done
3584     echo pids=$pids
3585     for pid in $pids; do
3586         wait $pid || rc=$?
3587     done
3588
3589     return $rc
3590 }
3591
3592 get_clients_mount_count () {
3593     local clients=${CLIENTS:-`hostname`}
3594
3595     # we need to take into account the clients mounts and
3596     # exclude mds/ost mounts if any;
3597     do_nodes $clients cat /proc/mounts | grep lustre | grep $MOUNT | wc -l
3598 }
3599
3600 # gss functions
3601 PROC_CLI="srpc_info"
3602
3603 combination()
3604 {
3605     local M=$1
3606     local N=$2
3607     local R=1
3608
3609     if [ $M -lt $N ]; then
3610         R=0
3611     else
3612         N=$((N + 1))
3613         while [ $N -le $M ]; do
3614             R=$((R * N))
3615             N=$((N + 1))
3616         done
3617     fi
3618
3619     echo $R
3620     return 0
3621 }
3622
3623 calc_connection_cnt() {
3624     local dir=$1
3625
3626     # MDT->MDT = 2 * C(M, 2)
3627     # MDT->OST = M * O
3628     # CLI->OST = C * O
3629     # CLI->MDT = C * M
3630     comb_m2=$(combination $MDSCOUNT 2)
3631
3632     local num_clients=$(get_clients_mount_count)
3633
3634     local cnt_mdt2mdt=$((comb_m2 * 2))
3635     local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
3636     local cnt_cli2ost=$((num_clients * OSTCOUNT))
3637     local cnt_cli2mdt=$((num_clients * MDSCOUNT))
3638     local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
3639     local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
3640     local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt + cnt_cli2ost + cnt_cli2mdt))
3641
3642     local var=cnt_$dir
3643     local res=${!var}
3644
3645     echo $res
3646 }
3647
3648 set_rule()
3649 {
3650     local tgt=$1
3651     local net=$2
3652     local dir=$3
3653     local flavor=$4
3654     local cmd="$tgt.srpc.flavor"
3655
3656     if [ $net == "any" ]; then
3657         net="default"
3658     fi
3659     cmd="$cmd.$net"
3660
3661     if [ $dir != "any" ]; then
3662         cmd="$cmd.$dir"
3663     fi
3664
3665     cmd="$cmd=$flavor"
3666     log "Setting sptlrpc rule: $cmd"
3667     do_facet mgs "$LCTL conf_param $cmd"
3668 }
3669
3670 count_flvr()
3671 {
3672     local output=$1
3673     local flavor=$2
3674     local count=0
3675
3676     rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
3677     bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
3678
3679     count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
3680
3681     if [ "x$bulkspec" != "x" ]; then
3682         algs=`echo $bulkspec | awk -F : '{ print $2 }'`
3683
3684         if [ "x$algs" != "x" ]; then
3685             bulk_count=`echo "$output" | grep "bulk flavor" | grep $algs | wc -l`
3686         else
3687             bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
3688             if [ $bulk == "bulkn" ]; then
3689                 bulk_count=`echo "$output" | grep "bulk flavor" \
3690                             | grep "null/null" | wc -l`
3691             elif [ $bulk == "bulki" ]; then
3692                 bulk_count=`echo "$output" | grep "bulk flavor" \
3693                             | grep "/null" | grep -v "null/" | wc -l`
3694             else
3695                 bulk_count=`echo "$output" | grep "bulk flavor" \
3696                             | grep -v "/null" | grep -v "null/" | wc -l`
3697             fi
3698         fi
3699
3700         [ $bulk_count -lt $count ] && count=$bulk_count
3701     fi
3702
3703     echo $count
3704 }
3705
3706 flvr_cnt_cli2mdt()
3707 {
3708     local flavor=$1
3709     local cnt
3710
3711     local clients=${CLIENTS:-`hostname`}
3712
3713     for c in ${clients//,/ }; do
3714         output=`do_node $c lctl get_param -n mdc.*-MDT*-mdc-*.$PROC_CLI 2>/dev/null`
3715         tmpcnt=`count_flvr "$output" $flavor`
3716         cnt=$((cnt + tmpcnt))
3717     done
3718     echo $cnt
3719 }
3720
3721 flvr_cnt_cli2ost()
3722 {
3723     local flavor=$1
3724     local cnt
3725
3726     local clients=${CLIENTS:-`hostname`}
3727
3728     for c in ${clients//,/ }; do
3729         output=`do_node $c lctl get_param -n osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null`
3730         tmpcnt=`count_flvr "$output" $flavor`
3731         cnt=$((cnt + tmpcnt))
3732     done
3733     echo $cnt
3734 }
3735
3736 flvr_cnt_mdt2mdt()
3737 {
3738     local flavor=$1
3739     local cnt=0
3740
3741     if [ $MDSCOUNT -le 1 ]; then
3742         echo 0
3743         return
3744     fi
3745
3746     for num in `seq $MDSCOUNT`; do
3747         output=`do_facet mds$num lctl get_param -n mdc.*-MDT*-mdc[0-9]*.$PROC_CLI 2>/dev/null`
3748         tmpcnt=`count_flvr "$output" $flavor`
3749         cnt=$((cnt + tmpcnt))
3750     done
3751     echo $cnt;
3752 }
3753
3754 flvr_cnt_mdt2ost()
3755 {
3756     local flavor=$1
3757     local cnt=0
3758
3759     for num in `seq $MDSCOUNT`; do
3760         output=`do_facet mds$num lctl get_param -n osc.*OST*-osc-MDT*.$PROC_CLI 2>/dev/null`
3761         tmpcnt=`count_flvr "$output" $flavor`
3762         cnt=$((cnt + tmpcnt))
3763     done
3764     echo $cnt;
3765 }
3766
3767 flvr_cnt_mgc2mgs()
3768 {
3769     local flavor=$1
3770
3771     output=`do_facet client lctl get_param -n mgc.*.$PROC_CLI 2>/dev/null`
3772     count_flvr "$output" $flavor
3773 }
3774
3775 do_check_flavor()
3776 {
3777     local dir=$1        # from to
3778     local flavor=$2     # flavor expected
3779     local res=0
3780
3781     if [ $dir == "cli2mdt" ]; then
3782         res=`flvr_cnt_cli2mdt $flavor`
3783     elif [ $dir == "cli2ost" ]; then
3784         res=`flvr_cnt_cli2ost $flavor`
3785     elif [ $dir == "mdt2mdt" ]; then
3786         res=`flvr_cnt_mdt2mdt $flavor`
3787     elif [ $dir == "mdt2ost" ]; then
3788         res=`flvr_cnt_mdt2ost $flavor`
3789     elif [ $dir == "all2ost" ]; then
3790         res1=`flvr_cnt_mdt2ost $flavor`
3791         res2=`flvr_cnt_cli2ost $flavor`
3792         res=$((res1 + res2))
3793     elif [ $dir == "all2mdt" ]; then
3794         res1=`flvr_cnt_mdt2mdt $flavor`
3795         res2=`flvr_cnt_cli2mdt $flavor`
3796         res=$((res1 + res2))
3797     elif [ $dir == "all2all" ]; then
3798         res1=`flvr_cnt_mdt2ost $flavor`
3799         res2=`flvr_cnt_cli2ost $flavor`
3800         res3=`flvr_cnt_mdt2mdt $flavor`
3801         res4=`flvr_cnt_cli2mdt $flavor`
3802         res=$((res1 + res2 + res3 + res4))
3803     fi
3804
3805     echo $res
3806 }
3807
3808 wait_flavor()
3809 {
3810     local dir=$1        # from to
3811     local flavor=$2     # flavor expected
3812     local expect=${3:-$(calc_connection_cnt $dir)}     # number expected
3813
3814     local res=0
3815
3816     for ((i=0;i<20;i++)); do
3817         echo -n "checking..."
3818         res=$(do_check_flavor $dir $flavor)
3819         if [ $res -eq $expect ]; then
3820             echo "found $res $flavor connections of $dir, OK"
3821             return 0
3822         else
3823             echo "found $res $flavor connections of $dir, not ready ($expect)"
3824             sleep 4
3825         fi
3826     done
3827
3828     echo "Error checking $flavor of $dir: expect $expect, actual $res"
3829     return 1
3830 }
3831
3832 restore_to_default_flavor()
3833 {
3834     local proc="mgs.MGS.live.$FSNAME"
3835
3836     echo "restoring to default flavor..."
3837
3838     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
3839
3840     # remove all existing rules if any
3841     if [ $nrule -ne 0 ]; then
3842         echo "$nrule existing rules"
3843         for rule in `do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor."`; do
3844             echo "remove rule: $rule"
3845             spec=`echo $rule | awk -F = '{print $1}'`
3846             do_facet mgs "$LCTL conf_param $spec="
3847         done
3848     fi
3849
3850     # verify no rules left
3851     nrule=`do_facet mgs lctl get_param -n $proc 2>/dev/null | grep ".srpc.flavor." | wc -l`
3852     [ $nrule -ne 0 ] && error "still $nrule rules left"
3853
3854     # wait for default flavor to be applied
3855     # currently default flavor for all connections are 'null'
3856     wait_flavor all2all null
3857     echo "now at default flavor settings"
3858 }
3859
3860 set_flavor_all()
3861 {
3862     local flavor=${1:-null}
3863
3864     echo "setting all flavor to $flavor"
3865
3866     # FIXME need parameter to this fn
3867     # and remove global vars
3868     local cnt_all2all=$(calc_connection_cnt all2all)
3869
3870     local res=$(do_check_flavor all2all $flavor)
3871     if [ $res -eq $cnt_all2all ]; then
3872         echo "already have total $res $flavor connections"
3873         return
3874     fi
3875
3876     echo "found $res $flavor out of total $cnt_all2all connections"
3877     restore_to_default_flavor
3878
3879     [[ $flavor = null ]] && return 0
3880
3881     set_rule $FSNAME any any $flavor
3882     wait_flavor all2all $flavor
3883 }
3884
3885
3886 check_logdir() {
3887     local dir=$1
3888     # Checking for shared logdir
3889     if [ ! -d $dir ]; then
3890         # Not found. Create local logdir
3891         mkdir -p $dir
3892     else
3893         touch $dir/node.$(hostname).yml
3894     fi
3895     return 0
3896 }
3897
3898 check_write_access() {
3899     local dir=$1
3900     for node in $(nodes_list); do
3901         if [ ! -f "$dir/node.${node}.yml" ]; then
3902             # Logdir not accessible/writable from this node.
3903             return 1
3904         fi
3905     done
3906     return 0
3907 }
3908
3909 init_logging() {
3910     if [[ -n $YAML_LOG ]]; then
3911         return
3912     fi
3913     export YAML_LOG=${LOGDIR}/results.yml
3914     mkdir -p $LOGDIR
3915     init_clients_lists
3916
3917     do_rpc_nodes $(comma_list $(nodes_list)) check_logdir $LOGDIR
3918     if check_write_access $LOGDIR; then
3919         touch $LOGDIR/shared
3920         echo "Logging to shared log directory: $LOGDIR"
3921     else
3922         echo "Logging to local directory: $LOGDIR"
3923     fi
3924
3925     yml_nodes_file $LOGDIR
3926     yml_results_file >> $YAML_LOG
3927 }
3928
3929 log_test() {
3930     yml_log_test $1 >> $YAML_LOG
3931 }
3932
3933 log_sub_test() {
3934     yml_log_sub_test $@ >> $YAML_LOG
3935 }
3936
3937 run_llverdev()
3938 {
3939         local dev=$1
3940         local devname=$(basename $1)
3941         local size=$(grep "$devname"$ /proc/partitions | awk '{print $3}')
3942         size=$(($size / 1024 / 1024)) # Gb
3943
3944         local partial_arg=""
3945         # Run in partial (fast) mode if the size
3946         # of a partition > 10 GB
3947         [ $size -gt 10 ] && partial_arg="-p"
3948
3949         llverdev --force $partial_arg $dev
3950 }