ctdb-tests: Extend eventscript unit test infrastructure for other scripts
[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     case "$EVENTSCRIPTS_PATH" in
13         /*) : ;;
14         *) EVENTSCRIPTS_PATH="${PWD}/${EVENTSCRIPTS_PATH}" ;;
15     esac
16 fi
17
18 export EVENTSCRIPTS_PATH
19
20 PATH="${EVENTSCRIPTS_PATH}:${PATH}"
21
22 export EVENTSCRIPTS_TESTS_VAR_DIR="${TEST_VAR_DIR}/unit_eventscripts"
23 if [ -d "$EVENTSCRIPTS_TESTS_VAR_DIR" -a \
24     "$EVENTSCRIPTS_TESTS_VAR_DIR" != "/unit_eventscripts" ] ; then
25     rm -r "$EVENTSCRIPTS_TESTS_VAR_DIR"
26 fi
27 mkdir -p "$EVENTSCRIPTS_TESTS_VAR_DIR"
28 export CTDB_VARDIR="$EVENTSCRIPTS_TESTS_VAR_DIR/ctdb"
29
30 export CTDB_LOGGING="file:${EVENTSCRIPTS_TESTS_VAR_DIR}/log.ctdb"
31 touch "${CTDB_LOGGING#file:}" || \
32     die "Unable to setup logging for \"$CTDB_LOGGING\""
33
34 if [ -d "${TEST_SUBDIR}/etc" ] ; then    
35     cp -a "${TEST_SUBDIR}/etc" "$EVENTSCRIPTS_TESTS_VAR_DIR"
36     export CTDB_ETCDIR="${EVENTSCRIPTS_TESTS_VAR_DIR}/etc"
37 else
38     die "Unable to setup \$CTDB_ETCDIR"
39 fi
40
41 if [ -d "${TEST_SUBDIR}/etc-ctdb" ] ; then
42     cp -prL "${TEST_SUBDIR}/etc-ctdb" "$EVENTSCRIPTS_TESTS_VAR_DIR"
43     export CTDB_BASE="${EVENTSCRIPTS_TESTS_VAR_DIR}/etc-ctdb"
44 else
45     die "Unable to set \$CTDB_BASE"
46 fi
47 export CTDB_BASE
48
49 if [ ! -d "${CTDB_BASE}/events.d" ] ; then
50     cat <<EOF
51 ERROR: Directory ${CTDB_BASE}/events.d does not exist.
52
53 That means that no eventscripts can be tested.
54
55 One possible explanation:
56
57   You have CTDB installed via RPMs (or similar), so the regular
58   CTDB_BASE directory is in /etc/ctdb/
59
60   BUT
61
62   You have done a regular "configure" and "make install" so the tests
63   are installed under /usr/local/.
64
65 If so, one possible hack to fix this is to create a symlink:
66
67   ln -s /etc/ctdb /usr/local/etc/ctdb
68
69 This is nasty but it works...  :-)
70 EOF
71     exit 1
72 fi
73
74 ######################################################################
75
76 if "$TEST_VERBOSE" ; then
77     debug () { echo "$@" ; }
78 else
79     debug () { : ; }
80 fi
81
82 eventscripts_tests_cleanup_hooks=""
83
84 # This loses quoting!
85 eventscripts_test_add_cleanup ()
86 {
87     eventscripts_tests_cleanup_hooks="${eventscripts_tests_cleanup_hooks}${eventscripts_tests_cleanup_hooks:+ ; }$*"
88 }
89
90 trap 'eval $eventscripts_tests_cleanup_hooks' 0
91
92
93 ######################################################################
94
95 # General setup fakery
96
97 setup_generic ()
98 {
99     debug "Setting up shares (3 existing shares)"
100     # Create 3 fake shares/exports.
101     export FAKE_SHARES=""
102     for i in $(seq 1 3) ; do
103         _s="${EVENTSCRIPTS_TESTS_VAR_DIR}/shares/${i}_existing"
104         mkdir -p "$_s"
105         FAKE_SHARES="${FAKE_SHARES}${FAKE_SHARES:+ }${_s}"
106     done
107
108     export FAKE_PROC_NET_BONDING="$EVENTSCRIPTS_TESTS_VAR_DIR/proc-net-bonding"
109     mkdir -p "$FAKE_PROC_NET_BONDING"
110     rm -f "$FAKE_PROC_NET_BONDING"/*
111
112     export FAKE_ETHTOOL_LINK_DOWN="$EVENTSCRIPTS_TESTS_VAR_DIR/ethtool-link-down"
113     mkdir -p "$FAKE_ETHTOOL_LINK_DOWN"
114     rm -f "$FAKE_ETHTOOL_LINK_DOWN"/*
115
116     # This can only have 2 levels.  We don't want to resort to usings
117     # something dangerous like "rm -r" setup time.
118     export FAKE_IP_STATE="$EVENTSCRIPTS_TESTS_VAR_DIR/fake-ip-state"
119     mkdir -p "$FAKE_IP_STATE"
120     rm -f "$FAKE_IP_STATE"/*/*
121     rm -f "$FAKE_IP_STATE"/* 2>/dev/null || true
122     rmdir "$FAKE_IP_STATE"/* 2>/dev/null || true
123
124
125     export CTDB_DBDIR="${EVENTSCRIPTS_TESTS_VAR_DIR}/db"
126     mkdir -p "${CTDB_DBDIR}/persistent"
127
128     export FAKE_TDBTOOL_SUPPORTS_CHECK="yes"
129     export FAKE_TDB_IS_OK
130     export FAKE_DATE_OUTPUT
131
132     export FAKE_NETSTAT_TCP_ESTABLISHED FAKE_TCP_LISTEN FAKE_NETSTAT_UNIX_LISTEN
133     export FAKE_NETSTAT_TCP_ESTABLISHED_FILE=$(mktemp --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
134 }
135
136 tcp_port_down ()
137 {
138     for _i ; do
139         debug "Marking TCP port \"${_i}\" as not listening"
140         FAKE_TCP_LISTEN=$(echo "$FAKE_TCP_LISTEN" | sed -r -e "s@[[:space:]]*[\.0-9]+:${_i}@@g")
141     done
142 }
143
144 shares_missing ()
145 {
146     _fmt="$1" ; shift
147
148     # Replace some shares with non-existent ones.
149     _t=""
150     _n=1
151     _nl="
152 "
153     export MISSING_SHARES_TEXT=""
154     for _i in $FAKE_SHARES ; do
155         if [ $_n = "$1" ] ; then
156             shift
157             _i="${_i%_existing}_missing"
158             debug "Replacing share $_n with missing share \"$_i\""
159             rmdir "$_i" 2>/dev/null || true
160             MISSING_SHARES_TEXT="${MISSING_SHARES_TEXT}${MISSING_SHARES_TEXT:+${_nl}}"$(printf "$_fmt" "${_i}")
161         fi
162         _t="${_t}${_t:+ }${_i}"
163         _n=$(($_n + 1))
164     done
165     FAKE_SHARES="$_t"
166 }
167
168 # Setup some fake /proc/net/bonding files with just enough info for
169 # the eventscripts.
170
171 # arg1 is interface name, arg2 is currently active slave (use "None"
172 # if none), arg3 is MII status ("up" or "down").
173 setup_bond ()
174 {
175     _iface="$1"
176     _slave="${2:-${_iface}_sl_0}"
177     _mii_s="${3:-up}"
178     _mii_subs="${4:-${_mii_s:-up}}"
179     echo "Setting $_iface to be a bond with active slave $_slave and MII status $_mii_s"
180     cat >"${FAKE_PROC_NET_BONDING}/$_iface" <<EOF
181 Bonding Mode: IEEE 802.3ad Dynamic link aggregation
182 Currently Active Slave: $_slave
183 # Status of the bond
184 MII Status: $_mii_s
185 # Status of 1st pretend adapter
186 MII Status: $_mii_subs
187 # Status of 2nd pretend adapter
188 MII Status: $_mii_subs
189 EOF
190 }
191
192 ethtool_interfaces_down ()
193 {
194     for _i ; do
195         echo "Marking interface $_i DOWN for ethtool"
196         touch "${FAKE_ETHTOOL_LINK_DOWN}/${_i}"
197     done
198 }
199
200 ethtool_interfaces_up ()
201 {
202     for _i ; do
203         echo "Marking interface $_i UP for ethtool"
204         rm -f "${FAKE_ETHTOOL_LINK_DOWN}/${_i}"
205     done
206 }
207
208 dump_routes ()
209 {
210     echo "# ip rule show"
211     ip rule show
212
213     ip rule show |
214     while read _p _x _i _x _t ; do
215         # Remove trailing colon after priority/preference.
216         _p="${_p%:}"
217         # Only remove rules that match our priority/preference.
218         [ "$CTDB_PER_IP_ROUTING_RULE_PREF" = "$_p" ] || continue
219
220         echo "# ip route show table $_t"
221         ip route show table "$_t"
222     done
223 }
224
225 # Copied from 13.per_ip_routing for now... so this is lazy testing  :-(
226 ipv4_host_addr_to_net ()
227 {
228     _host="$1"
229     _maskbits="$2"
230
231     # Convert the host address to an unsigned long by splitting out
232     # the octets and doing the math.
233     _host_ul=0
234     for _o in $(export IFS="." ; echo $_host) ; do
235         _host_ul=$(( ($_host_ul << 8) + $_o)) # work around Emacs color bug
236     done
237
238     # Calculate the mask and apply it.
239     _mask_ul=$(( 0xffffffff << (32 - $_maskbits) ))
240     _net_ul=$(( $_host_ul & $_mask_ul ))
241
242     # Now convert to a network address one byte at a time.
243     _net=""
244     for _o in $(seq 1 4) ; do
245         _net="$(($_net_ul & 255))${_net:+.}${_net}"
246         _net_ul=$(($_net_ul >> 8))
247     done
248
249     echo "${_net}/${_maskbits}"
250 }
251
252 ######################################################################
253
254 # CTDB fakery
255
256 # Evaluate an expression that probably calls functions or uses
257 # variables from the CTDB functions file.  This is used for test
258 # initialisation.
259 eventscript_call ()
260 {
261     (
262         . "$CTDB_BASE/functions"
263         "$@"
264     )
265 }
266
267 # Set output for ctdb command.  Option 1st argument is return code.
268 ctdb_set_output ()
269 {
270     _out="$EVENTSCRIPTS_TESTS_VAR_DIR/ctdb.out"
271     cat >"$_out"
272
273     _rc="$EVENTSCRIPTS_TESTS_VAR_DIR/ctdb.rc"
274     echo "${1:-0}" >"$_rc"
275
276     eventscripts_test_add_cleanup "rm -f $_out $_rc"
277 }
278
279 setup_ctdb ()
280 {
281     setup_generic
282
283     export FAKE_CTDB_NUMNODES="${1:-3}"
284     echo "Setting up CTDB with ${FAKE_CTDB_NUMNODES} fake nodes"
285
286     export FAKE_CTDB_PNN="${2:-0}"
287     echo "Setting up CTDB with PNN ${FAKE_CTDB_PNN}"
288
289     export CTDB_PUBLIC_ADDRESSES="${CTDB_BASE}/public_addresses"
290     if [ -n "$3" ] ; then
291         echo "Setting up CTDB_PUBLIC_ADDRESSES: $3"
292         CTDB_PUBLIC_ADDRESSES=$(mktemp)
293         for _i in $3 ; do
294             _ip="${_i%@*}"
295             _ifaces="${_i#*@}"
296             echo "${_ip} ${_ifaces}" >>"$CTDB_PUBLIC_ADDRESSES"
297         done
298         eventscripts_test_add_cleanup "rm -f $CTDB_PUBLIC_ADDRESSES"
299     fi
300
301     export FAKE_CTDB_STATE="$EVENTSCRIPTS_TESTS_VAR_DIR/fake-ctdb"
302
303     export FAKE_CTDB_EXTRA_CONFIG="$EVENTSCRIPTS_TESTS_VAR_DIR/fake-config.sh"
304     rm -f "$FAKE_CTDB_EXTRA_CONFIG"
305
306     export FAKE_CTDB_IFACES_DOWN="$FAKE_CTDB_STATE/ifaces-down"
307     mkdir -p "$FAKE_CTDB_IFACES_DOWN"
308     rm -f "$FAKE_CTDB_IFACES_DOWN"/*
309
310     export FAKE_CTDB_SCRIPTSTATUS="$FAKE_CTDB_STATE/scriptstatus"
311     mkdir -p "$FAKE_CTDB_SCRIPTSTATUS"
312     rm -f "$FAKE_CTDB_SCRIPTSTATUS"/*
313
314     export CTDB_PARTIALLY_ONLINE_INTERFACES
315
316     export FAKE_CTDB_TUNABLES_OK="MonitorInterval TDBMutexEnabled DatabaseHashSize"
317     export FAKE_CTDB_TUNABLES_OBSOLETE="EventScriptUnhealthyOnTimeout"
318 }
319
320 setup_config ()
321 {
322     cat >"$FAKE_CTDB_EXTRA_CONFIG"
323 }
324
325 setup_memcheck ()
326 {
327     setup_ctdb
328
329     _swap_total="5857276"
330
331     if [ "$1" = "bad" ] ; then
332         _swap_free="   4352"
333         _mem_cached=" 112"
334         _mem_free=" 468"
335     else
336         _swap_free="$_swap_total"
337         _mem_cached="1112"
338         _mem_free="1468"
339     fi
340
341     export FAKE_PROC_MEMINFO="\
342 MemTotal:        3940712 kB
343 MemFree:          225268 kB
344 Buffers:          146120 kB
345 Cached:          1139348 kB
346 SwapCached:        56016 kB
347 Active:          2422104 kB
348 Inactive:        1019928 kB
349 Active(anon):    1917580 kB
350 Inactive(anon):   523080 kB
351 Active(file):     504524 kB
352 Inactive(file):   496848 kB
353 Unevictable:        4844 kB
354 Mlocked:            4844 kB
355 SwapTotal:       ${_swap_total} kB
356 SwapFree:        ${_swap_free} kB
357 ..."
358
359     export FAKE_FREE_M="\
360              total       used       free     shared    buffers     cached
361 Mem:          3848       3634        213          0        142       ${_mem_cached}
362 -/+ buffers/cache:       2379       ${_mem_free}
363 Swap:         5719        246       5473"
364
365     export CTDB_MONITOR_FREE_MEMORY
366     export CTDB_MONITOR_FREE_MEMORY_WARN
367     export CTDB_CHECK_SWAP_IS_NOT_USED
368 }
369
370 ctdb_get_interfaces ()
371 {
372     # The echo/subshell forces all the output onto 1 line.
373     echo $(ctdb ifaces -X | awk -F'|' 'FNR > 1 {print $2}')
374 }
375
376 ctdb_get_1_interface ()
377 {
378     _t=$(ctdb_get_interfaces)
379     echo ${_t%% *}
380 }
381
382 # Print all public addresses as: interface IP maskbits
383 # Each line is suitable for passing to takeip/releaseip
384 ctdb_get_all_public_addresses ()
385 {
386     _f="${CTDB_PUBLIC_ADDRESSES:-${CTDB_BASE}/public_addresses}"
387     while IFS="/$IFS" read _ip _maskbits _ifaces ; do
388         echo "$_ifaces $_ip $_maskbits"
389     done <"$_f"
390 }
391
392 # Print public addresses on this node as: interface IP maskbits
393 # Each line is suitable for passing to takeip/releaseip
394 ctdb_get_my_public_addresses ()
395 {
396     ctdb ip -v -X | {
397         read _x # skip header line
398
399         while IFS="|" read _x _ip _x _iface _x ; do
400             [ -n "$_iface" ] || continue
401             while IFS="/$IFS" read _i _maskbits _x ; do
402                 if [ "$_ip" = "$_i" ] ; then
403                     echo $_iface $_ip $_maskbits
404                     break
405                 fi
406             done <"${CTDB_PUBLIC_ADDRESSES:-${CTDB_BASE}/public_addresses}"
407         done
408     }
409 }
410
411 # Prints the 1st public address as: interface IP maskbits
412 # This is suitable for passing to takeip/releaseip
413 ctdb_get_1_public_address ()
414 {
415     ctdb_get_my_public_addresses | { head -n 1 ; cat >/dev/null ; }
416 }
417
418 ctdb_not_implemented ()
419 {
420     export CTDB_NOT_IMPLEMENTED="$1"
421     ctdb_not_implemented="\
422 DEBUG: ctdb: command \"$1\" not implemented in stub"
423 }
424
425 ctdb_fake_scriptstatus ()
426 {
427     _code="$1"
428     _status="$2"
429     _err_out="$3"
430
431     _d1=$(date '+%s.%N')
432     _d2=$(date '+%s.%N')
433
434     echo "$_code $_status $_err_out" >"$FAKE_CTDB_SCRIPTSTATUS/$script"
435 }
436
437 ######################################################################
438
439 setup_ctdb_policy_routing ()
440 {
441     service_name="per_ip_routing"
442
443     export CTDB_PER_IP_ROUTING_CONF="$CTDB_BASE/policy_routing"
444     export CTDB_PER_IP_ROUTING_RULE_PREF=100
445     export CTDB_PER_IP_ROUTING_TABLE_ID_LOW=1000
446     export CTDB_PER_IP_ROUTING_TABLE_ID_HIGH=2000
447
448     # Tests need to create and populate this file
449     rm -f "$CTDB_PER_IP_ROUTING_CONF"
450 }
451
452 # Create policy routing configuration in $CTDB_PER_IP_ROUTING_CONF.
453 # $1 is the number of assigned IPs to use (<num>, all), defaulting to
454 # 1.  If $2 is "default" then a default route is also added.
455 create_policy_routing_config ()
456 {
457     _num_ips="${1:-1}"
458     _should_add_default="$2"
459
460     ctdb_get_my_public_addresses |
461     if [ "$_num_ips" = "all" ] ; then
462         cat
463     else
464         { head -n "$_num_ips" ; cat >/dev/null ; }
465     fi |
466     while read _dev _ip _bits ; do
467         _net=$(ipv4_host_addr_to_net "$_ip" "$_bits")
468         _gw="${_net%.*}.1" # a dumb, calculated default
469
470         echo "$_ip $_net"
471
472         if [ "$_should_add_default" = "default" ] ; then
473             echo "$_ip 0.0.0.0/0 $_gw"
474         fi
475     done >"$CTDB_PER_IP_ROUTING_CONF"
476 }
477
478 # Check the routes against those that are expected.  $1 is the number
479 # of assigned IPs to use (<num>, all), defaulting to 1.  If $2 is
480 # "default" then expect default routes to have been added.
481 check_routes ()
482 {
483     _num_ips="${1:-1}"
484     _should_add_default="$2"
485
486     _policy_rules=""
487     _policy_routes=""
488
489     ctdb_get_my_public_addresses |
490     if [ "$_num_ips" = "all" ] ; then
491         cat
492     else
493         { head -n "$_num_ips" ; cat >/dev/null ; }
494     fi | {
495         while read _dev _ip _bits ; do
496             _net=$(ipv4_host_addr_to_net "$_ip" "$_bits")
497             _gw="${_net%.*}.1" # a dumb, calculated default
498
499             _policy_rules="${_policy_rules}
500 ${CTDB_PER_IP_ROUTING_RULE_PREF}:       from $_ip lookup ctdb.$_ip "
501             _policy_routes="${_policy_routes}
502 # ip route show table ctdb.$_ip
503 $_net dev $_dev  scope link "
504
505             if [ "$_should_add_default" = "default" ] ; then
506                 _policy_routes="${_policy_routes}
507 default via $_gw dev $_dev "
508             fi
509         done
510
511         ok <<EOF
512 # ip rule show
513 0:      from all lookup local ${_policy_rules}
514 32766:  from all lookup main 
515 32767:  from all lookup default ${_policy_routes}
516 EOF
517
518         simple_test_command dump_routes
519     }
520 }
521
522 ######################################################################
523
524 setup_ctdb_natgw ()
525 {
526     debug "Setting up NAT gateway"
527
528     natgw_config_dir="${TEST_VAR_DIR}/natgw_config"
529     mkdir -p "$natgw_config_dir"
530
531     # These will accumulate, 1 per test... but will be cleaned up at
532     # the end.
533     export CTDB_NATGW_NODES=$(mktemp --tmpdir="$natgw_config_dir")
534
535     # Read from stdin
536     while read _ip _master _dev ; do
537         echo "$_ip"
538         if [ "$_master" = "master" ] ; then
539             export FAKE_CTDB_NATGW_MASTER="$_ip"
540         fi
541     done >"$CTDB_NATGW_NODES"
542
543     # Assume all of the nodes are on a /24 network and have IPv4
544     # addresses:
545     read _ip <"$CTDB_NATGW_NODES"
546     export CTDB_NATGW_PRIVATE_NETWORK="${_ip%.*}.0/24"
547
548     # These are fixed.  Probably don't use the same network for the
549     # private node IPs.  To unset the default gateway just set it to
550     # "".  :-)
551     export CTDB_NATGW_PUBLIC_IP="10.1.1.121/24"
552     export CTDB_NATGW_PUBLIC_IFACE="eth1"
553     export CTDB_NATGW_DEFAULT_GATEWAY="10.1.1.254"
554     export CTDB_NATGW_SLAVE_ONLY=""
555 }
556
557 ok_natgw_master_ip_addr_show ()
558 {
559     _mac=$(echo "$CTDB_NATGW_PUBLIC_IFACE" | md5sum | sed -r -e 's@(..)(..)(..)(..)(..)(..).*@\1:\2:\3:\4:\5:\6@')
560
561     # This is based on CTDB_NATGW_PUBLIC_IP
562     _brd="10.1.1.255"
563
564 ok <<EOF
565 1: ${CTDB_NATGW_PUBLIC_IFACE}: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
566     link/ether ${_mac} brd ff:ff:ff:ff:ff:ff
567     inet ${CTDB_NATGW_PUBLIC_IP} brd ${_brd} scope global ${CTDB_NATGW_PUBLIC_IFACE}
568        valid_lft forever preferred_lft forever
569 EOF
570 }
571
572 ok_natgw_slave_ip_addr_show ()
573 {
574     _mac=$(echo "$CTDB_NATGW_PUBLIC_IFACE" | md5sum | sed -r -e 's@(..)(..)(..)(..)(..)(..).*@\1:\2:\3:\4:\5:\6@')
575 ok <<EOF
576 1: ${CTDB_NATGW_PUBLIC_IFACE}: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
577     link/ether ${_mac} brd ff:ff:ff:ff:ff:ff
578 EOF
579 }
580
581 ok_natgw_master_static_routes ()
582 {
583     _nl="
584 "
585     _t=""
586     for _i in $CTDB_NATGW_STATIC_ROUTES ; do
587         # This is intentionally different to the code in 11.natgw ;-)
588         case "$_i" in
589             *@*)
590                 _net=$(echo "$_i" | sed -e 's|@.*||')
591                 _gw=$(echo "$_i" | sed -e 's|.*@||')
592                 ;;
593             *)
594                 _net="$_i"
595                 _gw="$CTDB_NATGW_DEFAULT_GATEWAY"
596         esac
597
598         [ -n "$_gw" ] || continue
599         _t="${_t}${_t:+${_nl}}"
600         _t="${_t}${_net} via ${_gw} dev ethXXX  metric 10 "
601     done
602     ok "$_t"
603 }
604
605 ok_natgw_slave_static_routes ()
606 {
607     _nl="
608 "
609     _t=""
610     for _i in $CTDB_NATGW_STATIC_ROUTES ; do
611         # This is intentionally different to the code in 11.natgw ;-)
612         _net=$(echo "$_i" | sed -e 's|@.*||')
613
614         # The interface for the private network isn't specified as
615         # part of the NATGW configuration and isn't part of the
616         # command to add the route.  It is implicitly added by "ip
617         # route" but our stub doesn't do this and adds "ethXXX".
618         _t="${_t}${_t:+${_nl}}"
619         _t="${_t}${_net} via ${FAKE_CTDB_NATGW_MASTER} dev ethXXX  metric 10 "
620     done
621     ok "$_t"
622 }
623
624 ######################################################################
625
626 # Samba/winbind fakery
627
628 setup_samba ()
629 {
630     setup_ctdb
631
632     service_name="samba"
633
634     if [ "$1" != "down" ] ; then
635
636         debug "Marking Samba services as up, listening and managed by CTDB"
637         # Get into known state.
638         eventscript_call ctdb_service_managed
639
640         # All possible service names for all known distros.
641         for i in "smb" "nmb" "samba" ; do
642             service "$i" force-started
643         done
644
645         export CTDB_SAMBA_SKIP_SHARE_CHECK="no"
646         export CTDB_MANAGED_SERVICES="foo samba bar"
647
648         export FAKE_TCP_LISTEN="0.0.0.0:445 0.0.0.0:139"
649         export FAKE_WBINFO_FAIL="no"
650
651         # Some things in 50.samba are backgrounded and waited for.  If
652         # we don't sleep at all then timeouts can happen.  This avoids
653         # that...  :-)
654         export FAKE_SLEEP_FORCE=0.1
655     else
656         debug "Marking Samba services as down, not listening and not managed by CTDB"
657         # Get into known state.
658         eventscript_call ctdb_service_unmanaged
659
660         # All possible service names for all known distros.
661         for i in "smb" "nmb" "samba" ; do
662             service "$i" force-stopped
663         done
664
665         export CTDB_SAMBA_SKIP_SHARE_CHECK="no"
666         export CTDB_MANAGED_SERVICES="foo bar"
667         unset CTDB_MANAGES_SAMBA
668
669         export FAKE_TCP_LISTEN=""
670         export FAKE_WBINFO_FAIL="yes"
671     fi
672
673     # This is ugly but if this file isn't removed before each test
674     # then configuration changes between tests don't stick.
675     rm -f "$CTDB_VARDIR/state/samba/smb.conf.cache"
676 }
677
678 setup_winbind ()
679 {
680     setup_ctdb
681
682     service_name="winbind"
683
684     if [ "$1" != "down" ] ; then
685
686         debug "Marking Winbind service as up and managed by CTDB"
687         # Get into known state.
688         eventscript_call ctdb_service_managed
689
690         service "winbind" force-started
691
692         export CTDB_MANAGED_SERVICES="foo winbind bar"
693
694         export FAKE_WBINFO_FAIL="no"
695
696     else
697         debug "Marking Winbind service as down and not managed by CTDB"
698         # Get into known state.
699         eventscript_call ctdb_service_unmanaged
700
701         service "winbind" force-stopped
702
703         export CTDB_MANAGED_SERVICES="foo bar"
704         unset CTDB_MANAGES_WINBIND
705
706         export FAKE_WBINFO_FAIL="yes"
707     fi
708 }
709
710 wbinfo_down ()
711 {
712     debug "Making wbinfo commands fail"
713     FAKE_WBINFO_FAIL="yes"
714 }
715
716 ######################################################################
717
718 # NFS fakery
719
720 setup_nfs ()
721 {
722     setup_ctdb
723
724     service_name="nfs"
725
726     export FAKE_RPCINFO_SERVICES=""
727
728     export CTDB_NFS_SKIP_SHARE_CHECK="no"
729
730     export CTDB_MONITOR_NFS_THREAD_COUNT RPCNFSDCOUNT FAKE_NFSD_THREAD_PIDS
731     export CTDB_NFS_DUMP_STUCK_THREADS FAKE_RPC_THREAD_PIDS
732
733     # Reset the failcounts for nfs services.
734     eventscript_call eval rm -f '$ctdb_fail_dir/nfs_*'
735
736     if [ "$1" != "down" ] ; then
737         debug "Setting up NFS environment: all RPC services up, NFS managed by CTDB"
738
739         eventscript_call ctdb_service_managed
740         service "nfs" force-started  # might not be enough
741
742         export CTDB_MANAGED_SERVICES="foo nfs bar"
743
744         rpc_services_up "nfs" "mountd" "rquotad" "nlockmgr" "status"
745     else
746         debug "Setting up NFS environment: all RPC services down, NFS not managed by CTDB"
747
748         eventscript_call ctdb_service_unmanaged
749         service "nfs" force-stopped  # might not be enough
750         eventscript_call startstop_nfs stop
751
752         export CTDB_MANAGED_SERVICES="foo bar"
753         unset CTDB_MANAGES_NFS
754     fi
755 }
756
757 setup_nfs_ganesha ()
758 {
759     setup_nfs "$@"
760     export CTDB_NFS_SERVER_MODE="ganesha"
761     if [ "$1" != "down" ] ; then
762         export CTDB_MANAGES_NFS="yes"
763     fi
764
765     # We do not support testing the Ganesha-nfsd-specific part of the
766     # eventscript.
767     export CTDB_SKIP_GANESHA_NFSD_CHECK="yes"
768     export CTDB_NFS_SKIP_SHARE_CHECK="yes"
769 }
770
771 rpc_services_down ()
772 {
773     for _i ; do
774         debug "Marking RPC service \"${_i}\" as unavailable"
775         FAKE_RPCINFO_SERVICES=$(echo "$FAKE_RPCINFO_SERVICES" | sed -r -e "s@[[:space:]]*${_i}:[0-9]+:[0-9]+@@g")
776     done
777 }
778
779 rpc_services_up ()
780 {
781     for _i ; do
782         debug "Marking RPC service \"${_i}\" as available"
783         case "$_i" in
784             nfs)      _t="2:3" ;;
785             mountd)   _t="1:3" ;;
786             rquotad)  _t="1:2" ;;
787             nlockmgr) _t="3:4" ;;
788             status)   _t="1:1" ;;
789             *) die "Internal error - unsupported RPC service \"${_i}\"" ;;
790         esac
791
792         FAKE_RPCINFO_SERVICES="${FAKE_RPCINFO_SERVICES}${FAKE_RPCINFO_SERVICES:+ }${_i}:${_t}"
793     done
794 }
795
796 # Set the required result for a particular RPC program having failed
797 # for a certain number of iterations.  This is probably still a work
798 # in progress.  Note that we could hook aggressively
799 # nfs_check_rpc_service() to try to implement this but we're better
800 # off testing nfs_check_rpc_service() using independent code...  even
801 # if it is incomplete and hacky.  So, if the 60.nfs eventscript
802 # changes and the tests start to fail then it may be due to this
803 # function being incomplete.
804 rpc_set_service_failure_response ()
805 {
806     _progname="$1"
807     # The number of failures defaults to the iteration number.  This
808     # will be true when we fail from the 1st iteration... but we need
809     # the flexibility to set the number of failures.
810     _numfails="${2:-${iteration}}"
811
812     _etc="$CTDB_ETCDIR" # shortcut for readability
813     for _c in "$_etc/sysconfig/nfs" "$_etc/default/nfs" "$_etc/ctdb/sysconfig/nfs" ; do
814         if [ -r "$_c" ] ; then
815             . "$_c"
816             break
817         fi
818     done
819
820     # A handy newline.  :-)
821     _nl="
822 "
823
824     # Default
825     ok_null
826
827     _file=$(ls "${CTDB_BASE}/nfs-rpc-checks.d/"[0-9][0-9]."${_progname}.check")
828     [ -r "$_file" ] || die "RPC check file \"$_file\" does not exist or is not unique"
829
830     while read _op _li _actions ; do
831         # Skip comments
832         case "$_op" in
833             \#*) continue ;;
834         esac
835
836         _hit=false
837         if [ "$_op" != "%" ] ; then
838             if [ $_numfails $_op $_li ] ; then
839                 _hit=true
840             fi
841         else
842             if [ $(($_numfails $_op $_li)) -eq 0 ] ; then
843                 _hit=true
844             fi
845         fi
846         if $_hit ; then
847             _out=""
848             _rc=0
849             for _action in $_actions ; do
850                 case "$_action" in
851                     verbose)
852                         _ver=1
853                         _pn="$_progname"
854                         case "$_progname" in
855                             nfsd) _ver=3 ; _pn="nfs" ;;
856                             lockd) _ver=4 ; _pn="nlockmgr" ;;
857                             statd) _pn="status" ;;
858                         esac
859                         _out="\
860 ERROR: $_pn failed RPC check:
861 rpcinfo: RPC: Program not registered
862 program $_pn version $_ver is not available"
863                         ;;
864                     restart*)
865                         _p="rpc.${_progname}"
866                         case "$_action" in
867                             *:b) _bg="&" ;;
868                             *)   _bg=""  ;;
869                         esac
870                         case "$_progname" in
871                             nfsd)
872                                 _t="\
873 Trying to restart NFS service"
874
875                                 if [ -n "$CTDB_NFS_DUMP_STUCK_THREADS" ] ; then
876                                     for _pid in $FAKE_NFSD_THREAD_PIDS ; do
877                                         _t="\
878 $_t
879 ${_bg}Stack trace for nfsd[${_pid}]:
880 ${_bg}[<ffffffff87654321>] fake_stack_trace_for_pid_${_pid}/stack+0x0/0xff"
881                                     done
882                                 fi
883
884                                 _t="\
885 ${_t}
886 ${_bg}Starting nfslock: OK
887 ${_bg}Starting nfs: OK"
888                                 ;;
889                             lockd)
890                                 _t="\
891 Trying to restart lock manager service
892 ${_bg}Starting nfslock: OK"
893                                 ;;
894                             *)
895                                 _t="Trying to restart $_progname [${_p}]"
896                                 if [ -n "$CTDB_NFS_DUMP_STUCK_THREADS" ] ; then
897                                     for _pid in $FAKE_RPC_THREAD_PIDS ; do
898                                         _t="\
899 $_t
900 Stack trace for ${_p}[${_pid}]:
901 [<ffffffff87654321>] fake_stack_trace_for_pid_${_pid}/stack+0x0/0xff"
902                                     done
903                                 fi
904                         esac
905                         _out="${_out}${_out:+${_nl}}${_t}"
906                         ;;
907                     unhealthy)
908                         _rc=1
909                 esac
910             done
911             required_result $_rc "$_out"
912             return
913         fi
914     done <"$_file"
915 }
916
917 ######################################################################
918
919 # VSFTPD fakery
920
921 setup_vsftpd ()
922 {
923     service_name="vsftpd"
924
925     if [ "$1" != "down" ] ; then
926         die "setup_vsftpd up not implemented!!!"
927     else
928         debug "Setting up VSFTPD environment: service down, not managed by CTDB"
929
930         eventscript_call ctdb_service_unmanaged
931         service vsftpd force-stopped
932
933         export CTDB_MANAGED_SERVICES="foo"
934         unset CTDB_MANAGES_VSFTPD
935     fi
936 }
937
938 ######################################################################
939
940 # HTTPD fakery
941
942 setup_httpd ()
943 {
944     if [ "$1" != "down" ] ; then
945         die "setup_httpd up not implemented!!!"
946     else
947         debug "Setting up HTTPD environment: service down, not managed by CTDB"
948
949         for service_name in "apache2" "httpd" ; do
950             eventscript_call ctdb_service_unmanaged
951             service "$service_name" force-stopped
952         done
953
954         export CTDB_MANAGED_SERVICES="foo"
955         unset CTDB_MANAGES_HTTPD
956     fi
957 }
958
959 ######################################################################
960
961 # multipathd fakery
962
963 setup_multipathd ()
964 {
965     for i ; do
966         case "$i" in
967             \!*)
968                 _t="${i#!}"
969                 echo "Marking ${_t} as having no active paths"
970                 FAKE_MULTIPATH_FAILURES="${FAKE_MULTIPATH_FAILURES}${FAKE_MULTIPATH+FAILURES:+ }${_t}"
971                 ;;
972             *)
973                 _t="$i"         
974         esac
975         CTDB_MONITOR_MPDEVICES="${CTDB_MONITOR_MPDEVICES}${CTDB_MONITOR_MPDEVICES:+ }${_t}"
976     done
977
978     export CTDB_MONITOR_MPDEVICES FAKE_MULTIPATH_FAILURES
979     export FAKE_SLEEP_FORCE=0.1
980 }
981
982 ######################################################################
983
984 # Result and test functions
985
986 # Set some globals and print the summary.
987 define_test ()
988 {
989     desc="$1"
990
991     _f=$(basename "$0" ".sh")
992
993     # Remaining format should be NN.service.event.NNN or NN.service.NNN:
994     _num="${_f##*.}"
995     _f="${_f%.*}"
996
997     case "$_f" in
998         [0-9][0-9].*.*)
999             script="${_f%.*}"
1000             event="${_f##*.}"
1001             script_dir="${CTDB_BASE}/events.d"
1002             ;;
1003         [0-9][0-9].*)
1004             script="$_f"
1005             unset event
1006             script_dir="${CTDB_BASE}/events.d"
1007             ;;
1008         *.*)
1009             script="${_f%.*}"
1010             event="${_f##*.}"
1011             script_dir="${CTDB_BASE}"
1012             ;;
1013         *)
1014             script="${_f%.*}"
1015             unset event
1016             script_dir="${CTDB_BASE}"
1017     esac
1018
1019     [ -x "${script_dir}/${script}" ] || \
1020         die "Internal error - unable to find script \"${script_dir}/${script}\""
1021
1022     printf "%-17s %-10s %-4s - %s\n\n" "$script" "$event" "$_num" "$desc"
1023 }
1024
1025 _extra_header ()
1026 {
1027     cat <<EOF
1028 CTDB_BASE="$CTDB_BASE"
1029 CTDB_ETCDIR="$CTDB_ETCDIR"
1030 ctdb client is "$(which ctdb)"
1031 ip command is "$(which ip)"
1032 EOF
1033 }
1034
1035 # Run an eventscript once.  The test passes if the return code and
1036 # output match those required.
1037
1038 # Any args are passed to the eventscript.
1039
1040 simple_test ()
1041 {
1042     [ -n "$event" ] || die 'simple_test: $event not set'
1043
1044     _extra_header=$(_extra_header)
1045
1046     echo "Running script \"$script $event${1:+ }$*\""
1047     _shell=""
1048     if $TEST_COMMAND_TRACE ; then
1049         _shell="sh -x"
1050     else
1051         _shell="sh"
1052     fi
1053     _out=$($_shell "${script_dir}/${script}" "$event" "$@" 2>&1)
1054
1055     result_check "$_extra_header"
1056 }
1057
1058 simple_test_event ()
1059 {
1060     # If something has previously failed then don't continue.
1061     : ${_passed:=true}
1062     $_passed || return 1
1063
1064     event="$1" ; shift
1065     echo "=================================================="
1066     simple_test "$@"
1067 }
1068
1069 simple_test_command ()
1070 {
1071     # If something has previously failed then don't continue.
1072     : ${_passed:=true}
1073     $_passed || return 1
1074
1075     echo "=================================================="
1076     echo "Running command \"$*\""
1077     _out=$("$@" 2>&1)
1078
1079     result_check
1080 }
1081
1082 # Run an eventscript iteratively.
1083 # - 1st argument is the number of iterations.
1084 # - 2nd argument is something to eval to do setup for every iteration.
1085 #   The easiest thing to do here is to define a function and pass it
1086 #   here.
1087 # - Subsequent arguments come in pairs: an iteration number and
1088 #   something to eval for that iteration.  Each time an iteration
1089 #   number is matched the associated argument is given to eval after
1090 #   the default setup is done.  The iteration numbers need to be given
1091 #   in ascending order.
1092 #
1093 # Some optional args can be given *before* these, surrounded by extra
1094 # "--" args.  These args are passed to the eventscript.  Quoting is
1095 # lost.
1096 #
1097 # One use of the 2nd and further arguments is to call
1098 # required_result() to change what is expected of a particular
1099 # iteration.
1100 iterate_test ()
1101 {
1102     [ -n "$event" ] || die 'simple_test: $event not set'
1103
1104     args=""
1105     if [ "$1" = "--" ] ; then
1106         shift
1107         while [ "$1" != "--" ] ; do
1108             args="${args}${args:+ }$1"
1109             shift
1110         done
1111         shift
1112     fi
1113
1114     _repeats="$1"
1115     _setup_default="$2"
1116     shift 2
1117
1118     echo "Running $_repeats iterations of \"$script $event\" $args"
1119
1120     _result=true
1121
1122     for iteration in $(seq 1 $_repeats) ; do
1123         # This is inefficient because the iteration-specific setup
1124         # might completely replace the default one.  However, running
1125         # the default is good because it allows you to revert to a
1126         # particular result without needing to specify it explicitly.
1127         eval $_setup_default
1128         if [ $iteration = "$1" ] ; then
1129             eval $2
1130             shift 2
1131         fi
1132
1133         _shell=""
1134         if $TEST_COMMAND_TRACE ; then
1135             _shell="sh -x"
1136         else
1137             _shell="sh"
1138         fi
1139         _out=$($_shell "${script_dir}/${script}" "$event" $args 2>&1)
1140         _rc=$?
1141
1142         _fout=$(echo "$_out" | result_filter)
1143
1144         if [ "$_fout" = "$required_output" -a $_rc = $required_rc ] ; then
1145             _passed=true
1146         else
1147             _passed=false
1148             _result=false
1149         fi
1150
1151         result_print "$_passed" "$_out" "$_rc" "Iteration $iteration"
1152     done
1153
1154     result_footer "$_result" "$(_extra_header)"
1155 }