Merge commit 'martins/master'
[vlendec/samba-autobuild/.git] / ctdb / tests / scripts / ctdb_test_functions.bash
1 # Hey Emacs, this is a -*- shell-script -*- !!!  :-)
2
3 fail ()
4 {
5     echo "$*"
6     exit 1
7 }
8
9 ######################################################################
10
11 ctdb_test_begin ()
12 {
13     local name="$1"
14
15     teststarttime=$(date '+%s')
16     testduration=0
17
18     echo "--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--"
19     echo "Running test $name ($(date '+%T'))"
20     echo "--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--"
21 }
22
23 ctdb_test_end ()
24 {
25     local name="$1" ; shift
26     local status="$1" ; shift
27     # "$@" is command-line
28
29     local interp="SKIPPED"
30     local statstr=" (reason $*)"
31     if [ -n "$status" ] ; then
32         if [ $status -eq 0 ] ; then
33             interp="PASSED"
34             statstr=""
35             echo "ALL OK: $*"
36         else
37             interp="FAILED"
38             statstr=" (status $status)"
39             testfailures=$(($testfailures+1))
40         fi
41     fi
42
43     testduration=$(($(date +%s)-$teststarttime))
44
45     echo "=========================================================================="
46     echo "TEST ${interp}: ${name}${statstr} (duration: ${testduration}s)"
47     echo "=========================================================================="
48
49 }
50
51 test_exit ()
52 {
53     exit $(($testfailures+0))
54 }
55
56 ctdb_test_exit ()
57 {
58     local status=$?
59
60     trap - 0
61
62     [ $(($testfailures+0)) -eq 0 -a $status -ne 0 ] && testfailures=$status
63     status=$(($testfailures+0))
64
65     # Avoid making a test fail from this point onwards.  The test is
66     # now complete.
67     set +e
68
69     echo "*** TEST COMPLETE (RC=$status), CLEANING UP..."
70
71     eval "$ctdb_test_exit_hook" || true
72     unset ctdb_test_exit_hook
73
74     if $ctdb_test_restart_scheduled || ! cluster_is_healthy ; then
75
76         restart_ctdb
77     else
78         # This could be made unconditional but then we might get
79         # duplication from the recovery in restart_ctdb.  We want to
80         # leave the recovery in restart_ctdb so that future tests that
81         # might do a manual restart mid-test will benefit.
82         echo "Forcing a recovery..."
83         onnode 0 ctdb recover
84     fi
85
86     exit $status
87 }
88
89 ctdb_test_exit_hook_add ()
90 {
91     ctdb_test_exit_hook="${ctdb_test_exit_hook}${ctdb_test_exit_hook:+ ; }$*"
92 }
93
94 ctdb_test_run ()
95 {
96     local name="$1" ; shift
97     
98     [ -n "$1" ] || set -- "$name"
99
100     ctdb_test_begin "$name"
101
102     local status=0
103     "$@" || status=$?
104
105     ctdb_test_end "$name" "$status" "$*"
106     
107     return $status
108 }
109
110 ctdb_test_usage()
111 {
112     local status=${1:-2}
113     
114     cat <<EOF
115 Usage: $0 [option]
116
117 Options:        
118     -h, --help          show this screen.
119     -v, --version       show test case version.
120     --category          show the test category (ACL, CTDB, Samba ...).
121     -d, --description   show test case description.
122     --summary           show short test case summary.
123     -x                  trace test using set -x
124 EOF
125
126     exit $status
127 }
128
129 ctdb_test_version ()
130 {
131     [ -n "$CTDB_DIR" ] || fail "Can not determine version."
132
133     (cd "$CTDB_DIR" && git describe)
134 }
135
136 ctdb_test_cmd_options()
137 {
138     [ -n "$1" ] || return 0
139
140     case "$1" in
141         -h|--help)        ctdb_test_usage 0   ;;
142         -v|--version)     ctdb_test_version   ;;
143         --category)       echo "CTDB"         ;; 
144         -d|--description) test_info           ;;
145         -x)               set -x ; return 0   ;;
146         *)
147             echo "Error: Unknown parameter = $1"
148             echo
149             ctdb_test_usage 2
150             ;;
151     esac
152
153     exit 0
154 }
155
156 ctdb_test_init () 
157 {
158     scriptname=$(basename "$0")
159     testfailures=0
160     ctdb_test_restart_scheduled=false
161
162     ctdb_test_cmd_options $@
163
164     trap "ctdb_test_exit" 0
165 }
166
167 ctdb_test_check_real_cluster ()
168 {
169     [ -n "$CTDB_TEST_REAL_CLUSTER" ] && return 0
170
171     echo "ERROR: This test must be run on a real/virtual cluster, not local daemons."
172     return 1
173 }
174
175 ########################################
176
177 # Sets: $out
178 try_command_on_node ()
179 {
180     local nodespec="$1" ; shift
181
182     local verbose=false
183     local onnode_opts=""
184
185     while [ "${nodespec#-}" != "$nodespec" ] ; do
186         if [ "$nodespec" = "-v" ] ; then
187             verbose=true
188         else
189             onnode_opts="$nodespec"
190         fi
191         nodespec="$1" ; shift
192     done
193
194     local cmd="$*"
195
196     out=$(onnode -q $onnode_opts "$nodespec" "$cmd" 2>&1) || {
197
198         echo "Failed to execute \"$cmd\" on node(s) \"$nodespec\""
199         echo "$out"
200         return 1
201     }
202
203     if $verbose ; then
204         echo "Output of \"$cmd\":"
205         echo "$out"
206     fi
207 }
208
209 sanity_check_output ()
210 {
211     local min_lines="$1"
212     local regexp="$2" # Should be anchored as necessary.
213     local output="$3"
214
215     local ret=0
216
217     local num_lines=$(echo "$output" | wc -l)
218     echo "There are $num_lines lines of output"
219     if [ $num_lines -lt $min_lines ] ; then
220         echo "BAD: that's less than the required number (${min_lines})"
221         ret=1
222     fi
223
224     local status=0
225     local unexpected # local doesn't pass through status of command on RHS.
226     unexpected=$(echo "$output" | egrep -v "$regexp") || status=$?
227
228     # Note that this is reversed.
229     if [ $status -eq 0 ] ; then
230         echo "BAD: unexpected lines in output:"
231         echo "$unexpected" | cat -A
232         ret=1
233     else
234         echo "Output lines look OK"
235     fi
236
237     return $ret
238 }
239
240 sanity_check_ips ()
241 {
242     local ips="$1" # Output of "ctdb ip -n all"
243
244     echo "Sanity checking IPs..."
245
246     local x ipp prev
247     prev=""
248     while read x ipp ; do
249         [ "$ipp" = "-1" ] && break
250         if [ -n "$prev" -a "$ipp" != "$prev" ] ; then
251             echo "OK"
252             return 0
253         fi
254         prev="$ipp"
255     done <<<"$ips"
256
257     echo "BAD: a node was -1 or IPs are only assigned to one node"
258     echo "Are you running an old version of CTDB?"
259     return 1
260 }
261
262 select_test_node_and_ips ()
263 {
264     try_command_on_node 0 "$CTDB ip -n all | sed -e '1d'"
265
266     # When selecting test_node we just want a node that has public
267     # IPs.  This will work and is economically semi-random.  :-)
268     local x
269     read x test_node <<<"$out"
270
271     test_node_ips=""
272     local ip pnn
273     while read ip pnn ; do
274         if [ "$pnn" = "$test_node" ] ; then
275             test_node_ips="${test_node_ips}${test_node_ips:+ }${ip}"
276         fi
277     done <<<"$out" # bashism to avoid problem setting variable in pipeline.
278
279     echo "Selected node ${test_node} with IPs: ${test_node_ips}."
280     test_ip="${test_node_ips%% *}"
281 }
282
283 #######################################
284
285 # Wait until either timeout expires or command succeeds.  The command
286 # will be tried once per second.
287 wait_until ()
288 {
289     local timeout="$1" ; shift # "$@" is the command...
290
291     local negate=false
292     if [ "$1" = "!" ] ; then
293         negate=true
294         shift
295     fi
296
297     echo -n "<${timeout}|"
298     local t=$timeout
299     while [ $t -gt 0 ] ; do
300         local rc=0
301         "$@" || rc=$?
302         if { ! $negate && [ $rc -eq 0 ] ; } || \
303             { $negate && [ $rc -ne 0 ] ; } ; then
304             echo "|$(($timeout - $t))|"
305             echo "OK"
306             return 0
307         fi
308         echo -n .
309         t=$(($t - 1))
310         sleep 1
311     done
312     
313     echo "*TIMEOUT*"
314     
315     return 1
316 }
317
318 sleep_for ()
319 {
320     echo -n "=${1}|"
321     for i in $(seq 1 $1) ; do
322         echo -n '.'
323         sleep 1
324     done
325     echo '|'
326 }
327
328 _cluster_is_healthy ()
329 {
330     local out x count line
331
332     out=$(ctdb -Y status 2>&1) || return 1
333
334     {
335         read x
336         count=0
337         while read line ; do
338             count=$(($count + 1))
339             [ "${line##:*:*:*1:}" != "$line" ] && return 1
340         done
341         [ $count -gt 0 ] && return $?
342     } <<<"$out" # Yay bash!
343 }
344
345 cluster_is_healthy ()
346 {
347     if onnode 0 $CTDB_TEST_WRAPPER _cluster_is_healthy ; then
348         echo "Cluster is HEALTHY"
349         return 0
350     else
351         echo "Cluster is UNHEALTHY"
352         if ! ${ctdb_test_restart_scheduled:-false} ; then
353             echo "DEBUG:"
354             local i
355             for i in "onnode -q 0 ctdb status" "onnode -q 0 onnode all ctdb scriptstatus" ; do
356                 echo "$i"
357                 $i || true
358             done
359         fi
360         return 1
361     fi
362 }
363
364 wait_until_healthy ()
365 {
366     local timeout="${1:-120}"
367
368     echo "Waiting for cluster to become healthy..."
369
370     wait_until 120 _cluster_is_healthy
371 }
372
373 # This function is becoming nicely overloaded.  Soon it will collapse!  :-)
374 node_has_status ()
375 {
376     local pnn="$1"
377     local status="$2"
378
379     local bits fpat mpat
380     case "$status" in
381         (unhealthy)    bits="?:?:?:1:*" ;;
382         (healthy)      bits="?:?:?:0:*" ;;
383         (disconnected) bits="1:*" ;;
384         (connected)    bits="0:*" ;;
385         (banned)       bits="?:1:*" ;;
386         (unbanned)     bits="?:0:*" ;;
387         (disabled)     bits="?:?:1:*" ;;
388         (enabled)      bits="?:?:0:*" ;;
389         (stopped)      bits="?:?:?:?:1:*" ;;
390         (notstopped)   bits="?:?:?:?:0:*" ;;
391         (frozen)       fpat='^[[:space:]]+frozen[[:space:]]+1$' ;;
392         (unfrozen)     fpat='^[[:space:]]+frozen[[:space:]]+0$' ;;
393         (monon)        mpat='^Monitoring mode:ACTIVE \(0\)$' ;;
394         (monoff)       mpat='^Monitoring mode:DISABLED \(1\)$' ;;
395         *)
396             echo "node_has_status: unknown status \"$status\""
397             return 1
398     esac
399
400     if [ -n "$bits" ] ; then
401         local out x line
402
403         out=$(ctdb -Y status 2>&1) || return 1
404
405         {
406             read x
407             while read line ; do
408                 # This needs to be done in 2 steps to avoid false matches.
409                 local line_bits="${line#:${pnn}:*:}"
410                 [ "$line_bits" = "$line" ] && continue
411                 [ "${line_bits#${bits}}" != "$line_bits" ] && return 0
412             done
413             return 1
414         } <<<"$out" # Yay bash!
415     elif [ -n "$fpat" ] ; then
416         ctdb statistics -n "$pnn" | egrep -q "$fpat"
417     elif [ -n "$mpat" ] ; then
418         ctdb getmonmode -n "$pnn" | egrep -q "$mpat"
419     else
420         echo 'node_has_status: unknown mode, neither $bits nor $fpat is set'
421         return 1
422     fi
423 }
424
425 wait_until_node_has_status ()
426 {
427     local pnn="$1"
428     local status="$2"
429     local timeout="${3:-30}"
430
431     echo "Waiting until node $pnn has status \"$status\"..."
432
433     if ! onnode any $CTDB_TEST_WRAPPER wait_until $timeout node_has_status "$pnn" "$status" ; then
434         for i in "onnode -q any ctdb status" "onnode -q any onnode all ctdb scriptstatus" ; do
435             echo "$i"
436             $i || true
437         done
438
439         return 1
440     fi
441
442 }
443
444 # Useful for superficially testing IP failover.
445 # IPs must be on nodes matching nodeglob.
446 ips_are_on_nodeglob ()
447 {
448     local nodeglob="$1" ; shift
449     local ips="$*"
450
451     local out
452
453     try_command_on_node 1 ctdb ip -n all
454
455     while read ip pnn ; do
456         for check in $ips ; do
457             if [ "$check" = "$ip" ] ; then
458                 case "$pnn" in
459                     ($nodeglob) : ;;
460                     (*) return 1  ;;
461                 esac
462                 ips="${ips/${ip}}" # Remove from list
463             fi
464         done
465     done <<<"$out" # bashism to avoid problem setting variable in pipeline.
466
467     ips="${ips// }" # Remove any spaces.
468     [ -z "$ips" ]
469 }
470
471 wait_until_ips_are_on_nodeglob ()
472 {
473     echo "Waiting for IPs to fail over..."
474
475     wait_until 60 ips_are_on_nodeglob "$@"
476 }
477
478 get_src_socket ()
479 {
480     local proto="$1"
481     local dst_socket="$2"
482     local pid="$3"
483     local prog="$4"
484
485     local pat="^${proto}[[:space:]]+[[:digit:]]+[[:space:]]+[[:digit:]]+[[:space:]]+[^[:space:]]+[[:space:]]+${dst_socket//./\\.}[[:space:]]+ESTABLISHED[[:space:]]+${pid}/${prog}[[:space:]]*\$"
486     out=$(netstat -tanp |
487         egrep "$pat" |
488         awk '{ print $4 }')
489
490     [ -n "$out" ]
491 }
492
493 wait_until_get_src_socket ()
494 {
495     local proto="$1"
496     local dst_socket="$2"
497     local pid="$3"
498     local prog="$4"
499
500     echo "Waiting for ${prog} to establish connection to ${dst_socket}..."
501
502     wait_until 5 get_src_socket "$@"
503 }
504
505 #######################################
506
507 # filename will be in $tcpdump_filename, pid in $tcpdump_pid
508 tcpdump_start ()
509 {
510     tcpdump_filter="$1" # global
511
512     echo "Running tcpdump..."
513     tcpdump_filename=$(mktemp)
514     ctdb_test_exit_hook_add "rm -f $tcpdump_filename"
515
516     # The only way of being sure that tcpdump is listening is to send
517     # some packets that it will see.  So we use dummy pings - the -U
518     # option to tcpdump ensures that packets are flushed to the file
519     # as they are captured.
520     local dummy_addr="127.3.2.1"
521     local dummy="icmp and dst host ${dummy_addr} and icmp[icmptype] == icmp-echo"
522     tcpdump -n -p -s 0 -e -U -w $tcpdump_filename -i any "($tcpdump_filter) or ($dummy)" &
523     ctdb_test_exit_hook_add "kill $! >/dev/null 2>&1"
524
525     echo "Waiting for tcpdump output file to be ready..."
526     ping -q "$dummy_addr" >/dev/null 2>&1 &
527     ctdb_test_exit_hook_add "kill $! >/dev/null 2>&1"
528
529     tcpdump_listen_for_dummy ()
530     {
531         tcpdump -n -r $tcpdump_filename -c 1 "$dummy" >/dev/null 2>&1
532     }
533
534     wait_until 10 tcpdump_listen_for_dummy
535 }
536
537 # By default, wait for 1 matching packet.
538 tcpdump_wait ()
539 {
540     local count="${1:-1}"
541     local filter="${2:-${tcpdump_filter}}"
542
543     tcpdump_check ()
544     {
545         local found=$(tcpdump -n -r $tcpdump_filename "$filter" 2>/dev/null | wc -l)
546         [ $found -ge $count ]
547     }
548
549     echo "Waiting for tcpdump to capture some packets..."
550     if ! wait_until 30 tcpdump_check ; then
551         echo "DEBUG:"
552         local i
553         for i in "onnode -q 0 ctdb status" "netstat -tanp" "tcpdump -n -e -r $tcpdump_filename" ; do
554             echo "$i"
555             $i || true
556         done
557         return 1
558     fi
559 }
560
561 tcpdump_show ()
562 {
563     local filter="${1:-${tcpdump_filter}}"
564
565     tcpdump -n -r $tcpdump_filename  "$filter" 2>/dev/null
566 }
567
568 tcptickle_sniff_start ()
569 {
570     local src="$1"
571     local dst="$2"
572
573     local in="src host ${dst%:*} and tcp src port ${dst##*:} and dst host ${src%:*} and tcp dst port ${src##*:}"
574     local out="src host ${src%:*} and tcp src port ${src##*:} and dst host ${dst%:*} and tcp dst port ${dst##*:}"
575     local tickle_ack="${in} and (tcp[tcpflags] & tcp-ack != 0) and (tcp[14] == 4) and (tcp[15] == 210)" # win == 1234
576     local ack_ack="${out} and (tcp[tcpflags] & tcp-ack != 0)"
577     tcptickle_reset="${in} and tcp[tcpflags] & tcp-rst != 0"
578     local filter="(${tickle_ack}) or (${ack_ack}) or (${tcptickle_reset})"
579
580     tcpdump_start "$filter"
581 }
582
583 tcptickle_sniff_wait_show ()
584 {
585     tcpdump_wait 1 "$tcptickle_reset"
586
587     echo "GOOD: here are some TCP tickle packets:"
588     tcpdump_show
589 }
590
591 gratarp_sniff_start ()
592 {
593     tcpdump_start "arp host ${test_ip}"
594 }
595
596 gratarp_sniff_wait_show ()
597 {
598     tcpdump_wait 2
599
600     echo "GOOD: this should be the some gratuitous ARPs:"
601     tcpdump_show
602 }
603
604
605 #######################################
606
607 daemons_stop ()
608 {
609     echo "Attempting to politely shutdown daemons..."
610     onnode 1 ctdb shutdown -n all || true
611
612     echo "Sleeping for a while..."
613     sleep_for 1
614
615     if pgrep -f $CTDB_DIR/bin/ctdbd >/dev/null ; then
616         echo "Killing remaining daemons..."
617         pkill -f $CTDB_DIR/bin/ctdbd
618
619         if pgrep -f $CTDB_DIR/bin/ctdbd >/dev/null ; then
620             echo "Once more with feeling.."
621             pkill -9 $CTDB_DIR/bin/ctdbd
622         fi
623     fi
624
625     local var_dir=$CTDB_DIR/tests/var
626     rm -rf $var_dir/test.db
627 }
628
629 daemons_setup ()
630 {
631     local num_nodes="${CTDB_TEST_NUM_DAEMONS:-2}" # default is 2 nodes
632
633     local var_dir=$CTDB_DIR/tests/var
634
635     mkdir -p $var_dir/test.db/persistent
636
637     local nodes=$var_dir/nodes.txt
638     local public_addresses=$var_dir/public_addresses.txt
639     local no_public_addresses=$var_dir/no_public_addresses.txt
640     rm -f $nodes $public_addresses $no_public_addresses
641
642     # If there are (strictly) greater than 2 nodes then we'll randomly
643     # choose a node to have no public addresses.
644     local no_public_ips=-1
645     [ $num_nodes -gt 2 ] && no_public_ips=$(($RANDOM % $num_nodes))
646     echo "$no_public_ips" >$no_public_addresses
647
648     local i
649     for i in $(seq 1 $num_nodes) ; do
650         if [ "${CTDB_USE_IPV6}x" != "x" ]; then
651             echo ::$i >> $nodes
652             ip addr add ::$i/128 dev lo
653         else
654             echo 127.0.0.$i >> $nodes
655             # 2 public addresses on most nodes, just to make things interesting.
656             if [ $(($i - 1)) -ne $no_public_ips ] ; then
657                 echo "192.0.2.$i/24 lo" >> $public_addresses
658                 echo "192.0.2.$(($i + $num_nodes))/24 lo" >> $public_addresses
659             fi
660         fi
661     done
662 }
663
664 daemons_start_1 ()
665 {
666     local pnn="$1"
667     shift # "$@" gets passed to ctdbd
668
669     local var_dir=$CTDB_DIR/tests/var
670
671     local nodes=$var_dir/nodes.txt
672     local public_addresses=$var_dir/public_addresses.txt
673     local no_public_addresses=$var_dir/no_public_addresses.txt
674
675     local no_public_ips=-1
676     [ -r $no_public_addresses ] && read no_public_ips <$no_public_addresses
677
678     if  [ "$no_public_ips" = $pnn ] ; then
679         echo "Node $no_public_ips will have no public IPs."
680     fi
681
682     local ctdb_options="--reclock=$var_dir/rec.lock --nlist $nodes --nopublicipcheck --event-script-dir=$CTDB_DIR/tests/events.d --logfile=$var_dir/daemons.log -d 0 --dbdir=$var_dir/test.db --dbdir-persistent=$var_dir/test.db/persistent"
683
684     if [ $(id -u) -eq 0 ]; then
685         ctdb_options="$ctdb_options --public-interface=lo"
686     fi
687
688     if [ $pnn -eq $no_public_ips ] ; then
689         ctdb_options="$ctdb_options --public-addresses=/dev/null"
690     else
691         ctdb_options="$ctdb_options --public-addresses=$public_addresses"
692     fi
693
694     # Need full path so we can use "pkill -f" to kill the daemons.
695     $VALGRIND $CTDB_DIR/bin/ctdbd --socket=$var_dir/sock.$pnn $ctdb_options "$@" ||return 1
696 }
697
698 daemons_start ()
699 {
700     # "$@" gets passed to ctdbd
701
702     local num_nodes="${CTDB_TEST_NUM_DAEMONS:-2}" # default is 2 nodes
703
704     echo "Starting $num_nodes ctdb daemons..."
705
706     for i in $(seq 0 $(($num_nodes - 1))) ; do
707         daemons_start_1 $i "$@"
708     done
709
710     local var_dir=$CTDB_DIR/tests/var
711
712     if [ -L /tmp/ctdb.socket -o ! -S /tmp/ctdb.socket ] ; then 
713         ln -sf $var_dir/sock.0 /tmp/ctdb.socket || return 1
714     fi
715 }
716
717 #######################################
718
719 _ctdb_hack_options ()
720 {
721     local ctdb_options="$*"
722
723     # We really just want to pass CTDB_OPTIONS but on RH
724     # /etc/sysconfig/ctdb can, and frequently does, set that variable.
725     # So instead, we hack badly.  We'll add these as we use them.
726     # Note that these may still be overridden by the above file... but
727     # we tend to use the exotic options here... so that is unlikely.
728
729     case "$ctdb_options" in
730         *--start-as-stopped*)
731             export CTDB_START_AS_STOPPED="yes"
732     esac
733 }
734
735 _restart_ctdb ()
736 {
737     _ctdb_hack_options "$@"
738
739     if [ -e /etc/redhat-release ] ; then
740         service ctdb restart
741     else
742         /etc/init.d/ctdb restart
743     fi
744 }
745
746 _ctdb_start ()
747 {
748     _ctdb_hack_options "$@"
749
750     /etc/init.d/ctdb start
751 }
752
753 setup_ctdb ()
754 {
755     if [ -n "$CTDB_NODES_SOCKETS" ] ; then
756         daemons_setup
757     fi
758 }
759
760 # Common things to do after starting one or more nodes.
761 _ctdb_start_post ()
762 {
763     onnode -q 1  $CTDB_TEST_WRAPPER wait_until_healthy || return 1
764
765     echo "Setting RerecoveryTimeout to 1"
766     onnode -pq all "ctdb setvar RerecoveryTimeout 1"
767
768     # In recent versions of CTDB, forcing a recovery like this blocks
769     # until the recovery is complete.  Hopefully this will help the
770     # cluster to stabilise before a subsequent test.
771     echo "Forcing a recovery..."
772     onnode -q 0 ctdb recover
773     sleep_for 1
774     echo "Forcing a recovery..."
775     onnode -q 0 ctdb recover
776
777     echo "ctdb is ready"
778 }
779
780 # This assumes that ctdbd is not running on the given node.
781 ctdb_start_1 ()
782 {
783     local pnn="$1"
784     shift # "$@" is passed to ctdbd start.
785
786     echo -n "Starting CTDB on node ${pnn}..."
787     
788     if [ -n "$CTDB_NODES_SOCKETS" ] ; then
789         daemons_start_1 $pnn "$@"
790     else
791         onnode $pnn $CTDB_TEST_WRAPPER _ctdb_start "$@"
792     fi
793
794     # If we're starting only 1 node then we're doing something weird.
795     ctdb_restart_when_done
796 }
797
798 restart_ctdb ()
799 {
800     # "$@" is passed to ctdbd start.
801
802     echo -n "Restarting CTDB"
803     if $ctdb_test_restart_scheduled ; then
804         echo -n " (scheduled)"
805     fi
806     echo "..."
807     
808     local i=0
809     while : ; do
810         if [ -n "$CTDB_NODES_SOCKETS" ] ; then
811             daemons_stop
812             daemons_start "$@"
813         else
814             onnode -p all $CTDB_TEST_WRAPPER _restart_ctdb "$@"
815         fi && break
816
817         i=$(($i + 1))
818         [ $i -lt 5 ] || break
819
820         echo "That didn't seem to work - sleeping for a while..."
821         sleep_for 5
822     done
823         
824     onnode -q 1  $CTDB_TEST_WRAPPER wait_until_healthy || return 1
825
826     echo "Setting RerecoveryTimeout to 1"
827     onnode -pq all "ctdb setvar RerecoveryTimeout 1"
828
829     # In recent versions of CTDB, forcing a recovery like this blocks
830     # until the recovery is complete.  Hopefully this will help the
831     # cluster to stabilise before a subsequent test.
832     echo "Forcing a recovery..."
833     onnode -q 0 ctdb recover
834     sleep_for 1
835     echo "Forcing a recovery..."
836     onnode -q 0 ctdb recover
837
838     echo "ctdb is ready"
839 }
840
841 ctdb_restart_when_done ()
842 {
843     ctdb_test_restart_scheduled=true
844 }
845
846 #######################################
847
848 install_eventscript ()
849 {
850     local script_name="$1"
851     local script_contents="$2"
852
853     if [ -n "$CTDB_TEST_REAL_CLUSTER" ] ; then
854         # The quoting here is *very* fragile.  However, we do
855         # experience the joy of installing a short script using
856         # onnode, and without needing to know the IP addresses of the
857         # nodes.
858         onnode all "f=\"\${CTDB_BASE:-/etc/ctdb}/events.d/${script_name}\" ; echo \"Installing \$f\" ; echo '${script_contents}' > \"\$f\" ; chmod 755 \"\$f\""
859     else
860         f="${CTDB_DIR}/tests/events.d/${script_name}"
861         echo "$script_contents" >"$f"
862         chmod 755 "$f"
863     fi
864 }
865
866 uninstall_eventscript ()
867 {
868     local script_name="$1"
869
870     if [ -n "$CTDB_TEST_REAL_CLUSTER" ] ; then
871         onnode all "rm -vf \"\${CTDB_BASE:-/etc/ctdb}/events.d/${script_name}\""
872     else
873         rm -vf "${CTDB_DIR}/tests/events.d/${script_name}"
874     fi
875 }
876
877 #######################################
878
879 # This section deals with the 99.ctdb_test eventscript.
880
881 # Metafunctions: Handle a ctdb-test file on a node.
882 # given event.
883 ctdb_test_eventscript_file_create ()
884 {
885     local pnn="$1"
886     local type="$2"
887
888     try_command_on_node $pnn touch "/tmp/ctdb-test-${type}.${pnn}"
889 }
890
891 ctdb_test_eventscript_file_remove ()
892 {
893     local pnn="$1"
894     local type="$2"
895
896     try_command_on_node $pnn rm -f "/tmp/ctdb-test-${type}.${pnn}"
897 }
898
899 ctdb_test_eventscript_file_exists ()
900 {
901     local pnn="$1"
902     local type="$2"
903
904     try_command_on_node $pnn test -f "/tmp/ctdb-test-${type}.${pnn}" >/dev/null 2>&1
905 }
906
907
908 # Handle a flag file on a node that is removed by 99.ctdb_test on the
909 # given event.
910 ctdb_test_eventscript_flag ()
911 {
912     local cmd="$1"
913     local pnn="$2"
914     local event="$3"
915
916     ctdb_test_eventscript_file_${cmd} "$pnn" "flag-${event}"
917 }
918
919
920 # Handle a trigger that causes 99.ctdb_test to fail it's monitor
921 # event.
922 ctdb_test_eventscript_unhealthy_trigger ()
923 {
924     local cmd="$1"
925     local pnn="$2"
926
927     ctdb_test_eventscript_file_${cmd} "$pnn" "unhealthy-trigger"
928 }
929
930 # Handle the file that 99.ctdb_test created to show that it has marked
931 # a node unhealthy because it detected the above trigger.
932 ctdb_test_eventscript_unhealthy_detected ()
933 {
934     local cmd="$1"
935     local pnn="$2"
936
937     ctdb_test_eventscript_file_${cmd} "$pnn" "unhealthy-detected"
938 }
939
940 # Note that the eventscript can't use the above functions!
941 ctdb_test_eventscript_install ()
942 {
943
944     local script='#!/bin/sh
945 out=$(ctdb pnn)
946 pnn="${out#PNN:}"
947
948 rm -vf "/tmp/ctdb-test-flag-${1}.${pnn}"
949
950 trigger="/tmp/ctdb-test-unhealthy-trigger.${pnn}"
951 detected="/tmp/ctdb-test-unhealthy-detected.${pnn}"
952 if [ "$1" = "monitor" ] ; then
953     if [ -e "$trigger" ] ; then
954         echo "${0}: Unhealthy because \"$trigger\" detected"
955         touch "$detected"
956         exit 1
957     elif [ -e "$detected" -a ! -e "$trigger" ] ; then
958         echo "${0}: Healthy again, \"$trigger\" no longer detected"
959         rm "$detected"
960     fi
961 fi
962
963 exit 0
964 '
965     install_eventscript "99.ctdb_test" "$script"
966 }
967
968 ctdb_test_eventscript_uninstall ()
969 {
970     uninstall_eventscript "99.ctdb_test"
971 }
972
973 # Note that this only works if you know all other monitor events will
974 # succeed.  You also need to install the eventscript before using it.
975 wait_for_monitor_event ()
976 {
977     local pnn="$1"
978
979     echo "Waiting for a monitor event on node $pnn to complete..."
980     ctdb_test_eventscript_flag create $pnn "monitor"
981
982     wait_until 120 ! ctdb_test_eventscript_flag exists $pnn "monitor"
983
984 }