Whamcloud - gitweb
63d85018f9947579431ba1c7ca980bb40b9e89ed
[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 PDSH="pdsh -S -Rssh -w"
15
16 # eg, assert_env LUSTRE MDSNODES OSTNODES CLIENTS
17 assert_env() {
18     local failed=""
19     for name in $@; do
20         if [ -z "${!name}" ]; then
21             echo "$0: $name must be set"
22             failed=1
23         fi
24     done
25     [ $failed ] && exit 1 || true
26 }
27
28 assert_DIR () {
29     local failed=""
30     [[ $DIR/ = $MOUNT/* ]] || \
31         { failed=1 && echo "DIR=$DIR not in $MOUNT. Aborting."; }
32     [[ $DIR1/ = $MOUNT1/* ]] || \
33         { failed=1 && echo "DIR1=$DIR1 not in $MOUNT1. Aborting."; }
34     [[ $DIR2/ = $MOUNT2/* ]] || \
35         { failed=1 && echo "DIR2=$DIR2 not in $MOUNT2. Aborting"; }
36
37     [ -n "$failed" ] && exit 99 || true
38 }
39
40 usage() {
41     echo "usage: $0 [-r] [-f cfgfile]"
42     echo "       -r: reformat"
43
44     exit
45 }
46
47 print_summary () {
48     [ "$TESTSUITE" == "lfscktest" ] && return 0
49     [ -n "$ONLY" ] && echo "WARNING: ONLY is set to ${ONLY}."
50     local form="%-13s %-17s %s\n"
51     printf "$form" "status" "script" "skipped tests E(xcluded) S(low)"
52     echo "------------------------------------------------------------------------------------"
53     for O in $TESTSUITE_LIST; do
54         local skipped=""
55         local slow=""
56         local o=$(echo $O | tr "[:upper:]" "[:lower:]")
57         o=${o//_/-}
58         o=${o//tyn/tyN}
59         local log=${TMP}/${o}.log
60         [ -f $log ] && skipped=$(grep excluded $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
61         [ -f $log ] && slow=$(grep SLOW $log | awk '{ printf " %s", $3 }' | sed 's/test_//g')
62         [ "${!O}" = "done" ] && \
63             printf "$form" "Done" "$O" "E=$skipped" && \
64             [ -n "$slow" ] && printf "$form" "-" "-" "S=$slow"
65
66     done
67
68     for O in $TESTSUITE_LIST; do
69         [ "${!O}" = "no" ] && \
70             printf "$form" "Skipped" "$O" ""
71     done
72
73     for O in $TESTSUITE_LIST; do
74         [ "${!O}" = "done" -o "${!O}" = "no" ] || \
75             printf "$form" "UNFINISHED" "$O" ""
76     done
77 }
78
79 init_test_env() {
80     export LUSTRE=`absolute_path $LUSTRE`
81     export TESTSUITE=`basename $0 .sh`
82     export TEST_FAILED=false
83
84     export MKE2FS=${MKE2FS:-mke2fs}
85     export DEBUGFS=${DEBUGFS:-debugfs}
86     export TUNE2FS=${TUNE2FS:-tune2fs}
87     export E2LABEL=${E2LABEL:-e2label}
88     export DUMPE2FS=${DUMPE2FS:-dumpe2fs}
89     export E2FSCK=${E2FSCK:-e2fsck}
90
91     #[ -d /r ] && export ROOT=${ROOT:-/r}
92     export TMP=${TMP:-$ROOT/tmp}
93     export TESTSUITELOG=${TMP}/${TESTSUITE}.log
94     export HOSTNAME=${HOSTNAME:-`hostname`}
95     if ! echo $PATH | grep -q $LUSTRE/utils; then
96         export PATH=$PATH:$LUSTRE/utils
97     fi
98     if ! echo $PATH | grep -q $LUSTRE/test; then
99         export PATH=$PATH:$LUSTRE/tests
100     fi
101     export MDSRATE=${MDSRATE:-"$LUSTRE/tests/mdsrate"}
102     [ ! -f "$MDSRATE" ] && export MDSRATE=$(which mdsrate 2> /dev/null)
103     if ! echo $PATH | grep -q $LUSTRE/tests/racer; then
104         export PATH=$PATH:$LUSTRE/tests/racer
105     fi
106     export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
107     export LFS=${LFS:-"$LUSTRE/utils/lfs"}
108     [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
109     export LFS=${LFS:-"$LUSTRE/utils/lfs"}
110     [ ! -f "$LFS" ] && export LFS=$(which lfs)
111     export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
112     [ ! -f "$MKFS" ] && export MKFS=$(which mkfs.lustre)
113     export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
114     [ ! -f "$TUNEFS" ] && export TUNEFS=$(which tunefs.lustre)
115     export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
116     export FSTYPE=${FSTYPE:-"ldiskfs"}
117     export NAME=${NAME:-local}
118     export DIR2
119     export AT_MAX_PATH
120     export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
121
122     if [ "$ACCEPTOR_PORT" ]; then
123         export PORT_OPT="--port $ACCEPTOR_PORT"
124     fi
125
126     # Paths on remote nodes, if different
127     export RLUSTRE=${RLUSTRE:-$LUSTRE}
128     export RPWD=${RPWD:-$PWD}
129     export I_MOUNTED=${I_MOUNTED:-"no"}
130
131     # command line
132
133     while getopts "rvwf:" opt $*; do
134         case $opt in
135             f) CONFIG=$OPTARG;;
136             r) REFORMAT=--reformat;;
137             v) VERBOSE=true;;
138             w) WRITECONF=writeconf;;
139             \?) usage;;
140         esac
141     done
142
143     shift $((OPTIND - 1))
144     ONLY=${ONLY:-$*}
145
146     [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
147     rm -f $TMP/*active
148
149 }
150
151 case `uname -r` in
152     *) EXT=".ko"; USE_QUOTA=yes;;
153 esac
154
155 load_module() {
156     module=$1
157     shift
158     BASE=`basename $module $EXT`
159     lsmod | grep -q ${BASE} || \
160       if [ -f ${LUSTRE}/${module}${EXT} ]; then
161         insmod ${LUSTRE}/${module}${EXT} $@
162     else
163         # must be testing a "make install" or "rpm" installation
164         modprobe $BASE $@
165     fi
166 }
167
168 load_modules() {
169     if [ -n "$MODPROBE" ]; then
170         # use modprobe
171     return 0
172     fi
173     if [ "$HAVE_MODULES" = true ]; then
174     # we already loaded
175         return 0
176     fi
177     HAVE_MODULES=true
178
179     echo Loading modules from $LUSTRE
180     load_module ../lnet/libcfs/libcfs
181     [ "$PTLDEBUG" ] && lctl set_param debug=$PTLDEBUG
182     [ "$SUBSYSTEM" ] && lctl set_param subsystem_debug=${SUBSYSTEM# }
183     local MODPROBECONF=
184     [ -f /etc/modprobe.conf ] && MODPROBECONF=/etc/modprobe.conf
185     [ ! "$MODPROBECONF" -a -d /etc/modprobe.d ] && MODPROBECONF=/etc/modprobe.d/Lustre
186     [ -z "$LNETOPTS" -a "$MODPROBECONF" ] && \
187         LNETOPTS=$(awk '/^options lnet/ { print $0}' $MODPROBECONF | sed 's/^options lnet //g')
188     echo $LNETOPTS | grep -q "accept=all"  || LNETOPTS="$LNETOPTS accept=all";
189     echo "lnet options: '$LNETOPTS'"
190     # note that insmod will ignore anything in modprobe.conf
191     load_module ../lnet/lnet/lnet $LNETOPTS
192     LNETLND=${LNETLND:-"socklnd/ksocklnd"}
193     load_module ../lnet/klnds/$LNETLND
194     load_module lvfs/lvfs
195     load_module obdclass/obdclass
196     load_module ptlrpc/ptlrpc
197     [ "$USE_QUOTA" = "yes" ] && load_module quota/lquota
198     load_module mdc/mdc
199     load_module osc/osc
200     load_module lov/lov
201     load_module mgc/mgc
202     if [ -z "$CLIENTONLY" ] && [ -z "$CLIENTMODSONLY" ]; then
203         load_module mgs/mgs
204         load_module mds/mds
205         grep -q crc16 /proc/kallsyms || { modprobe crc16 2>/dev/null || true; }
206         grep -q jbd /proc/kallsyms || { modprobe jbd 2>/dev/null || true; }
207         [ "$FSTYPE" = "ldiskfs" ] && load_module ../ldiskfs/ldiskfs/ldiskfs
208         load_module lvfs/fsfilt_$FSTYPE
209         load_module ost/ost
210         load_module obdfilter/obdfilter
211     fi
212
213     load_module llite/lustre
214     load_module llite/llite_lloop
215     rm -f $TMP/ogdb-$HOSTNAME
216     OGDB=$TMP
217     [ -d /r ] && OGDB="/r/tmp"
218     $LCTL modules > $OGDB/ogdb-$HOSTNAME
219     # 'mount' doesn't look in $PATH, just sbin
220     [ -f $LUSTRE/utils/mount.lustre ] && cp $LUSTRE/utils/mount.lustre /sbin/. || true
221 }
222
223 RMMOD=rmmod
224 if [ `uname -r | cut -c 3` -eq 4 ]; then
225     RMMOD="modprobe -r"
226 fi
227
228 wait_for_lnet() {
229     local UNLOADED=0
230     local WAIT=0
231     local MAX=60
232     MODULES=$($LCTL modules | awk '{ print $2 }')
233     while [ -n "$MODULES" ]; do
234     sleep 5
235     $RMMOD $MODULES >/dev/null 2>&1 || true
236     MODULES=$($LCTL modules | awk '{ print $2 }')
237         if [ -z "$MODULES" ]; then
238         return 0
239         else
240             WAIT=$((WAIT + 5))
241             echo "waiting, $((MAX - WAIT)) secs left"
242         fi
243         if [ $WAIT -eq $MAX ]; then
244             echo "LNET modules $MODULES will not unload"
245         lsmod
246             return 3
247         fi
248     done
249 }
250
251 unload_dep_module() {
252     #lsmod output
253     #libcfs                107852  17 llite_lloop,lustre,obdfilter,ost,...
254     local MODULE=$1
255     local DEPS=$(lsmod | awk '($1 == "'$MODULE'") { print $4 }' | tr ',' ' ')
256     for SUBMOD in $DEPS; do
257         unload_dep_module $SUBMOD
258     done
259     [ "$MODULE" = "libcfs" ] && $LCTL dk $TMP/debug || true
260     $RMMOD $MODULE || true
261 }
262
263 check_mem_leak () {
264     LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
265     LEAK_PORTALS=$(dmesg | tail -n 20 | grep "Portals memory leaked" || true)
266     if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
267         echo "$LEAK_LUSTRE" 1>&2
268         echo "$LEAK_PORTALS" 1>&2
269         mv $TMP/debug $TMP/debug-leak.`date +%s` || true
270         echo "Memory leaks detected"
271         [ -n "$IGNORE_LEAK" ] && { echo "ignoring leaks" && return 0; } || true
272         return 1
273     fi
274 }
275
276 unload_modules() {
277     wait_exit_ST client # bug 12845
278
279     lsmod | grep libcfs > /dev/null && $LCTL dl
280     [ -z "$CLIENTONLY" ] && unload_dep_module $FSTYPE
281     unload_dep_module libcfs
282
283     local MODULES=$($LCTL modules | awk '{ print $2 }')
284     if [ -n "$MODULES" ]; then
285         echo "Modules still loaded: "
286         echo $MODULES
287         if [ "$(lctl dl)" ]; then
288             echo "Lustre still loaded"
289             lctl dl || true
290             lsmod
291             return 2
292         else
293             echo "Lustre stopped but LNET is still loaded, waiting..."
294             wait_for_lnet || return 3
295         fi
296     fi
297     HAVE_MODULES=false
298
299     check_mem_leak || return 254
300
301     echo "modules unloaded."
302     return 0
303 }
304
305 # Facet functions
306 mount_facet() {
307     local facet=$1
308     shift
309     local dev=${facet}_dev
310     local opt=${facet}_opt
311     echo "Starting ${facet}: ${!opt} $@ ${!dev} ${MOUNT%/*}/${facet}"
312     do_facet ${facet} mount -t lustre ${!opt} $@ ${!dev} ${MOUNT%/*}/${facet}
313     RC=${PIPESTATUS[0]}
314     if [ $RC -ne 0 ]; then
315         echo "mount -t lustre $@ ${!dev} ${MOUNT%/*}/${facet}"
316         echo "Start of ${!dev} on ${facet} failed ${RC}"
317     else
318         do_facet ${facet} "lctl set_param debug=$PTLDEBUG; \
319             lctl set_param subsystem_debug=${SUBSYSTEM# }; \
320             lctl set_param debug_mb=${DEBUG_SIZE}; \
321             sync"
322
323         label=$(do_facet ${facet} "$E2LABEL ${!dev}")
324         [ -z "$label" ] && echo no label for ${!dev} && exit 1
325         eval export ${facet}_svc=${label}
326         echo Started ${label}
327     fi
328     return $RC
329 }
330
331 # start facet device options
332 start() {
333     facet=$1
334     shift
335     device=$1
336     shift
337     eval export ${facet}_dev=${device}
338     eval export ${facet}_opt=\"$@\"
339     do_facet ${facet} mkdir -p ${MOUNT%/*}/${facet}
340     mount_facet ${facet}
341     RC=$?
342     return $RC
343 }
344
345 stop() {
346     local running
347     facet=$1
348     shift
349     HOST=`facet_active_host $facet`
350     [ -z $HOST ] && echo stop: no host for $facet && return 0
351
352     running=$(do_facet ${facet} "grep -c ${MOUNT%/*}/${facet}' ' /proc/mounts") || true
353     if [ ${running} -ne 0 ]; then
354         echo "Stopping ${MOUNT%/*}/${facet} (opts:$@)"
355         do_facet ${facet} umount -d $@ ${MOUNT%/*}/${facet}
356     fi
357
358     # umount should block, but we should wait for unrelated obd's
359     # like the MGS or MGC to also stop.
360
361     wait_exit_ST ${facet}
362 }
363
364 zconf_mount() {
365     local OPTIONS
366     local client=$1
367     local mnt=$2
368     # Only supply -o to mount if we have options
369     if [ -n "$MOUNTOPT" ]; then
370         OPTIONS="-o $MOUNTOPT"
371     fi
372     local device=$MGSNID:/$FSNAME
373     if [ -z "$mnt" -o -z "$FSNAME" ]; then
374         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
375         exit 1
376     fi
377
378     echo "Starting client: $client: $OPTIONS $device $mnt"
379     do_node $client mkdir -p $mnt
380     do_node $client mount -t lustre $OPTIONS $device $mnt || return 1
381     do_node $client "lctl set_param debug=$PTLDEBUG;
382         lctl set_param subsystem_debug=${SUBSYSTEM# };
383         lctl set_param debug_mb=${DEBUG_SIZE}"
384
385     return 0
386 }
387
388 zconf_umount() {
389     local client=$1
390     local mnt=$2
391     local force
392     local busy 
393     local need_kill
394
395     [ "$3" ] && force=-f
396     local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
397     if [ $running -ne 0 ]; then
398         echo "Stopping client $client $mnt (opts:$force)"
399         do_node $client lsof -t $mnt || need_kill=no
400         if [ "x$force" != "x" -a "x$need_kill" != "xno" ]; then
401             pids=$(do_node $client lsof -t $mnt | sort -u);
402             if [ -n $pids ]; then
403                 do_node $client kill -9 $pids || true
404             fi
405         fi
406
407         busy=$(do_node $client "umount $force $mnt 2>&1" | grep -c "busy") || true
408         if [ $busy -ne 0 ] ; then
409             echo "$mnt is still busy, wait one second" && sleep 1
410             do_node $client umount $force $mnt
411         fi
412     fi
413 }
414
415 # mount clients if not mouted
416 zconf_mount_clients() {
417     local OPTIONS
418     local clients=$1
419     local mnt=$2
420
421     # Only supply -o to mount if we have options
422     if [ -n "$MOUNTOPT" ]; then
423         OPTIONS="-o $MOUNTOPT"
424     fi
425     local device=$MGSNID:/$FSNAME
426     if [ -z "$mnt" -o -z "$FSNAME" ]; then
427         echo Bad zconf mount command: opt=$OPTIONS dev=$device mnt=$mnt
428         exit 1
429     fi
430
431     echo "Starting client $clients: $OPTIONS $device $mnt"
432     do_nodes $clients "mount | grep $mnt || { mkdir -p $mnt && mount -t lustre $OPTIONS $device $mnt || false; }"
433
434     echo "Started clients $clients: "
435     do_nodes $clients "mount | grep $mnt"
436
437     do_nodes $clients "sysctl -w lnet.debug=$PTLDEBUG;
438         sysctl -w lnet.subsystem_debug=${SUBSYSTEM# };
439         sysctl -w lnet.debug_mb=${DEBUG_SIZE};"
440
441     return 0
442 }
443
444 zconf_umount_clients() {
445     local clients=$1
446     local mnt=$2
447     local force
448
449     [ "$3" ] && force=-f
450
451     echo "Stopping clients: $clients $mnt (opts:$force)"
452     do_nodes $clients "set -x; running=\\\$(grep -c $mnt' ' /proc/mounts)
453 if [ \\\$running -ne 0 ] ; then
454 echo Stopping client \\\$(hostname) client $mnt opts:$force
455 lsof -t $mnt || need_kill=no
456 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
457     pids=\\\$(lsof -t $mnt | sort -u);
458     if [ -n \\\"\\\$pids\\\" ]; then
459              kill -9 \\\$pids
460     fi
461 fi
462 busy=\\\$(umount $force $mnt 2>&1 | grep -c "busy")
463 if [ \\\$busy -ne 0 ] ; then
464     echo "$mnt is still busy, wait one second" && sleep 1
465     umount $force $mnt
466 fi
467 fi"
468 }
469
470 shudown_node_hard () {
471     local host=$1
472     local attempts=3
473
474     for i in $(seq $attempts) ; do
475         $POWER_DOWN $host
476         sleep 1
477         ping -w 3 -c 1 $host > /dev/null 2>&1 || return 0
478         echo "waiting for $host to fail attempts=$attempts"
479         [ $i -lt $attempts ] || \
480             { echo "$host still pingable after power down! attempts=$attempts" && return 1; } 
481     done
482 }
483
484 shutdown_client() {
485     local client=$1
486     local mnt=${2:-$MOUNT}
487     local attempts=3
488
489     if [ "$FAILURE_MODE" = HARD ]; then
490         shudown_node_hard $client 
491     else
492        zconf_umount_clients $client $mnt -f
493     fi
494 }
495
496 shutdown_facet() {
497     local facet=$1
498     if [ "$FAILURE_MODE" = HARD ]; then
499         shudown_node_hard $(facet_active_host $facet)
500     elif [ "$FAILURE_MODE" = SOFT ]; then
501         stop $facet
502     fi
503 }
504
505 reboot_facet() {
506     facet=$1
507     if [ "$FAILURE_MODE" = HARD ]; then
508         $POWER_UP `facet_active_host $facet`
509     else
510         sleep 10
511     fi
512 }
513
514 boot_node() {
515     local node=$1
516     if [ "$FAILURE_MODE" = HARD ]; then
517        $POWER_UP $node
518     fi
519 }
520
521 # recovery-scale functions
522 check_progs_installed () {
523     local clients=$1
524     shift
525     local progs=$@
526
527     do_nodes $clients "set -x ; PATH=:$PATH status=true; for prog in $progs; do
528         which \\\$prog || { echo \\\$prog missing on \\\$(hostname) && status=false; }
529         done;
530         eval \\\$status"
531 }
532
533 start_client_load() {
534     local client=$1
535     local var=${client}_load
536
537     do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
538                               BREAK_ON_ERROR=$BREAK_ON_ERROR \
539                               END_RUN_FILE=$END_RUN_FILE \
540                               LOAD_PID_FILE=$LOAD_PID_FILE \
541                               TESTSUITELOG=$TESTSUITELOG \
542                               run_${!var}.sh" &
543     CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $!"
544     log "Started client load: ${!var} on $client"
545
546     return 0
547 }
548
549 start_client_loads () {
550     local clients=(${1//,/ })
551     local numloads=${#CLIENT_LOADS[@]}
552     local testnum
553
554     for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
555         testnum=$((nodenum % numloads))
556         eval export ${clients[nodenum]}_load=${CLIENT_LOADS[testnum]}
557         start_client_load ${clients[nodenum]}
558     done
559 }
560
561 # only for remote client 
562 check_client_load () {
563     local client=$1
564     local var=${client}_load
565
566     local TESTLOAD=run_${!var}.sh
567
568     ps auxww | grep -v grep | grep $client | grep -q "$TESTLOAD" || return 1
569
570     check_catastrophe $client || return 2
571
572     # see if the load is still on the client
573     local tries=3
574     local RC=254
575     while [ $RC = 254 -a $tries -gt 0 ]; do
576         let tries=$tries-1
577         # assume success
578         RC=0
579         if ! do_node $client "ps auxwww | grep -v grep | grep -q $TESTLOAD"; then
580             RC=${PIPESTATUS[0]}
581             sleep 30
582         fi
583     done
584     if [ $RC = 254 ]; then
585         echo "got a return status of $RC from do_node while checking (i.e. with 'ps') the client load on the remote system"
586         # see if we can diagnose a bit why this is
587     fi
588
589     return $RC
590 }
591 check_client_loads () {
592    local clients=${1//,/ }
593    local client=
594    local rc=0
595
596    for client in $clients; do
597       check_client_load $client
598       rc=${PIPESTATUS[0]}
599       if [ "$rc" != 0 ]; then
600         log "Client load failed on node $client, rc=$rc"
601         return $rc
602       fi
603    done
604 }
605
606 restart_client_loads () {
607     local clients=${1//,/ }
608     local expectedfail=${2:-""}
609     local client=
610     local rc=0
611
612     for client in $clients; do
613         check_client_load $client
614         rc=${PIPESTATUS[0]}
615         if [ "$rc" != 0 -a "$expectedfail" ]; then
616             start_client_load $client
617             echo "Restarted client load: on $client. Checking ..."
618             check_client_load $client 
619             rc=${PIPESTATUS[0]}
620             if [ "$rc" != 0 ]; then
621                 log "Client load failed to restart on node $client, rc=$rc"
622                 # failure one client load means test fail
623                 # we do not need to check other 
624                 return $rc
625             fi
626         else
627             return $rc
628         fi
629     done
630 }
631 # End recovery-scale functions
632
633 # verify that lustre actually cleaned up properly
634 cleanup_check() {
635     [ -f $CATASTROPHE ] && [ `cat $CATASTROPHE` -ne 0 ] && \
636         error "LBUG/LASSERT detected"
637     BUSY=`dmesg | grep -i destruct || true`
638     if [ "$BUSY" ]; then
639         echo "$BUSY" 1>&2
640         [ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.`date +%s`
641         exit 205
642     fi
643
644     check_mem_leak || exit 204
645
646     [ "`lctl dl 2> /dev/null | wc -l`" -gt 0 ] && lctl dl && \
647         echo "$0: lustre didn't clean up..." 1>&2 && return 202 || true
648
649     if [ "`/sbin/lsmod 2>&1 | egrep 'lnet|libcfs'`" ]; then
650         echo "$0: modules still loaded..." 1>&2
651         /sbin/lsmod 1>&2
652         return 203
653     fi
654     return 0
655 }
656
657 wait_update () {
658     local node=$1
659     local TEST=$2
660     local FINAL=$3
661     local MAX=${4:-90}
662
663         local RESULT
664         local WAIT=0
665         local sleep=5
666         while [ $WAIT -lt $MAX ]; do
667             RESULT=$(do_node $node "$TEST")
668             if [ "$RESULT" == "$FINAL" ]; then
669                 echo "Updated after $WAIT sec: wanted '$FINAL' got '$RESULT'"
670                 return 0
671             fi
672             echo "Waiting $((MAX - WAIT)) secs for update"
673             WAIT=$((WAIT + sleep))
674             sleep $sleep
675         done
676         echo "Update not seen after $MAX sec: wanted '$FINAL' got '$RESULT'"
677         return 3
678 }
679
680 wait_update_facet () {
681     local facet=$1
682     wait_update  $(facet_host $facet) $@
683 }
684
685 wait_delete_completed () {
686     local TOTALPREV=`lctl get_param -n osc.*.kbytesavail | \
687                      awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
688
689     local WAIT=0
690     local MAX_WAIT=20
691     while [ "$WAIT" -ne "$MAX_WAIT" ]; do
692         sleep 1
693         TOTAL=`lctl get_param -n osc.*.kbytesavail | \
694                awk 'BEGIN{total=0}; {total+=$1}; END{print total}'`
695         [ "$TOTAL" -eq "$TOTALPREV" ] && break
696         echo "Waiting delete completed ... prev: $TOTALPREV current: $TOTAL "
697         TOTALPREV=$TOTAL
698         WAIT=$(( WAIT + 1))
699     done
700     echo "Delete completed."
701 }
702
703 wait_for_host() {
704     local host=$1
705     check_network "$host" 900
706     while ! do_node $host "ls -d $LUSTRE " > /dev/null; do sleep 5; done
707 }
708
709 wait_for() {
710     local facet=$1
711     local host=`facet_active_host $facet`
712     wait_for_host $host
713 }
714
715 wait_recovery_complete () {
716     local facet=$1
717
718     # Use default policy if $2 is not passed by caller.
719     #define OBD_RECOVERY_TIMEOUT (obd_timeout * 5 / 2)
720     # as we are in process of changing obd_timeout in different ways
721     # let's set MAX longer than that
722     local MAX=${2:-$(( TIMEOUT * 4 ))}
723  
724     local var_svc=${facet}_svc
725     local procfile="*.${!var_svc}.recovery_status"
726     local WAIT=0
727     local STATUS=
728
729     while [ $WAIT -lt $MAX ]; do
730         STATUS=$(do_facet $facet lctl get_param -n $procfile | grep status)
731         [[ $STATUS = "status: COMPLETE" ]] && return 0
732         sleep 5
733         WAIT=$((WAIT + 5))
734         echo "Waiting $((MAX - WAIT)) secs for $facet recovery done. $STATUS"
735     done
736     echo "$facet recovery not done in $MAX sec. $STATUS"
737     return 1
738 }
739
740 wait_exit_ST () {
741     local facet=$1
742
743     local WAIT=0
744     local INTERVAL=1
745     local running
746     # conf-sanity 31 takes a long time cleanup
747     while [ $WAIT -lt 300 ]; do
748         running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null && lctl dl | grep ' ST '") || true
749         [ -z "${running}" ] && return 0
750         echo "waited $WAIT for${running}"
751         [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
752         sleep $INTERVAL
753         WAIT=$((WAIT + INTERVAL))
754     done
755     echo "service didn't stop after $WAIT seconds.  Still running:"
756     echo ${running}
757     return 1
758 }
759
760 wait_remote_prog () {
761    local prog=$1
762    local WAIT=0
763    local INTERVAL=5
764    local rc=0
765
766    [ "$PDSH" = "no_dsh" ] && return 0
767
768    while [ $WAIT -lt $2 ]; do
769         running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep) || true
770         [ -z "${running}" ] && return 0 || true
771         echo "waited $WAIT for: "
772         echo "$running"
773         [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
774         sleep $INTERVAL
775         WAIT=$((WAIT + INTERVAL))
776     done
777     local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" | grep -v grep | awk '{print $2}')
778     [ -z "$pids" ] && return 0
779     echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
780     for pid in $pids; do
781         cat /proc/${pid}/status || true
782         cat /proc/${pid}/wchan || true
783         echo "Killing $pid"
784         kill -9 $pid || true
785         sleep 1
786         ps -P $pid && rc=1
787     done
788
789     return $rc
790 }
791
792 client_df() {
793     # not every config has many clients
794     if [ -n "$CLIENTS" ]; then
795         $PDSH $CLIENTS "df $MOUNT" > /dev/null
796     else
797         df $MOUNT > /dev/null
798     fi
799 }
800
801 client_reconnect() {
802     uname -n >> $MOUNT/recon
803     if [ -z "$CLIENTS" ]; then
804         df $MOUNT; uname -n >> $MOUNT/recon
805     else
806         do_nodes $CLIENTS "df $MOUNT; uname -n >> $MOUNT/recon" > /dev/null
807     fi
808     echo Connected clients:
809     cat $MOUNT/recon
810     ls -l $MOUNT/recon > /dev/null
811     rm $MOUNT/recon
812 }
813
814 facet_failover() {
815     local facet=$1
816     local sleep_time=$2
817     echo "Failing $facet on node `facet_active_host $facet`"
818     shutdown_facet $facet
819     [ -n "$sleep_time" ] && sleep $sleep_time
820     reboot_facet $facet
821     client_df &
822     DFPID=$!
823     RECOVERY_START_TIME=`date +%s`
824     echo "df pid is $DFPID"
825     change_active $facet
826     local TO=`facet_active_host $facet`
827     echo "Failover $facet to $TO"
828     wait_for $facet
829     mount_facet $facet || error "Restart of $facet failed"
830 }
831
832 obd_name() {
833     local facet=$1
834 }
835
836 replay_barrier() {
837     local facet=$1
838     do_facet $facet sync
839     df $MOUNT
840     local svc=${facet}_svc
841     do_facet $facet $LCTL --device %${!svc} readonly
842     do_facet $facet $LCTL --device %${!svc} notransno
843     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
844     $LCTL mark "local REPLAY BARRIER on ${!svc}"
845 }
846
847 replay_barrier_nodf() {
848     local facet=$1    echo running=${running}
849     do_facet $facet sync
850     local svc=${facet}_svc
851     echo Replay barrier on ${!svc}
852     do_facet $facet $LCTL --device %${!svc} readonly
853     do_facet $facet $LCTL --device %${!svc} notransno
854     do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
855     $LCTL mark "local REPLAY BARRIER on ${!svc}"
856 }
857
858 mds_evict_client() {
859     UUID=`lctl get_param -n mdc.${mds_svc}-mdc-*.uuid`
860     local mdtdevice=$(get_mds_mdt_device_proc_path)
861     do_facet mds "lctl set_param -n ${mdtdevice}.${mds_svc}.evict_client $UUID"
862 }
863
864 ost_evict_client() {
865     UUID=`lctl get_param -n osc.${ost1_svc}-osc-*.uuid`
866     do_facet ost1 "lctl set_param -n obdfilter.${ost1_svc}.evict_client $UUID"
867 }
868
869 fail() {
870     facet_failover $* || error "failover: $?"
871     df $MOUNT || error "post-failover df: $?"
872 }
873
874 fail_nodf() {
875     local facet=$1
876     facet_failover $facet
877 }
878
879 fail_abort() {
880     local facet=$1
881     stop $facet
882     change_active $facet
883     mount_facet $facet -o abort_recovery
884     df $MOUNT || echo "first df failed: $?"
885     sleep 1
886     df $MOUNT || error "post-failover df: $?"
887 }
888
889 do_lmc() {
890     echo There is no lmc.  This is mountconf, baby.
891     exit 1
892 }
893
894 h2gm () {
895     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
896         ID=`$PDSH $1 $GMNALNID -l | cut -d\  -f2`
897         echo $ID"@gm"
898     fi
899 }
900
901 h2name_or_ip() {
902     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
903         echo $1"@$2"
904     fi
905 }
906
907 h2ptl() {
908    if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
909        ID=`xtprocadmin -n $1 2>/dev/null | egrep -v 'NID' | awk '{print $1}'`
910        if [ -z "$ID" ]; then
911            echo "Could not get a ptl id for $1..."
912            exit 1
913        fi
914        echo $ID"@ptl"
915    fi
916 }
917 declare -fx h2ptl
918
919 h2tcp() {
920     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
921         echo $1"@tcp"
922     fi
923 }
924 declare -fx h2tcp
925
926 h2elan() {
927     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
928         if type __h2elan >/dev/null 2>&1; then
929             ID=$(__h2elan $1)
930         else
931             ID=`echo $1 | sed 's/[^0-9]*//g'`
932         fi
933         echo $ID"@elan"
934     fi
935 }
936 declare -fx h2elan
937
938 h2openib() {
939     if [ "$1" = "client" -o "$1" = "'*'" ]; then echo \'*\'; else
940         ID=`echo $1 | sed 's/[^0-9]*//g'`
941         echo $ID"@openib"
942     fi
943 }
944 declare -fx h2openib
945
946 h2o2ib() {
947     h2name_or_ip "$1" "o2ib"
948 }
949 declare -fx h2o2ib
950
951 facet_host() {
952     local facet=$1
953
954     [ "$facet" == client ] && echo -n $HOSTNAME && return
955     varname=${facet}_HOST
956     if [ -z "${!varname}" ]; then
957         if [ "${facet:0:3}" == "ost" ]; then
958             eval ${facet}_HOST=${ost_HOST}
959         fi
960     fi
961     echo -n ${!varname}
962 }
963
964 facet_active() {
965     local facet=$1
966     local activevar=${facet}active
967
968     if [ -f $TMP/${facet}active ] ; then
969         source $TMP/${facet}active
970     fi
971
972     active=${!activevar}
973     if [ -z "$active" ] ; then
974         echo -n ${facet}
975     else
976         echo -n ${active}
977     fi
978 }
979
980 facet_active_host() {
981     local facet=$1
982     local active=`facet_active $facet`
983     if [ "$facet" == client ]; then
984         echo $HOSTNAME
985     else
986         echo `facet_host $active`
987     fi
988 }
989
990 change_active() {
991     local facet=$1
992     failover=${facet}failover
993     host=`facet_host $failover`
994     [ -z "$host" ] && return
995     curactive=`facet_active $facet`
996     if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
997         eval export ${facet}active=$facet
998     else
999         eval export ${facet}active=$failover
1000     fi
1001     # save the active host for this facet
1002     activevar=${facet}active
1003     echo "$activevar=${!activevar}" > $TMP/$activevar
1004 }
1005
1006 do_node() {
1007     HOST=$1
1008     shift
1009     local myPDSH=$PDSH
1010     if [ "$HOST" = "$HOSTNAME" ]; then
1011         myPDSH="no_dsh"
1012     elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
1013         echo "cannot run remote command on $HOST with $myPDSH"
1014         return 128
1015     fi
1016     if $VERBOSE; then
1017         echo "CMD: $HOST $@" >&2
1018         $myPDSH $HOST $LCTL mark "$@" > /dev/null 2>&1 || :
1019     fi
1020
1021     if [ "$myPDSH" = "rsh" ]; then
1022 # we need this because rsh does not return exit code of an executed command
1023         local command_status="$TMP/cs"
1024         rsh $HOST ":> $command_status"
1025         rsh $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;
1026                     cd $RPWD; sh -c \"$@\") ||
1027                     echo command failed >$command_status"
1028         [ -n "$($myPDSH $HOST cat $command_status)" ] && return 1 || true
1029         return 0
1030     fi
1031     $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed "s/^${HOST}: //"
1032     return ${PIPESTATUS[0]}
1033 }
1034
1035 single_local_node () {
1036    [ "$1" = "$HOSTNAME" ]
1037 }
1038
1039 do_nodes() {
1040     local rnodes=$1
1041     shift
1042
1043     if $(single_local_node $rnodes); then
1044         do_node $rnodes $@
1045         return $?
1046     fi
1047
1048     # This is part from do_node
1049     local myPDSH=$PDSH
1050
1051     [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] && \
1052         echo "cannot run remote command on $rnodes with $myPDSH" && return 128
1053
1054     if $VERBOSE; then
1055         echo "CMD: $rnodes $@" >&2
1056         $myPDSH $rnodes $LCTL mark "$@" > /dev/null 2>&1 || :
1057     fi
1058
1059     $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; sh -c \"$@\")" | sed -re "s/\w+:\s//g"
1060     return ${PIPESTATUS[0]}
1061 }
1062
1063 do_facet() {
1064     facet=$1
1065     shift
1066     HOST=`facet_active_host $facet`
1067     [ -z $HOST ] && echo No host defined for facet ${facet} && exit 1
1068     do_node $HOST "$@"
1069 }
1070
1071 add() {
1072     local facet=$1
1073     shift
1074     # make sure its not already running
1075     stop ${facet} -f
1076     rm -f $TMP/${facet}active
1077     do_facet ${facet} $MKFS $*
1078 }
1079
1080 ostdevname() {
1081     num=$1
1082     DEVNAME=OSTDEV$num
1083     #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
1084     eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}}
1085     echo -n $DEVPTR
1086 }
1087
1088 ########
1089 ## MountConf setup
1090
1091 stopall() {
1092     # make sure we are using the primary server, so test-framework will
1093     # be able to clean up properly.
1094     activemds=`facet_active mds`
1095     if [ $activemds != "mds" ]; then
1096         fail mds
1097     fi
1098
1099     # assume client mount is local
1100     grep " $MOUNT " /proc/mounts && zconf_umount $HOSTNAME $MOUNT $*
1101     grep " $MOUNT2 " /proc/mounts && zconf_umount $HOSTNAME $MOUNT2 $*
1102
1103     if [ -n "$CLIENTS" ]; then
1104             zconf_umount_clients $CLIENTS $MOUNT "$*" || true
1105             [ -n "$MOUNT2" ] && zconf_umount_clients $CLIENTS $MOUNT2 "$*" || true
1106     fi
1107
1108     [ "$CLIENTONLY" ] && return
1109     # The add fn does rm ${facet}active file, this would be enough
1110     # if we use do_facet <facet> only after the facet added, but
1111     # currently we use do_facet mds in local.sh
1112     stop mds -f
1113     rm -f ${TMP}/mdsactive
1114     for num in `seq $OSTCOUNT`; do
1115         stop ost$num -f
1116         rm -f $TMP/ost${num}active
1117     done
1118     return 0
1119 }
1120
1121 cleanupall() {
1122     stopall $*
1123     unload_modules
1124 }
1125
1126 formatall() {
1127     [ "$FSTYPE" ] && FSTYPE_OPT="--backfstype $FSTYPE"
1128
1129     stopall
1130     # We need ldiskfs here, may as well load them all
1131     load_modules
1132     [ "$CLIENTONLY" ] && return
1133     echo Formatting mds, osts
1134     if $VERBOSE; then
1135         add mds $MDS_MKFS_OPTS $FSTYPE_OPT --reformat $MDSDEV || exit 10
1136     else
1137         add mds $MDS_MKFS_OPTS $FSTYPE_OPT --reformat $MDSDEV > /dev/null || exit 10
1138     fi
1139
1140     for num in `seq $OSTCOUNT`; do
1141         if $VERBOSE; then
1142             add ost$num $OST_MKFS_OPTS $FSTYPE_OPT --reformat `ostdevname $num` || exit 10
1143         else
1144             add ost$num $OST_MKFS_OPTS $FSTYPE_OPT --reformat `ostdevname $num` > /dev/null || exit 10
1145         fi
1146     done
1147 }
1148
1149 mount_client() {
1150     grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
1151 }
1152
1153 remount_client()
1154 {
1155         zconf_umount `hostname` $1 || error "umount failed"
1156         zconf_mount `hostname` $1 || error "mount failed"
1157 }
1158
1159 writeconf_facet () {
1160     local facet=$1
1161     local dev=$2
1162
1163     do_facet $facet "$TUNEFS --writeconf $dev"
1164 }
1165
1166 writeconf_all () {
1167     writeconf_facet mds $MDSDEV
1168
1169     for num in `seq $OSTCOUNT`; do
1170         DEVNAME=`ostdevname $num`
1171         writeconf_facet ost$num $DEVNAME
1172     done
1173 }
1174
1175 setupall() {
1176     load_modules
1177     if [ -z "$CLIENTONLY" ]; then
1178         echo Setup mdt, osts
1179
1180         echo $WRITECONF | grep -q "writeconf" && \
1181             writeconf_all
1182
1183         start mds $MDSDEV $MDS_MOUNT_OPTS
1184         # We started mds, now we should set failover variable properly.
1185         # Set mdsfailover_HOST if it is not set (the default failnode).
1186         mdsfailover_HOST=$(facet_host mds)
1187
1188         for num in `seq $OSTCOUNT`; do
1189             DEVNAME=`ostdevname $num`
1190             start ost$num $DEVNAME $OST_MOUNT_OPTS
1191
1192             # We started ost$num, now we should set ost${num}failover variable properly.
1193             # Set ost${num}failover_HOST if it is not set (the default failnode).
1194             varname=ost${num}failover_HOST
1195             if [ -z "${!varname}" ]; then
1196                 eval ost${num}failover_HOST=$(facet_host ost${num})
1197             fi
1198
1199         done
1200     fi
1201     [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
1202     mount_client $MOUNT
1203     [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT
1204
1205     if [ "$MOUNT_2" ]; then
1206         mount_client $MOUNT2
1207         [ -n "$CLIENTS" ] && zconf_mount_clients $CLIENTS $MOUNT2
1208     fi
1209     sleep 5
1210     init_param_vars
1211 }
1212
1213 mounted_lustre_filesystems() {
1214         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
1215 }
1216
1217 init_facet_vars () {
1218     local facet=$1
1219     shift
1220     local device=$1
1221
1222     shift
1223
1224     eval export ${facet}_dev=${device}
1225     eval export ${facet}_opt=\"$@\"
1226
1227     local dev=${facet}_dev
1228     local label=$(do_facet ${facet} "$E2LABEL ${!dev}")
1229     [ -z "$label" ] && echo no label for ${!dev} && exit 1
1230
1231     eval export ${facet}_svc=${label}
1232
1233     local varname=${facet}failover_HOST
1234     if [ -z "${!varname}" ]; then
1235        eval $varname=$(facet_host $facet)
1236     fi
1237 }
1238
1239 init_facets_vars () {
1240     init_facet_vars mds $MDSDEV $MDS_MOUNT_OPTS
1241
1242     for num in `seq $OSTCOUNT`; do
1243         DEVNAME=`ostdevname $num`
1244         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
1245     done
1246 }
1247
1248 init_param_vars () {
1249     export MDSVER=$(do_facet mds "lctl get_param version" | cut -d. -f1,2)
1250     export OSTVER=$(do_facet ost1 "lctl get_param version" | cut -d. -f1,2)
1251     export CLIVER=$(lctl get_param version | cut -d. -f 1,2)
1252
1253     TIMEOUT=$(do_facet mds "lctl get_param -n timeout")
1254     log "Using TIMEOUT=$TIMEOUT"
1255 }
1256
1257 check_config () {
1258     local mntpt=$1
1259     local myMGS_host=$mgs_HOST   
1260     if [ "$NETTYPE" = "ptl" ]; then
1261         myMGS_host=$(h2ptl $mgs_HOST | sed -e s/@ptl//) 
1262     fi
1263
1264     echo Checking config lustre mounted on $mntpt
1265     local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
1266     mgshost=$(echo $mgshost | awk -F: '{print $1}')
1267
1268     if [ "$mgshost" != "$myMGS_host" ]; then
1269         FAIL_ON_ERROR=true \
1270             error "Bad config file: lustre is mounted with mgs $mgshost, but mgs_HOST=$mgs_HOST, NETTYPE=$NETTYPE
1271                    Please use correct config or set mds_HOST correctly!"
1272     fi
1273 }
1274
1275 check_timeout () {
1276     local mdstimeout=$(do_facet mds "lctl get_param -n timeout")
1277     local cltimeout=$(lctl get_param -n timeout)
1278     if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
1279         error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
1280         return 1
1281     fi
1282 }
1283
1284 check_and_setup_lustre() {
1285     local MOUNTED=$(mounted_lustre_filesystems)
1286     if [ -z "$MOUNTED" ] || ! $(echo $MOUNTED | grep -w -q $MOUNT); then
1287         [ "$REFORMAT" ] && formatall
1288         setupall
1289         MOUNTED=$(mounted_lustre_filesystems | head -1)
1290         [ -z "$MOUNTED" ] && error "NAME=$NAME not mounted"
1291         export I_MOUNTED=yes
1292     else
1293         check_config $MOUNT
1294         init_facets_vars
1295         init_param_vars
1296     fi
1297     if [ "$ONLY" == "setup" ]; then
1298         exit 0
1299     fi
1300 }
1301
1302 cleanup_and_setup_lustre() {
1303     if [ "$ONLY" == "cleanup" -o "`mount | grep $MOUNT`" ]; then
1304         lctl set_param debug=0 || true
1305         cleanupall
1306         if [ "$ONLY" == "cleanup" ]; then
1307             exit 0
1308         fi
1309     fi
1310     check_and_setup_lustre
1311 }
1312
1313 check_and_cleanup_lustre() {
1314     if [ "`mount | grep $MOUNT`" ]; then
1315         [ -n "$DIR" ] && rm -rf $DIR/[Rdfs][0-9]*
1316     fi
1317     if [ "$I_MOUNTED" = "yes" ]; then
1318         cleanupall -f || error "cleanup failed"
1319     fi
1320     unset I_MOUNTED
1321 }
1322
1323 #######
1324 # General functions
1325
1326 check_network() {
1327     local NETWORK=0
1328     local WAIT=0
1329     local MAX=$2
1330     while [ $NETWORK -eq 0 ]; do
1331         ping -c 1 -w 3 $1 > /dev/null
1332         if [ $? -eq 0 ]; then
1333             NETWORK=1
1334         else
1335             WAIT=$((WAIT + 5))
1336             echo "waiting for $1, $((MAX - WAIT)) secs left"
1337             sleep 5
1338         fi
1339         if [ $WAIT -gt $MAX ]; then
1340             echo "Network not available"
1341             exit 1
1342         fi
1343     done
1344 }
1345 check_port() {
1346     while( !($DSH2 $1 "netstat -tna | grep -q $2") ) ; do
1347         sleep 9
1348     done
1349 }
1350
1351 no_dsh() {
1352     shift
1353     eval $@
1354 }
1355
1356 comma_list() {
1357     # the sed converts spaces to commas, but leaves the last space
1358     # alone, so the line doesn't end with a comma.
1359     echo "$*" | tr -s " " "\n" | sort -b -u | tr "\n" " " | sed 's/ \([^$]\)/,\1/g'
1360 }
1361
1362 # list, excluded are the comma separated lists
1363 exclude_items_from_list () {
1364     local list=$1
1365     local excluded=$2
1366     local item
1367
1368     list=${list//,/ }
1369     for item in ${excluded//,/ }; do
1370         list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
1371     done
1372     echo $(comma_list $list) 
1373 }
1374
1375 # list, expand  are the comma separated lists
1376 expand_list () {
1377     local list=${1//,/ }
1378     local expand=${2//,/ }
1379     local expanded=
1380
1381     expanded=$(for i in $list $expand; do echo $i; done | sort -u)
1382     echo $(comma_list $expanded)
1383 }
1384
1385 absolute_path() {
1386     (cd `dirname $1`; echo $PWD/`basename $1`)
1387 }
1388
1389 get_facets () {
1390     local name=$(echo $1 | tr "[:upper:]" "[:lower:]")
1391     local type=$(echo $1 | tr "[:lower:]" "[:upper:]")
1392
1393     local list=""
1394
1395     case $type in
1396         MDS )    list=mds;;
1397         OST )    for ((i=1; i<=$OSTCOUNT; i++)) do
1398                     list="$list ${name}$i"
1399                  done;;
1400           * )    error "Invalid facet type"
1401                  exit 1;;
1402     esac
1403     echo $(comma_list $list)
1404 }
1405
1406 ##################################
1407 # Adaptive Timeouts funcs
1408
1409 at_is_valid() {
1410     if [ -z "$AT_MAX_PATH" ]; then
1411         AT_MAX_PATH=$(do_facet mds "find /sys/ -name at_max")
1412         [ -z "$AT_MAX_PATH" ] && echo "missing /sys/.../at_max " && return 1
1413     fi
1414     return 0
1415 }
1416
1417 at_is_enabled() {
1418     at_is_valid || error "invalid call"
1419
1420     # only check mds, we assume at_max is the same on all nodes
1421     local at_max=$(do_facet mds "cat $AT_MAX_PATH")
1422     if [ $at_max -eq 0 ]; then
1423         return 1
1424     else
1425         return 0
1426     fi
1427 }
1428
1429 at_max_get() {
1430     local facet=$1
1431
1432     at_is_valid || error "invalid call"
1433
1434     # suppose that all ost-s has the same at_max set
1435     if [ $facet == "ost" ]; then
1436         do_facet ost1 "cat $AT_MAX_PATH"
1437     else
1438         do_facet $facet "cat $AT_MAX_PATH"
1439     fi
1440 }
1441
1442 at_max_set() {
1443     local at_max=$1
1444     shift
1445
1446     at_is_valid || error "invalid call"
1447
1448     local facet
1449     for facet in $@; do
1450         if [ $facet == "ost" ]; then
1451             for i in `seq $OSTCOUNT`; do
1452                 do_facet ost$i "echo $at_max > $AT_MAX_PATH"
1453             done
1454         else
1455             do_facet $facet "echo $at_max > $AT_MAX_PATH"
1456         fi
1457     done
1458 }
1459
1460 ##################################
1461 # OBD_FAIL funcs
1462
1463 drop_request() {
1464 # OBD_FAIL_MDS_ALL_REQUEST_NET
1465     RC=0
1466     do_facet mds lctl set_param fail_loc=0x123
1467     do_facet client "$1" || RC=$?
1468     do_facet mds lctl set_param fail_loc=0
1469     return $RC
1470 }
1471
1472 drop_reply() {
1473 # OBD_FAIL_MDS_ALL_REPLY_NET
1474     RC=0
1475     do_facet mds lctl set_param fail_loc=0x122
1476     do_facet client "$@" || RC=$?
1477     do_facet mds lctl set_param fail_loc=0
1478     return $RC
1479 }
1480
1481 drop_reint_reply() {
1482 # OBD_FAIL_MDS_REINT_NET_REP
1483     RC=0
1484     do_facet mds lctl set_param fail_loc=0x119
1485     do_facet client "$@" || RC=$?
1486     do_facet mds lctl set_param fail_loc=0
1487     return $RC
1488 }
1489
1490 pause_bulk() {
1491 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
1492     RC=0
1493     do_facet ost1 lctl set_param fail_loc=0x214
1494     do_facet client "$1" || RC=$?
1495     do_facet client "sync"
1496     do_facet ost1 lctl set_param fail_loc=0
1497     return $RC
1498 }
1499
1500 drop_ldlm_cancel() {
1501 #define OBD_FAIL_LDLM_CANCEL             0x304
1502     RC=0
1503     do_facet client lctl set_param fail_loc=0x304
1504     do_facet client "$@" || RC=$?
1505     do_facet client lctl set_param fail_loc=0
1506     return $RC
1507 }
1508
1509 drop_bl_callback() {
1510 #define OBD_FAIL_LDLM_BL_CALLBACK        0x305
1511     RC=0
1512     do_facet client lctl set_param fail_loc=0x305
1513     do_facet client "$@" || RC=$?
1514     do_facet client lctl set_param fail_loc=0
1515     return $RC
1516 }
1517
1518 drop_ldlm_reply() {
1519 #define OBD_FAIL_LDLM_REPLY              0x30c
1520     RC=0
1521     do_facet mds lctl set_param fail_loc=0x30c
1522     do_facet client "$@" || RC=$?
1523     do_facet mds lctl set_param fail_loc=0
1524     return $RC
1525 }
1526
1527 clear_failloc() {
1528     facet=$1
1529     pause=$2
1530     sleep $pause
1531     echo "clearing fail_loc on $facet"
1532     do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
1533 }
1534
1535 set_nodes_failloc () {
1536     local nodes=$1
1537     local node
1538
1539     for node in $nodes ; do
1540         do_node $node lctl set_param fail_loc=$2
1541     done
1542 }
1543
1544 cancel_lru_locks() {
1545     $LCTL mark "cancel_lru_locks $1 start"
1546     for d in `lctl get_param -N ldlm.namespaces.*.lru_size | egrep -i $1`; do
1547         $LCTL set_param -n $d=clear
1548     done
1549     $LCTL get_param ldlm.namespaces.*.lock_unused_count | egrep -i $1 | grep -v '=0'
1550     $LCTL mark "cancel_lru_locks $1 stop"
1551 }
1552
1553 default_lru_size()
1554 {
1555         NR_CPU=$(grep -c "processor" /proc/cpuinfo)
1556         DEFAULT_LRU_SIZE=$((100 * NR_CPU))
1557         echo "$DEFAULT_LRU_SIZE"
1558 }
1559
1560 lru_resize_enable()
1561 {
1562     lctl set_param ldlm.namespaces.*$1*.lru_size=0
1563 }
1564
1565 lru_resize_disable()
1566 {
1567     lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)
1568 }
1569
1570 pgcache_empty() {
1571     local FILE
1572     for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
1573         if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
1574             echo there is still data in page cache $FILE ?
1575             lctl get_param -n $FILE
1576             return 1
1577         fi
1578     done
1579     return 0
1580 }
1581
1582 create_fake_exports () {
1583     local facet=$1
1584     local num=$2
1585 #obd_fail_val = num;
1586 #define OBD_FAIL_TGT_FAKE_EXP 0x708
1587     do_facet $facet "lctl set_param fail_val=$num"
1588     do_facet $facet "lctl set_param fail_loc=0x80000708"
1589     fail $facet
1590 }
1591
1592 debugsave() {
1593     DEBUGSAVE="$(lctl get_param -n debug)"
1594 }
1595
1596 debugrestore() {
1597     [ -n "$DEBUGSAVE" ] && lctl set_param debug="${DEBUGSAVE}"
1598     DEBUGSAVE=""
1599 }
1600
1601 ##################################
1602 # Test interface
1603 ##################################
1604
1605 error_noexit() {
1606     local TYPE=${TYPE:-"FAIL"}
1607     local ERRLOG
1608     lctl set_param fail_loc=0 2>/dev/null || true
1609     log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ "
1610     ERRLOG=$TMP/lustre_${TESTSUITE}_${TESTNAME}.$(date +%s)
1611     echo "Dumping lctl log to $ERRLOG"
1612     # We need to dump the logs on all nodes
1613     local NODES=$(nodes_list)
1614     for NODE in $NODES; do
1615         do_node $NODE $LCTL dk $ERRLOG
1616     done
1617     debugrestore
1618     [ "$TESTSUITELOG" ] && echo "$0: ${TYPE}: $TESTNAME $@" >> $TESTSUITELOG
1619     TEST_FAILED=true
1620 }
1621
1622 error() {
1623     error_noexit "$@"
1624     $FAIL_ON_ERROR && exit 1 || true
1625 }
1626
1627 error_exit() {
1628     error_noexit "$@"
1629     exit 1
1630 }
1631
1632 # use only if we are ignoring failures for this test, bugno required.
1633 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
1634 # e.g. error_ignore 5494 "your message"
1635 error_ignore() {
1636     local TYPE="IGNORE (bz$1)"
1637     shift
1638     error_noexit "$@"
1639 }
1640
1641 skip () {
1642         log " SKIP: ${TESTSUITE} ${TESTNAME} $@"
1643         [ "$TESTSUITELOG" ] && \
1644                 echo "${TESTSUITE}: SKIP: $TESTNAME $@" >> $TESTSUITELOG || true
1645 }
1646
1647 build_test_filter() {
1648     [ "$ONLY" ] && log "only running test `echo $ONLY`"
1649     for O in $ONLY; do
1650         eval ONLY_${O}=true
1651     done
1652     [ "$EXCEPT$ALWAYS_EXCEPT" ] && \
1653         log "excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`"
1654     [ "$EXCEPT_SLOW" ] && \
1655         log "skipping tests SLOW=no: `echo $EXCEPT_SLOW`"
1656     for E in $EXCEPT $ALWAYS_EXCEPT; do
1657         eval EXCEPT_${E}=true
1658     done
1659     for E in $EXCEPT_SLOW; do
1660         eval EXCEPT_SLOW_${E}=true
1661     done
1662     for G in $GRANT_CHECK_LIST; do
1663         eval GCHECK_ONLY_${G}=true
1664         done
1665 }
1666
1667 _basetest() {
1668     echo $*
1669 }
1670
1671 basetest() {
1672     IFS=abcdefghijklmnopqrstuvwxyz _basetest $1
1673 }
1674
1675 # print a newline if the last test was skipped
1676 export LAST_SKIPPED=
1677 run_test() {
1678     assert_DIR
1679
1680     export base=`basetest $1`
1681     if [ ! -z "$ONLY" ]; then
1682         testname=ONLY_$1
1683         if [ ${!testname}x != x ]; then
1684             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
1685             run_one $1 "$2"
1686             return $?
1687         fi
1688         testname=ONLY_$base
1689         if [ ${!testname}x != x ]; then
1690             [ "$LAST_SKIPPED" ] && echo "" && LAST_SKIPPED=
1691             run_one $1 "$2"
1692             return $?
1693         fi
1694         LAST_SKIPPED="y"
1695         echo -n "."
1696         return 0
1697     fi
1698     testname=EXCEPT_$1
1699     if [ ${!testname}x != x ]; then
1700         LAST_SKIPPED="y"
1701         TESTNAME=test_$1 skip "skipping excluded test $1"
1702         return 0
1703     fi
1704     testname=EXCEPT_$base
1705     if [ ${!testname}x != x ]; then
1706         LAST_SKIPPED="y"
1707         TESTNAME=test_$1 skip "skipping excluded test $1 (base $base)"
1708         return 0
1709     fi
1710     testname=EXCEPT_SLOW_$1
1711     if [ ${!testname}x != x ]; then
1712         LAST_SKIPPED="y"
1713         TESTNAME=test_$1 skip "skipping SLOW test $1"
1714         return 0
1715     fi
1716     testname=EXCEPT_SLOW_$base
1717     if [ ${!testname}x != x ]; then
1718         LAST_SKIPPED="y"
1719         TESTNAME=test_$1 skip "skipping SLOW test $1 (base $base)"
1720         return 0
1721     fi
1722
1723     LAST_SKIPPED=
1724     run_one $1 "$2"
1725
1726     return $?
1727 }
1728
1729 EQUALS="======================================================================"
1730 equals_msg() {
1731     msg="$@"
1732
1733     local suffixlen=$((${#EQUALS} - ${#msg}))
1734     [ $suffixlen -lt 5 ] && suffixlen=5
1735     log `echo $(printf '===== %s %.*s\n' "$msg" $suffixlen $EQUALS)`
1736 }
1737
1738 log() {
1739     echo "$*"
1740     lsmod | grep lnet > /dev/null || load_modules
1741
1742     local MSG="$*"
1743     # Get rif of '
1744     MSG=${MSG//\'/\\\'}
1745     MSG=${MSG//\(/\\\(}
1746     MSG=${MSG//\)/\\\)}
1747     MSG=${MSG//\;/\\\;}
1748     MSG=${MSG//\|/\\\|}
1749     MSG=${MSG//\>/\\\>}
1750     MSG=${MSG//\</\\\<}
1751     MSG=${MSG//\//\\\/}
1752     local NODES=$(nodes_list)
1753     for NODE in $NODES; do
1754         do_node $NODE $LCTL mark "$MSG" 2> /dev/null || true
1755     done
1756 }
1757
1758 trace() {
1759         log "STARTING: $*"
1760         strace -o $TMP/$1.strace -ttt $*
1761         RC=$?
1762         log "FINISHED: $*: rc $RC"
1763         return 1
1764 }
1765
1766 pass() {
1767     $TEST_FAILED && echo -n "FAIL " || echo -n "PASS " 
1768     echo $@
1769 }
1770
1771 check_mds() {
1772     FFREE=`lctl get_param -n mds.*.filesfree`
1773     FTOTAL=`lctl get_param -n mds.*.filestotal`
1774     [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" || true
1775 }
1776
1777 reset_fail_loc () {
1778     local myNODES=$(nodes_list)
1779     local NODE
1780
1781     for NODE in $myNODES; do
1782         do_node $NODE "lctl set_param fail_loc=0 2>/dev/null || true"
1783     done
1784 }
1785
1786 run_one() {
1787     testnum=$1
1788     message=$2
1789     tfile=f${testnum}
1790     export tdir=d0.${TESTSUITE}/d${base}
1791
1792     local SAVE_UMASK=`umask`
1793     umask 0022
1794
1795     local BEFORE=`date +%s`
1796     log "== test $testnum: $message ============ `date +%H:%M:%S` ($BEFORE)"
1797     #check_mds
1798     export TESTNAME=test_$testnum
1799     TEST_FAILED=false
1800     test_${testnum} || error "test_$testnum failed with $?"
1801     #check_mds
1802     cd $SAVE_PWD
1803     reset_fail_loc
1804     check_grant ${testnum} || error "check_grant $testnum failed with $?"
1805     check_catastrophe || error "LBUG/LASSERT detected"
1806     ps auxww | grep -v grep | grep -q multiop && error "multiop still running"
1807     pass "($((`date +%s` - $BEFORE))s)"
1808     TEST_FAILED=false
1809     unset TESTNAME
1810     unset tdir
1811     umask $SAVE_UMASK
1812 }
1813
1814 canonical_path() {
1815     (cd `dirname $1`; echo $PWD/`basename $1`)
1816 }
1817
1818 sync_clients() {
1819     [ -d $DIR1 ] && cd $DIR1 && sync; sleep 1; sync
1820     [ -d $DIR2 ] && cd $DIR2 && sync; sleep 1; sync
1821         cd $SAVE_PWD
1822 }
1823
1824 check_grant() {
1825     export base=`basetest $1`
1826     [ "$CHECK_GRANT" == "no" ] && return 0
1827
1828         testname=GCHECK_ONLY_${base}
1829     [ ${!testname}x == x ] && return 0
1830
1831     echo -n "checking grant......"
1832         cd $SAVE_PWD
1833         # write some data to sync client lost_grant
1834         rm -f $DIR1/${tfile}_check_grant_* 2>&1
1835         for i in `seq $OSTCOUNT`; do
1836                 $LFS setstripe $DIR1/${tfile}_check_grant_$i -i $(($i -1)) -c 1
1837                 dd if=/dev/zero of=$DIR1/${tfile}_check_grant_$i bs=4k \
1838                                               count=1 > /dev/null 2>&1
1839         done
1840     # sync all the data and make sure no pending data on server
1841     sync_clients
1842
1843     #get client grant and server grant
1844     client_grant=0
1845     for d in `lctl get_param -n osc.*.cur_grant_bytes`; do
1846         client_grant=$((client_grant + $d))
1847     done
1848     server_grant=0
1849     for d in `lctl get_param -n obdfilter.*.tot_granted`; do
1850         server_grant=$((server_grant + $d))
1851     done
1852
1853         # cleanup the check_grant file
1854         for i in `seq $OSTCOUNT`; do
1855                 rm $DIR1/${tfile}_check_grant_$i
1856         done
1857
1858         #check whether client grant == server grant
1859         if [ $client_grant != $server_grant ]; then
1860                 echo "failed: client:${client_grant} server: ${server_grant}"
1861                 return 1
1862         else
1863                 echo "pass"
1864         fi
1865 }
1866
1867 ########################
1868 # helper functions
1869
1870 osc_to_ost()
1871 {
1872     osc=$1
1873     ost=`echo $1 | awk -F_ '{print $3}'`
1874     if [ -z $ost ]; then
1875         ost=`echo $1 | sed 's/-osc.*//'`
1876     fi
1877     echo $ost
1878 }
1879
1880 remote_node () {
1881     local node=$1
1882     [ "$node" != "$(hostname)" ]
1883 }
1884
1885 remote_mds ()
1886 {
1887     remote_node $mds_HOST
1888 }
1889
1890 remote_mds_nodsh()
1891 {
1892     remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
1893 }
1894
1895 remote_ost ()
1896 {
1897     local node
1898     for node in $(osts_nodes) ; do
1899         remote_node $node && return 0
1900     done
1901     return 1
1902 }
1903
1904 remote_ost_nodsh()
1905 {
1906     remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
1907 }
1908
1909 remote_mgs_nodsh()
1910 {
1911     local MGS
1912     MGS=$(facet_host mgs)
1913     remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
1914 }
1915
1916 remote_servers () {
1917     remote_ost && remote_mds
1918 }
1919
1920 osts_nodes () {
1921     local OSTNODES=$(facet_host ost1)
1922     local NODES_sort
1923
1924     for num in `seq $OSTCOUNT`; do
1925         local myOST=$(facet_host ost$num)
1926         OSTNODES="$OSTNODES $myOST"
1927     done
1928     NODES_sort=$(for i in $OSTNODES; do echo $i; done | sort -u)
1929
1930     echo $NODES_sort
1931 }
1932
1933 nodes_list () {
1934     # FIXME. We need a list of clients
1935     local myNODES=$HOSTNAME
1936     local myNODES_sort
1937
1938     # CLIENTS (if specified) contains the local client
1939     [ -n "$CLIENTS" ] && myNODES=${CLIENTS//,/ }
1940
1941     if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
1942         myNODES="$myNODES $(osts_nodes) $mds_HOST"
1943     fi
1944
1945     myNODES_sort=$(for i in $myNODES; do echo $i; done | sort -u)
1946
1947     echo $myNODES_sort
1948 }
1949
1950 remote_nodes_list () {
1951     local rnodes=$(nodes_list)
1952     rnodes=$(echo " $rnodes " | sed -re "s/\s+$HOSTNAME\s+/ /g")
1953     echo $rnodes
1954 }
1955
1956 init_clients_lists () {
1957     # Sanity check: exclude the local client from RCLIENTS
1958     local rclients=$(echo " $RCLIENTS " | sed -re "s/\s+$HOSTNAME\s+/ /g")
1959
1960     # Sanity check: exclude the dup entries
1961     rclients=$(for i in $rclients; do echo $i; done | sort -u)
1962
1963     local clients="$SINGLECLIENT $HOSTNAME $rclients"
1964
1965     # Sanity check: exclude the dup entries from CLIENTS
1966     # for those configs which has SINGLCLIENT set to local client
1967     clients=$(for i in $clients; do echo $i; done | sort -u)
1968
1969     CLIENTS=`comma_list $clients`
1970     local -a remoteclients=($rclients)
1971     for ((i=0; $i<${#remoteclients[@]}; i++)); do
1972             varname=CLIENT$((i + 2))
1973             eval $varname=${remoteclients[i]}
1974     done
1975
1976     CLIENTCOUNT=$((${#remoteclients[@]} + 1))
1977 }
1978
1979 get_random_entry () {
1980     local rnodes=$1
1981
1982     rnodes=${rnodes//,/ }
1983
1984     local nodes=($rnodes)
1985     local num=${#nodes[@]} 
1986     local i=$((RANDOM * num * 2 / 65536))
1987
1988     echo ${nodes[i]}
1989 }
1990
1991 is_patchless ()
1992 {
1993     lctl get_param version | grep -q patchless
1994 }
1995
1996 check_versions () {
1997     [ "$MDSVER" = "$CLIVER" -a "$OSTVER" = "$CLIVER" ]
1998 }
1999
2000 get_node_count() {
2001     local nodes="$@"
2002     echo $nodes | wc -w || true
2003 }
2004
2005 mixed_ost_devs () {
2006     local nodes=$(osts_nodes)
2007     local osscount=$(get_node_count "$nodes")
2008     [ ! "$OSTCOUNT" = "$osscount" ]
2009 }
2010
2011 generate_machine_file() {
2012     local nodes=${1//,/ }
2013     local machinefile=$2
2014     rm -f $machinefile || error "can't rm $machinefile"
2015     for node in $nodes; do
2016         echo $node >>$machinefile
2017     done
2018 }
2019
2020 get_stripe () {
2021     local file=$1/stripe
2022     touch $file
2023     $LFS getstripe -v $file || error
2024     rm -f $file
2025 }
2026
2027 check_runas_id_ret() {
2028     local myRC=0
2029     local myRUNAS_UID=$1
2030     local myRUNAS_GID=$2
2031     shift 2
2032     local myRUNAS=$@
2033     if [ -z "$myRUNAS" ]; then
2034         error_exit "myRUNAS command must be specified for check_runas_id"
2035     fi
2036     mkdir $DIR/d0_runas_test
2037     chmod 0755 $DIR
2038     chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
2039     $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=1
2040     rm -rf $DIR/d0_runas_test
2041     return $myRC
2042 }
2043
2044 check_runas_id() {
2045     local myRUNAS_UID=$1
2046     local myRUNAS_GID=$2
2047     shift 2
2048     local myRUNAS=$@
2049     check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
2050         error "unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.
2051         Please set RUNAS_ID to some UID which exists on MDS and client or
2052         add user $myRUNAS_UID:$myRUNAS_GID on these nodes."
2053 }
2054
2055 # Run multiop in the background, but wait for it to print
2056 # "PAUSING" to its stdout before returning from this function.
2057 multiop_bg_pause() {
2058     MULTIOP_PROG=${MULTIOP_PROG:-multiop}
2059     FILE=$1
2060     ARGS=$2
2061
2062     TMPPIPE=/tmp/multiop_open_wait_pipe.$$
2063     mkfifo $TMPPIPE
2064
2065     echo "$MULTIOP_PROG $FILE v$ARGS"
2066     $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
2067
2068     echo "TMPPIPE=${TMPPIPE}"
2069     local multiop_output
2070     local multiop_pid
2071
2072     read -t 60 multiop_output multiop_pid < $TMPPIPE
2073     if [ $? -ne 0 ]; then
2074         rm -f $TMPPIPE
2075         return 1
2076     fi
2077     rm -f $TMPPIPE
2078     if [ "$multiop_output" != "PAUSING" ]; then
2079         echo "Incorrect multiop output: $multiop_output"
2080         kill -9 $PID
2081         return 1
2082     fi
2083
2084     echo $multiop_pid
2085     return 0
2086 }
2087
2088 inodes_available () {
2089     local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{print $4}' | sort -un | head -1) || return 1
2090     echo $IFree
2091 }
2092
2093 # reset llite stat counters
2094 clear_llite_stats(){
2095         lctl set_param -n llite.*.stats 0
2096 }
2097
2098 # sum llite stat items
2099 calc_llite_stats() {
2100         local res=$(lctl get_param -n llite.*.stats |
2101                     awk 'BEGIN {s = 0} END {print s} /^'"$1"'/ {s += $2}')
2102         echo $res
2103 }
2104
2105 calc_sum () {
2106         awk 'BEGIN {s = 0}; {s += $1}; END {print s}'
2107 }
2108
2109 calc_osc_kbytes () {
2110         $LCTL get_param -n osc.*[oO][sS][cC][-_]*.$1 | calc_sum
2111 }
2112
2113 # save_lustre_params(node, parameter_mask)
2114 # generate a stream of formatted strings (<node> <param name>=<param value>)
2115 save_lustre_params() {
2116         local s
2117         do_node $1 "lctl get_param $2" | while read s; do echo "$1 $s"; done
2118 }
2119
2120 # restore lustre parameters from input stream, produces by save_lustre_params
2121 restore_lustre_params() {
2122         local node
2123         local name
2124         local val
2125         while IFS=" =" read node name val; do
2126                 do_node $node "lctl set_param -n $name $val"
2127         done
2128 }
2129
2130 check_catastrophe () {
2131     local rnodes=${1:-$(comma_list $(remote_nodes_list))}
2132
2133     [ -f $CATASTROPHE ] && [ $(cat $CATASTROPHE) -ne 0 ] && return 1
2134     if [ $rnodes ]; then
2135         do_nodes $rnodes "set -x; [ -f $CATASTROPHE ] && { [ \`cat $CATASTROPHE\` -eq 0 ] || false; } || true"
2136     fi
2137 }
2138
2139 # $1 node
2140 # $2 file
2141 # $3 $RUNAS
2142 get_stripe_info() {
2143         local tmp_file
2144
2145         stripe_size=0
2146         stripe_count=0
2147         stripe_index=0
2148         tmp_file=$(mktemp)
2149
2150         do_facet $1 $3 lfs getstripe -v $2 > $tmp_file
2151
2152         stripe_size=`awk '$1 ~ /size/ {print $2}' $tmp_file`
2153         stripe_count=`awk '$1 ~ /count/ {print $2}' $tmp_file`
2154         stripe_index=`awk '/obdidx/ {start = 1; getline; print $1; exit}' $tmp_file`
2155         rm -f $tmp_file
2156 }
2157
2158 mpi_run () {
2159     local mpirun="$MPIRUN $MPIRUN_OPTIONS"
2160     local command="$mpirun $@"
2161
2162     if [ "$MPI_USER" != root -a $mpirun ]; then
2163         echo "+ chmod 0777 $MOUNT"
2164         chmod 0777 $MOUNT
2165         command="su $MPI_USER sh -c \"$command \""
2166     fi
2167
2168     ls -ald $MOUNT
2169     echo "+ $command"
2170     eval $command
2171 }
2172
2173 mdsrate_cleanup () {
2174     mpi_run -np $1 -machinefile $2 ${MDSRATE} --unlink --nfiles $3 --dir $4 --filefmt $5
2175 }
2176
2177 delayed_recovery_enabled () {
2178     do_facet mds "lctl get_param -n mds.${mds_svc}.stale_export_age" > /dev/null 2>&1
2179 }
2180
2181 ################################################################################
2182 # The following functions are used to enable interop testing between
2183 # 1.8 and 2.0. The lprocfs layout changed from 1.8 to 2.0 as the followings:
2184 # mds -> mdt
2185 # {blocksize filesfree filestotal fstype kbytesavail kbytesfree kbytestotal mntdev} moved from mds to osd
2186 # mdt lov: fsname-mdtlov -> fsname-MDTXXXX-mdtlov
2187 # mdt osc: fsname-OSTXXXX-osc -> fsname-OSTXXXX-osc-MDTXXXX
2188 ################################################################################
2189
2190 get_lustre_version () {
2191     local node=${1:-"mds"}    
2192     do_facet $node $LCTL get_param -n version |  awk '/^lustre:/ {print $2}'
2193 }
2194
2195 get_mds_version_major () {
2196     local version=$(get_lustre_version mds)
2197     echo $version | awk -F. '{print $1}'
2198 }
2199
2200 get_mds_version_minor () {
2201     local version=$(get_lustre_version mds)
2202     echo $version | awk -F. '{print $2}'
2203 }
2204
2205 get_mds_version_patch () {
2206     local version=$(get_lustre_version mds)
2207     echo $version | awk -F. '{print $3}'
2208 }
2209
2210 get_mds_version_fix () {
2211     local version=$(get_lustre_version mds)
2212     echo $version | awk -F. '{print $4}'
2213 }
2214
2215 get_mds_fsstat_proc_path() {
2216     local major=$(get_mds_version_major)
2217     local minor=$(get_mds_version_minor)
2218     if [ $major -le 1 -a $minor -le 8 ] ; then
2219         echo "mds"
2220     else
2221         echo "osd"
2222     fi
2223 }
2224
2225 get_mds_mntdev_proc_path() {
2226     local fsstat_dev=$(get_mds_fsstat_proc_path)
2227     echo "$fsstat_dev.*.mntdev"
2228 }
2229
2230 get_mdtlov_proc_path() {
2231     local fsname=$1
2232     local major=$(get_mds_version_major)
2233     local minor=$(get_mds_version_minor)
2234     if [ $major -le 1 -a $minor -le 8 ] ; then
2235         echo "$fsname-mdtlov"
2236     else
2237         echo "$fsname-MDT0000-mdtlov"
2238     fi
2239 }
2240
2241 get_mdtosc_proc_path() {
2242     local ost=$1
2243     local major=$(get_mds_version_major)
2244     local minor=$(get_mds_version_minor)
2245     if [ $major -le 1 -a $minor -le 8 ] ; then
2246         echo "${ost}-osc"
2247     else
2248         echo "${ost}-osc-MDT0000"
2249     fi
2250 }
2251
2252 get_mds_mdt_device_proc_path() {
2253     local major=$(get_mds_version_major)
2254     local minor=$(get_mds_version_minor)
2255     if [ $major -le 1 -a $minor -le 8 ] ; then
2256         echo "mds"
2257     else
2258         echo "mdt"
2259     fi
2260 }
2261
2262