tests/eventscripts - Restructure according to new convention
[samba.git] / ctdb / tests / eventscripts / scripts / local.sh
1 # Hey Emacs, this is a -*- shell-script -*- !!!  :-)
2
3 # Augment PATH with relevant stubs/ directories.  We do this by actually
4 # setting PATH, and also by setting $EVENTSCRIPTS_PATH and then
5 # prepending that to $PATH in rc.local to avoid the PATH reset in
6 # functions.
7
8 EVENTSCRIPTS_PATH=""
9
10 if [ -d "${TEST_SUBDIR}/stubs" ] ; then
11     EVENTSCRIPTS_PATH="${TEST_SUBDIR}/stubs"
12 fi
13
14 export EVENTSCRIPTS_PATH
15
16 PATH="${EVENTSCRIPTS_PATH}:${PATH}"
17
18 if [ -d "${TEST_SUBDIR}/etc" ] ; then
19     CTDB_ETCDIR="${TEST_SUBDIR}/etc"
20 else
21     die "Unable to set \$CTDB_ETCDIR"
22 fi
23 export CTDB_ETCDIR
24
25 if [ -d "${TEST_SUBDIR}/etc-ctdb" ] ; then
26     CTDB_BASE="${TEST_SUBDIR}/etc-ctdb"
27 else
28     die "Unable to set \$CTDB_BASE"
29 fi
30 export CTDB_BASE
31
32 export EVENTSCRIPTS_TESTS_VAR_DIR="${TEST_SUBDIR}/var"
33 if [ "$EVENTSCRIPTS_TESTS_VAR_DIR" != "/var" ] ; then
34     rm -r "$EVENTSCRIPTS_TESTS_VAR_DIR"
35 fi
36 mkdir -p "$EVENTSCRIPTS_TESTS_VAR_DIR"
37 export CTDB_VARDIR="$EVENTSCRIPTS_TESTS_VAR_DIR/ctdb"
38
39 ######################################################################
40
41 if [ "$TEST_VERBOSE" = "yes" ] ; then
42     debug () { echo "$@" ; }
43 else
44     debug () { : ; }
45 fi
46
47 eventscripts_tests_cleanup_hooks=""
48
49 # This loses quoting!
50 eventscripts_test_add_cleanup ()
51 {
52     eventscripts_tests_cleanup_hooks="${eventscripts_tests_cleanup_hooks}${eventscripts_tests_cleanup_hooks:+ ; }$*"
53 }
54
55 trap 'eval $eventscripts_tests_cleanup_hooks' 0
56
57
58 ######################################################################
59
60 # General setup fakery
61
62 setup_generic ()
63 {
64     debug "Setting up shares (3 existing shares)"
65     # Create 3 fake shares/exports.
66     export FAKE_SHARES=""
67     for i in $(seq 1 3) ; do
68         _s="${EVENTSCRIPTS_TESTS_VAR_DIR}/shares/${i}_existing"
69         mkdir -p "$_s"
70         FAKE_SHARES="${FAKE_SHARES}${FAKE_SHARES:+ }${_s}"
71     done
72
73     export FAKE_PROC_NET_BONDING="$EVENTSCRIPTS_TESTS_VAR_DIR/proc-net-bonding"
74     mkdir -p "$FAKE_PROC_NET_BONDING"
75     rm -f "$FAKE_PROC_NET_BONDING"/*
76
77     export FAKE_ETHTOOL_LINK_DOWN="$EVENTSCRIPTS_TESTS_VAR_DIR/ethtool-link-down"
78     mkdir -p "$FAKE_ETHTOOL_LINK_DOWN"
79     rm -f "$FAKE_ETHTOOL_LINK_DOWN"/*
80
81     # This can only have 2 levels.  We don't want to resort to usings
82     # something dangerous like "rm -r" setup time.
83     export FAKE_IP_STATE="$EVENTSCRIPTS_TESTS_VAR_DIR/fake-ip-state"
84     mkdir -p "$FAKE_IP_STATE"
85     rm -f "$FAKE_IP_STATE"/*/*
86     rm -f "$FAKE_IP_STATE"/* 2>/dev/null || true
87     rmdir "$FAKE_IP_STATE"/* 2>/dev/null || true
88 }
89
90 tcp_port_down ()
91 {
92     for _i ; do
93         debug "Marking TCP port \"${_i}\" as not listening"
94         FAKE_TCP_LISTEN=$(echo "$FAKE_TCP_LISTEN" | sed -r -e "s@[[:space:]]*[\.0-9]+:${_i}@@g")
95     done
96 }
97
98 shares_missing ()
99 {
100     _fmt="$1" ; shift
101
102     # Replace some shares with non-existent ones.
103     _t=""
104     _n=1
105     _nl="
106 "
107     export MISSING_SHARES_TEXT=""
108     for _i in $FAKE_SHARES ; do
109         if [ $_n = "$1" ] ; then
110             shift
111             _i="${_i%_existing}_missing"
112             debug "Replacing share $_n with missing share \"$_i\""
113             rmdir "$_i" 2>/dev/null || true
114             MISSING_SHARES_TEXT="${MISSING_SHARES_TEXT}${MISSING_SHARES_TEXT:+${_nl}}"$(printf "$_fmt" "${_i}")
115         fi
116         _t="${_t}${_t:+ }${_i}"
117         _n=$(($_n + 1))
118     done
119     FAKE_SHARES="$_t"
120 }
121
122 # Setup some fake /proc/net/bonding files with just enough info for
123 # the eventscripts.
124
125 # arg1 is interface name, arg2 is currently active slave (use "None"
126 # if none), arg3 is MII status ("up" or "down").
127 setup_bond ()
128 {
129     _iface="$1"
130     _slave="${2:-${_iface}_sl_0}"
131     _mii_s="${3:-up}"
132     _mii_subs="${4:-${_mii_s:-up}}"
133     echo "Setting $_iface to be a bond with active slave $_slave and MII status $_mii_s"
134     cat >"${FAKE_PROC_NET_BONDING}/$_iface" <<EOF
135 Bonding Mode: IEEE 802.3ad Dynamic link aggregation
136 Currently Active Slave: $_slave
137 # Status of the bond
138 MII Status: $_mii_s
139 # Status of 1st pretend adapter
140 MII Status: $_mii_subs
141 # Status of 2nd pretend adapter
142 MII Status: $_mii_subs
143 EOF
144 }
145
146 ethtool_interfaces_down ()
147 {
148     for _i ; do
149         echo "Marking interface $_i DOWN for ethtool"
150         touch "${FAKE_ETHTOOL_LINK_DOWN}/${_i}"
151     done
152 }
153
154 ethtool_interfaces_up ()
155 {
156     for _i ; do
157         echo "Marking interface $_i UP for ethtool"
158         rm -f "${FAKE_ETHTOOL_LINK_DOWN}/${_i}"
159     done
160 }
161
162 setup_nmap_output_filter ()
163 {
164     OUT_FILTER="-e 's@^(DEBUG: # Nmap 5.21 scan initiated) .+ (as:)@\1 DATE \2@' -e 's@^(DEBUG: # Nmap done at) .+ (--)@\1 DATE \2@'"
165 }
166
167 dump_routes ()
168 {
169     echo "# ip rule show"
170     ip rule show
171
172     ip rule show |
173     while read _p _x _i _x _t ; do
174         # Remove trailing colon after priority/preference.
175         _p="${_p%:}"
176         # Only remove rules that match our priority/preference.
177         [ "$CTDB_PER_IP_ROUTING_RULE_PREF" = "$_p" ] || continue
178
179         echo "# ip route show table $_t"
180         ip route show table "$_t"
181     done
182 }
183
184 # Copied from 13.per_ip_routing for now... so this is lazy testing  :-(
185 ipv4_host_addr_to_net ()
186 {
187     _host="$1"
188     _maskbits="$2"
189
190     # Convert the host address to an unsigned long by splitting out
191     # the octets and doing the math.
192     _host_ul=0
193     for _o in $(export IFS="." ; echo $_host) ; do
194         _host_ul=$(( ($_host_ul << 8) + $_o)) # work around Emacs color bug
195     done
196
197     # Calculate the mask and apply it.
198     _mask_ul=$(( 0xffffffff << (32 - $_maskbits) ))
199     _net_ul=$(( $_host_ul & $_mask_ul ))
200
201     # Now convert to a network address one byte at a time.
202     _net=""
203     for _o in $(seq 1 4) ; do
204         _net="$(($_net_ul & 255))${_net:+.}${_net}"
205         _net_ul=$(($_net_ul >> 8))
206     done
207
208     echo "${_net}/${_maskbits}"
209 }
210
211 ######################################################################
212
213 # CTDB fakery
214
215 # Evaluate an expression that probably calls functions or uses
216 # variables from the CTDB functions file.  This is used for test
217 # initialisation.
218 eventscript_call ()
219 {
220     (
221         . "$CTDB_BASE/functions"
222         "$@"
223     )
224 }
225
226 # Set output for ctdb command.  Option 1st argument is return code.
227 ctdb_set_output ()
228 {
229     _out="$EVENTSCRIPTS_TESTS_VAR_DIR/ctdb.out"
230     cat >"$_out"
231
232     _rc="$EVENTSCRIPTS_TESTS_VAR_DIR/ctdb.rc"
233     echo "${1:-0}" >"$_rc"
234
235     eventscripts_test_add_cleanup "rm -f $_out $_rc"
236 }
237
238 setup_ctdb ()
239 {
240     setup_generic
241
242     export FAKE_CTDB_NUMNODES="${1:-3}"
243     echo "Setting up CTDB with ${FAKE_CTDB_NUMNODES} fake nodes"
244
245     export FAKE_CTDB_PNN="${2:-0}"
246     echo "Setting up CTDB with PNN ${FAKE_CTDB_PNN}"
247
248     if [ -n "$3" ] ; then
249         echo "Setting up CTDB_PUBLIC_ADDRESSES: $3"
250         export CTDB_PUBLIC_ADDRESSES=$(mktemp)
251         for _i in $3 ; do
252             _ip="${_i%@*}"
253             _ifaces="${_i#*@}"
254             echo "${_ip} ${_ifaces}" >>"$CTDB_PUBLIC_ADDRESSES"
255         done
256         eventscripts_test_add_cleanup "rm -f $CTDB_PUBLIC_ADDRESSES"
257     fi
258
259     export FAKE_CTDB_STATE="$EVENTSCRIPTS_TESTS_VAR_DIR/fake-ctdb"
260
261     export FAKE_CTDB_IFACES_DOWN="$FAKE_CTDB_STATE/ifaces-down"
262     mkdir -p "$FAKE_CTDB_IFACES_DOWN"
263     rm -f "$FAKE_CTDB_IFACES_DOWN"/*
264
265     export FAKE_CTDB_SCRIPTSTATUS="$FAKE_CTDB_STATE/scriptstatus"
266     mkdir -p "$FAKE_CTDB_SCRIPTSTATUS"
267     rm -f "$FAKE_CTDB_SCRIPTSTATUS"/*
268 }
269
270 ctdb_get_interfaces ()
271 {
272     # The echo/subshell forces all the output onto 1 line.
273     echo $(ctdb ifaces -Y | awk -F: 'FNR > 1 {print $2}')
274 }
275
276 ctdb_get_1_interface ()
277 {
278     _t=$(ctdb_get_interfaces)
279     echo ${_t%% *}
280 }
281
282 # Print all public addresses as: interface IP maskbits
283 # Each line is suitable for passing to takeip/releaseip
284 ctdb_get_all_public_addresses ()
285 {
286     _f="${CTDB_PUBLIC_ADDRESSES:-${CTDB_BASE}/public_addresses}"
287     while IFS="/$IFS" read _ip _maskbits _ifaces ; do
288         echo "$_ifaces $_ip $_maskbits"
289     done <"$_f"
290 }
291
292 # Print public addresses on this node as: interface IP maskbits
293 # Each line is suitable for passing to takeip/releaseip
294 ctdb_get_my_public_addresses ()
295 {
296     ctdb ip -v -Y | {
297         read _x # skip header line
298
299         while IFS=":" read _x _ip _x _iface _x ; do
300             [ -n "$_iface" ] || continue
301             while IFS="/$IFS" read _i _maskbits _x ; do
302                 if [ "$_ip" = "$_i" ] ; then
303                     echo $_iface $_ip $_maskbits
304                     break
305                 fi
306             done <"${CTDB_PUBLIC_ADDRESSES:-${CTDB_BASE}/public_addresses}"
307         done
308     }
309 }
310
311 # Prints the 1st public address as: interface IP maskbits
312 # This is suitable for passing to takeip/releaseip
313 ctdb_get_1_public_address ()
314 {
315     ctdb_get_my_public_addresses | head -n 1
316 }
317
318 ctdb_not_implemented ()
319 {
320     export CTDB_NOT_IMPLEMENTED="$1"
321     ctdb_not_implemented="\
322 DEBUG: ctdb: command \"$1\" not implemented in stub"
323 }
324
325 ctdb_fake_scriptstatus ()
326 {
327     _code="$1"
328     _status="$2"
329     _err_out="$3"
330
331     _d1=$(date '+%s.%N')
332     _d2=$(date '+%s.%N')
333
334     echo "$_code $_status $_err_out" >"$FAKE_CTDB_SCRIPTSTATUS/$script"
335 }
336
337 setup_ctdb_policy_routing ()
338 {
339     export CTDB_PER_IP_ROUTING_CONF="$CTDB_BASE/policy_routing"
340     export CTDB_PER_IP_ROUTING_RULE_PREF=100
341     export CTDB_PER_IP_ROUTING_TABLE_ID_LOW=1000
342     export CTDB_PER_IP_ROUTING_TABLE_ID_HIGH=2000
343
344     # Tests need to create and populate this file
345     rm -f "$CTDB_PER_IP_ROUTING_CONF"
346 }
347
348 ######################################################################
349
350 # Samba fakery
351
352 setup_samba ()
353 {
354     setup_ctdb
355
356     if [ "$1" != "down" ] ; then
357
358         debug "Marking Samba services as up, listening and managed by CTDB"
359         # Get into known state.
360         for i in "samba" "winbind" ; do
361             eventscript_call ctdb_service_managed "$i"
362         done
363         # All possible service names for all known distros.
364         for i in "smb" "nmb" "winbind" "samba" ; do
365             service "$i" force-started
366         done
367
368         export CTDB_SAMBA_SKIP_SHARE_CHECK="no"
369         export CTDB_MANAGED_SERVICES="foo samba winbind bar"
370
371         export FAKE_TCP_LISTEN="0.0.0.0:445 0.0.0.0:139"
372         export FAKE_WBINFO_FAIL="no"
373
374         # Some things in 50.samba are backgrounded and waited for.  If
375         # we don't sleep at all then timeouts can happen.  This avoids
376         # that...  :-)
377         export FAKE_SLEEP_FORCE=0.1
378     else
379         debug "Marking Samba services as down, not listening and not managed by CTDB"
380         # Get into known state.
381         for i in "samba" "winbind" ; do
382             eventscript_call ctdb_service_unmanaged "$i"
383         done
384         # All possible service names for all known distros.
385         for i in "smb" "nmb" "winbind" "samba" ; do
386             service "$i" force-stopped
387         done
388
389         export CTDB_SAMBA_SKIP_SHARE_CHECK="no"
390         export CTDB_MANAGED_SERVICES="foo bar"
391         unset CTDB_MANAGES_SAMBA
392         unset CTDB_MANAGES_WINBIND
393
394         export FAKE_TCP_LISTEN=""
395         export FAKE_WBINFO_FAIL="yes"
396     fi
397
398     # This is ugly but if this file isn't removed before each test
399     # then configuration changes between tests don't stick.
400     rm -f "$CTDB_VARDIR/state/samba/smb.conf.cache"
401 }
402
403 wbinfo_down ()
404 {
405     debug "Making wbinfo commands fail"
406     FAKE_WBINFO_FAIL="yes"
407 }
408
409 ######################################################################
410
411 # NFS fakery
412
413 setup_nfs ()
414 {
415     setup_ctdb
416
417     export FAKE_RPCINFO_SERVICES=""
418
419     export CTDB_NFS_SKIP_SHARE_CHECK="no"
420     export CTDB_NFS_SKIP_KNFSD_ALIVE_CHECK="no"
421
422     # Reset the failcounts for nfs services.
423     eventscript_call eval rm -f '$ctdb_fail_dir/nfs_*'
424
425     rpc_fail_limits_file="${EVENTSCRIPTS_TESTS_VAR_DIR}/rpc_fail_limits"
426
427     # Force this file to exist so tests can be individually run.
428     if [ ! -f "$rpc_fail_limits_file" ] ; then
429         # This is gross... but is needed to fake through the nfs monitor event.
430         eventscript_call ctdb_service_managed "nfs"
431         service "nfs" force-started  # might not be enough
432         CTDB_RC_LOCAL="$CTDB_BASE/rc.local.nfs.monitor.get-limits" \
433             CTDB_MANAGES_NFS="yes" \
434             "${CTDB_BASE}/events.d/60.nfs" "monitor" >"$rpc_fail_limits_file"
435     fi
436     
437     if [ "$1" != "down" ] ; then
438         debug "Setting up NFS environment: all RPC services up, NFS managed by CTDB"
439
440         eventscript_call ctdb_service_managed "nfs"
441         service "nfs" force-started  # might not be enough
442
443         export CTDB_MANAGED_SERVICES="foo nfs bar"
444
445         rpc_services_up "nfs" "mountd" "rquotad" "nlockmgr" "status"
446     else
447         debug "Setting up NFS environment: all RPC services down, NFS not managed by CTDB"
448
449         eventscript_call ctdb_service_unmanaged "nfs"
450         service "nfs" force-stopped  # might not be enough
451         eventscript_call startstop_nfs stop
452
453         export CTDB_MANAGED_SERVICES="foo bar"
454         unset CTDB_MANAGES_NFS
455     fi
456 }
457
458 rpc_services_down ()
459 {
460     for _i ; do
461         debug "Marking RPC service \"${_i}\" as unavailable"
462         FAKE_RPCINFO_SERVICES=$(echo "$FAKE_RPCINFO_SERVICES" | sed -r -e "s@[[:space:]]*${_i}:[0-9]+:[0-9]+@@g")
463     done
464 }
465
466 rpc_services_up ()
467 {
468     for _i ; do
469         debug "Marking RPC service \"${_i}\" as available"
470         case "$_i" in
471             nfs)      _t="2:3" ;;
472             mountd)   _t="1:3" ;;
473             rquotad)  _t="1:2" ;;
474             nlockmgr) _t="3:4" ;;
475             status)   _t="1:1" ;;
476             *) die "Internal error - unsupported RPC service \"${_i}\"" ;;
477         esac
478
479         FAKE_RPCINFO_SERVICES="${FAKE_RPCINFO_SERVICES}${FAKE_RPCINFO_SERVICES:+ }${_i}:${_t}"
480     done
481 }
482
483 # Set the required result for a particular RPC program having failed
484 # for a certain number of iterations.  This is probably still a work
485 # in progress.  Note that we could hook aggressively
486 # nfs_check_rpc_service() to try to implement this but we're better
487 # off testing nfs_check_rpc_service() using independent code...  even
488 # if it is incomplete and hacky.  So, if the 60.nfs eventscript
489 # changes and the tests start to fail then it may be due to this
490 # function being incomplete.
491 rpc_set_service_failure_response ()
492 {
493     _progname="$1"
494     # The number of failures defaults to the iteration number.  This
495     # will be true when we fail from the 1st iteration... but we need
496     # the flexibility to set the number of failures.
497     _numfails="${2:-${iteration}}"
498
499     _etc="$CTDB_ETCDIR" # shortcut for readability
500     for _c in "$_etc/sysconfig/nfs" "$_etc/default/nfs" "$_etc/ctdb/sysconfig/nfs" ; do
501         if [ -r "$_c" ] ; then
502             . "$_c"
503             break
504         fi
505     done
506
507     # A handy newline.  :-)
508     _nl="
509 "
510
511     # Default
512     ok_null
513
514     _ts=$(sed -n -e "s@^${_progname} @@p" "$rpc_fail_limits_file")
515
516     while [ -n "$_ts" ] ; do
517         # Get the triple: operator, fail limit and actions.
518         _op="${_ts%% *}" ; _ts="${_ts#* }"
519         _li="${_ts%% *}" ; _ts="${_ts#* }"
520         # We've lost some of the quoting but we can simulate
521         # because we know an operator is always the first in a
522         # triple.
523         _actions=""
524         while [ -n "$_ts" ] ; do
525             # If this is an operator then we've got all of the
526             # actions.
527             case "$_ts" in
528                 -*) break ;;
529             esac
530
531             _actions="${_actions}${_actions:+ }${_ts%% *}"
532             # Special case for end of list.
533             if [ "$_ts" != "${_ts#* }" ] ; then
534                 _ts="${_ts#* }"
535             else
536                 _ts=""
537             fi
538         done
539
540         if [ "$_numfails" "$_op" "$_li" ] ; then
541             _out=""
542             _rc=0
543             for _action in $_actions ; do
544                 case "$_action" in
545                     verbose)
546                         _ver=1
547                         _pn="$_progname"
548                         case "$_progname" in
549                             knfsd) _ver=3 ; _pn="nfs" ;;
550                             lockd) _ver=4 ; _pn="nlockmgr" ;;
551                             statd) _pn="status" ;;
552                         esac
553                         _out="\
554 ERROR: $_pn failed RPC check:
555 rpcinfo: RPC: Program not registered
556 program $_pn version $_ver is not available"
557                         ;;
558                     restart|restart:*)
559                         _opts=""
560                         _p="rpc.${_progname}"
561                         case "$_progname" in
562                             statd)
563                                 _opts="${STATD_HOSTNAME:+ -n }${STATD_HOSTNAME}"
564                                 ;;
565                         esac
566                         case "${_progname}${_action#restart}" in
567                             knfsd)
568                                 _t="\
569 Trying to restart NFS service
570 Starting nfslock: OK
571 Starting nfs: OK"
572                                 ;;
573                             knfsd:bs)
574                                 _t="Trying to restart NFS service"
575                                 ;;
576                             lockd)
577                                 _t="\
578 Trying to restart lock manager service
579 Stopping nfslock: OK
580 Starting nfslock: OK"
581                                 ;;
582                             lockd:*)
583                                 _t="Trying to restart lock manager service"
584                                 ;;
585                             *)
586                                 _t="Trying to restart $_progname [${_p}${_opts}]"
587                         esac
588                         _out="${_out}${_out:+${_nl}}${_t}"
589                         ;;
590                     unhealthy)
591                         _rc=1
592                 esac
593             done
594             required_result $_rc "$_out"
595             return
596         fi
597     done
598 }
599
600 ######################################################################
601
602 # VSFTPD fakery
603
604 setup_vsftpd ()
605 {
606     if [ "$1" != "down" ] ; then
607         die "setup_vsftpd up not implemented!!!"
608     else
609         debug "Setting up VSFTPD environment: service down, not managed by CTDB"
610
611         eventscript_call ctdb_service_unmanaged vsftpd
612         service vsftpd force-stopped
613
614         export CTDB_MANAGED_SERVICES="foo"
615         unset CTDB_MANAGES_VSFTPD
616     fi
617 }
618
619 ######################################################################
620
621 # HTTPD fakery
622
623 setup_httpd ()
624 {
625     if [ "$1" != "down" ] ; then
626         die "setup_httpd up not implemented!!!"
627     else
628         debug "Setting up HTTPD environment: service down, not managed by CTDB"
629
630         for i in "apache2" "httpd" ; do
631             eventscript_call ctdb_service_unmanaged "$i"
632             service "$i" force-stopped
633         done
634
635         export CTDB_MANAGED_SERVICES="foo"
636         unset CTDB_MANAGES_HTTPD
637     fi
638 }
639
640 ######################################################################
641
642 # Result and test functions
643
644 # Set some globals and print the summary.
645 define_test ()
646 {
647     desc="$1"
648
649     _f=$(basename "$0" ".sh")
650
651     # Remaining format should be NN.service.event.NNN or NN.service.NNN:
652     _num="${_f##*.}"
653     _f="${_f%.*}"
654     case "$_f" in
655         *.*.*)
656             script="${_f%.*}"
657             event="${_f##*.}"
658             ;;
659         *.*)
660             script="$_f"
661             unset event
662             ;;
663         *)
664             die "Internal error - unknown testcase filename format"
665     esac
666
667     printf "%-17s %-10s %-4s - %s\n\n" "$script" "$event" "$_num" "$desc"
668 }
669
670 # Set the required result for a test.
671 # - Argument 1 is exit code.
672 # - Argument 2, if present is the required test output but "--"
673 #   indicates empty output.
674 # If argument 2 is not present or null then read required test output
675 # from stdin.
676 required_result ()
677 {
678     required_rc="${1:-0}"
679     if [ -n "$2" ] ; then
680         if [ "$2" = "--" ] ; then
681             required_output=""
682         else
683             required_output="$2"
684         fi
685     else
686         if ! tty -s ; then
687             required_output=$(cat)
688         else
689             required_output=""
690         fi
691     fi
692 }
693
694 ok ()
695 {
696     required_result 0 "$@"
697 }
698
699 ok_null ()
700 {
701     ok --
702 }
703
704 result_print ()
705 {
706     _passed="$1"
707     _out="$2"
708     _rc="$3"
709     _iteration="$4"
710
711     if [ "$EVENTSCRIPT_TESTS_VERBOSE" = "yes" ] || ! $_passed ; then
712         if [ -n "$_iteration" ] ; then
713             cat <<EOF
714
715 ==================================================
716 Iteration $_iteration
717 EOF
718         fi
719
720 cat <<EOF
721 --------------------------------------------------
722 Output (Exit status: ${_rc}):
723 --------------------------------------------------
724 EOF
725         echo "$_out" | cat $EVENTSCRIPT_TESTS_CAT_RESULTS_OPTS
726     fi
727
728     if ! $_passed ; then
729         cat <<EOF
730 --------------------------------------------------
731 Required output (Exit status: ${required_rc}):
732 --------------------------------------------------
733 EOF
734         echo "$required_output" | cat $EVENTSCRIPT_TESTS_CAT_RESULTS_OPTS
735
736         if $EVENTSCRIPT_TESTS_DIFF_RESULTS ; then
737             _outr=$(mktemp)
738             echo "$required_output" >"$_outr"
739
740             _outf=$(mktemp)
741             echo "$_out" >"$_outf"
742
743             cat <<EOF
744 --------------------------------------------------
745 Diff:
746 --------------------------------------------------
747 EOF
748             diff -u "$_outr" "$_outf" | cat -A
749             rm "$_outr" "$_outf"
750         fi
751     fi
752 }
753
754 result_footer ()
755 {
756     _passed="$1"
757
758     if [ "$TEST_VERBOSE" = "yes" ] || ! $_passed ; then
759
760         cat <<EOF
761 --------------------------------------------------
762 CTDB_BASE="$CTDB_BASE"
763 CTDB_ETCDIR="$CTDB_ETCDIR"
764 ctdb client is "$(which ctdb)"
765 --------------------------------------------------
766 EOF
767     fi
768
769     if $_passed ; then
770         echo "PASSED"
771         return 0
772     else
773         echo
774         echo "FAILED"
775         return 1
776     fi
777 }
778
779 result_check ()
780 {
781     _rc=$?
782
783     if [ -n "$OUT_FILTER" ] ; then
784         _fout=$(echo "$_out" | eval sed -r $OUT_FILTER)
785     else
786         _fout="$_out"
787     fi
788
789     if [ "$_fout" = "$required_output" -a $_rc = $required_rc ] ; then
790         _passed=true
791     else
792         _passed=false
793     fi
794
795     result_print "$_passed" "$_out" "$_rc"
796     result_footer "$_passed"
797 }
798
799 # Run an eventscript once.  The test passes if the return code and
800 # output match those required.
801
802 # Any args are passed to the eventscript.
803
804 # Eventscript tracing can be done by setting:
805 #   EVENTSCRIPTS_TESTS_TRACE="sh -x"
806
807 # or similar.  This will almost certainly make a test fail but is
808 # useful for debugging.
809 simple_test ()
810 {
811     [ -n "$event" ] || die 'simple_test: $event not set'
812
813     echo "Running eventscript \"$script $event${1:+ }$*\""
814     _out=$($EVENTSCRIPTS_TESTS_TRACE "${CTDB_BASE}/events.d/$script" "$event" "$@" 2>&1)
815
816     result_check
817 }
818
819 simple_test_event ()
820 {
821     # If something has previously failed then don't continue.
822     : ${_passed:=true}
823     $_passed || return 1
824
825     event="$1" ; shift
826     echo "##################################################"
827     simple_test "$@"
828 }
829
830 simple_test_command ()
831 {
832     # If something has previously failed then don't continue.
833     : ${_passed:=true}
834     $_passed || return 1
835
836     echo "##################################################"
837     echo "Running command \"$*\""
838     _out=$("$@" 2>&1)
839
840     result_check
841 }
842
843 # Run an eventscript iteratively.
844 # - 1st argument is the number of iterations.
845 # - 2nd argument is something to eval to do setup for every iteration.
846 #   The easiest thing to do here is to define a function and pass it
847 #   here.
848 # - Subsequent arguments come in pairs: an iteration number and
849 #   something to eval for that iteration.  Each time an iteration
850 #   number is matched the associated argument is given to eval after
851 #   the default setup is done.  The iteration numbers need to be given
852 #   in ascending order.
853 #
854 # Some optional args can be given *before* these, surrounded by extra
855 # "--" args.  These args are passed to the eventscript.  Quoting is
856 # lost.
857 #
858 # One use of the 2nd and further arguments is to call
859 # required_result() to change what is expected of a particular
860 # iteration.
861 iterate_test ()
862 {
863     [ -n "$event" ] || die 'simple_test: $event not set'
864
865     args=""
866     if [ "$1" = "--" ] ; then
867         shift
868         while [ "$1" != "--" ] ; do
869             args="${args}${args:+ }$1"
870             shift
871         done
872         shift
873     fi
874
875     _repeats="$1"
876     _setup_default="$2"
877     shift 2
878
879     echo "Running $_repeats iterations of \"$script $event\" $args"
880
881     _result=true
882
883     for iteration in $(seq 1 $_repeats) ; do
884         # This is inefficient because the iteration-specific setup
885         # might completely replace the default one.  However, running
886         # the default is good because it allows you to revert to a
887         # particular result without needing to specify it explicitly.
888         eval $_setup_default
889         if [ $iteration = "$1" ] ; then
890             eval $2
891             shift 2
892         fi
893
894         _out=$($EVENTSCRIPTS_TESTS_TRACE "${CTDB_BASE}/events.d/$script" "$event" $args 2>&1)
895         _rc=$?
896
897     if [ -n "$OUT_FILTER" ] ; then
898         _fout=$(echo "$_out" | eval sed -r $OUT_FILTER)
899     else
900         _fout="$_out"
901     fi
902
903         if [ "$_fout" = "$required_output" -a $_rc = $required_rc ] ; then
904             _passed=true
905         else
906             _passed=false
907             _result=false
908         fi
909
910         result_print "$_passed" "$_out" "$_rc" "$iteration"
911     done
912
913     result_footer "$_result"
914 }