ctdb-tests: NAT gateway slave-only changes
[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_SCRIPT_VARDIR="$EVENTSCRIPTS_TESTS_VAR_DIR/script-state"
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_SYS_ETCDIR="${EVENTSCRIPTS_TESTS_VAR_DIR}/etc"
37 else
38     die "Unable to setup \$CTDB_SYS_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 ######################################################################
83
84 # General setup fakery
85
86 setup_generic ()
87 {
88     debug "Setting up shares (3 existing shares)"
89     # Create 3 fake shares/exports.
90     export FAKE_SHARES=""
91     for i in $(seq 1 3) ; do
92         _s="${EVENTSCRIPTS_TESTS_VAR_DIR}/shares/${i}_existing"
93         mkdir -p "$_s"
94         FAKE_SHARES="${FAKE_SHARES}${FAKE_SHARES:+ }${_s}"
95     done
96
97     export FAKE_PROC_NET_BONDING="$EVENTSCRIPTS_TESTS_VAR_DIR/proc-net-bonding"
98     mkdir -p "$FAKE_PROC_NET_BONDING"
99     rm -f "$FAKE_PROC_NET_BONDING"/*
100
101     export FAKE_ETHTOOL_LINK_DOWN="$EVENTSCRIPTS_TESTS_VAR_DIR/ethtool-link-down"
102     mkdir -p "$FAKE_ETHTOOL_LINK_DOWN"
103     rm -f "$FAKE_ETHTOOL_LINK_DOWN"/*
104
105     # This can only have 2 levels.  We don't want to resort to usings
106     # something dangerous like "rm -r" setup time.
107     export FAKE_IP_STATE="$EVENTSCRIPTS_TESTS_VAR_DIR/fake-ip-state"
108     mkdir -p "$FAKE_IP_STATE"
109     rm -f "$FAKE_IP_STATE"/*/*
110     rm -f "$FAKE_IP_STATE"/* 2>/dev/null || true
111     rmdir "$FAKE_IP_STATE"/* 2>/dev/null || true
112
113
114     export CTDB_DBDIR="${EVENTSCRIPTS_TESTS_VAR_DIR}/db"
115     export CTDB_DBDIR_PERSISTENT="${CTDB_DBDIR}/persistent"
116     export CTDB_DBDIR_STATE="${CTDB_DBDIR}/state"
117     mkdir -p "$CTDB_DBDIR_PERSISTENT"
118     mkdir -p "$CTDB_DBDIR_STATE"
119
120     export FAKE_TDBTOOL_SUPPORTS_CHECK="yes"
121     export FAKE_TDB_IS_OK
122     export FAKE_DATE_OUTPUT
123
124     export FAKE_NETSTAT_TCP_ESTABLISHED FAKE_TCP_LISTEN FAKE_NETSTAT_UNIX_LISTEN
125     export FAKE_NETSTAT_TCP_ESTABLISHED_FILE=$(mktemp --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
126 }
127
128 tcp_port_down ()
129 {
130     for _i ; do
131         debug "Marking TCP port \"${_i}\" as not listening"
132         FAKE_TCP_LISTEN=$(echo "$FAKE_TCP_LISTEN" | sed -r -e "s@[[:space:]]*[\.0-9]+:${_i}@@g")
133     done
134 }
135
136 shares_missing ()
137 {
138     _fmt="$1" ; shift
139
140     # Replace some shares with non-existent ones.
141     _t=""
142     _n=1
143     _nl="
144 "
145     export MISSING_SHARES_TEXT=""
146     for _i in $FAKE_SHARES ; do
147         if [ $_n = "$1" ] ; then
148             shift
149             _i="${_i%_existing}_missing"
150             debug "Replacing share $_n with missing share \"$_i\""
151             rmdir "$_i" 2>/dev/null || true
152             MISSING_SHARES_TEXT="${MISSING_SHARES_TEXT}${MISSING_SHARES_TEXT:+${_nl}}"$(printf "$_fmt" "${_i}")
153         fi
154         _t="${_t}${_t:+ }${_i}"
155         _n=$(($_n + 1))
156     done
157     FAKE_SHARES="$_t"
158 }
159
160 # Setup some fake /proc/net/bonding files with just enough info for
161 # the eventscripts.
162
163 # arg1 is interface name, arg2 is currently active slave (use "None"
164 # if none), arg3 is MII status ("up" or "down").
165 setup_bond ()
166 {
167     _iface="$1"
168     _slave="${2:-${_iface}_sl_0}"
169     _mii_s="${3:-up}"
170     _mii_subs="${4:-${_mii_s:-up}}"
171     echo "Setting $_iface to be a bond with active slave $_slave and MII status $_mii_s"
172     cat >"${FAKE_PROC_NET_BONDING}/$_iface" <<EOF
173 Bonding Mode: IEEE 802.3ad Dynamic link aggregation
174 Currently Active Slave: $_slave
175 # Status of the bond
176 MII Status: $_mii_s
177 # Status of 1st pretend adapter
178 MII Status: $_mii_subs
179 # Status of 2nd pretend adapter
180 MII Status: $_mii_subs
181 EOF
182 }
183
184 ethtool_interfaces_down ()
185 {
186     for _i ; do
187         echo "Marking interface $_i DOWN for ethtool"
188         touch "${FAKE_ETHTOOL_LINK_DOWN}/${_i}"
189     done
190 }
191
192 ethtool_interfaces_up ()
193 {
194     for _i ; do
195         echo "Marking interface $_i UP for ethtool"
196         rm -f "${FAKE_ETHTOOL_LINK_DOWN}/${_i}"
197     done
198 }
199
200 dump_routes ()
201 {
202     echo "# ip rule show"
203     ip rule show
204
205     ip rule show |
206     while read _p _x _i _x _t ; do
207         # Remove trailing colon after priority/preference.
208         _p="${_p%:}"
209         # Only remove rules that match our priority/preference.
210         [ "$CTDB_PER_IP_ROUTING_RULE_PREF" = "$_p" ] || continue
211
212         echo "# ip route show table $_t"
213         ip route show table "$_t"
214     done
215 }
216
217 # Copied from 13.per_ip_routing for now... so this is lazy testing  :-(
218 ipv4_host_addr_to_net ()
219 {
220     _host="$1"
221     _maskbits="$2"
222
223     # Convert the host address to an unsigned long by splitting out
224     # the octets and doing the math.
225     _host_ul=0
226     for _o in $(export IFS="." ; echo $_host) ; do
227         _host_ul=$(( ($_host_ul << 8) + $_o)) # work around Emacs color bug
228     done
229
230     # Calculate the mask and apply it.
231     _mask_ul=$(( 0xffffffff << (32 - $_maskbits) ))
232     _net_ul=$(( $_host_ul & $_mask_ul ))
233
234     # Now convert to a network address one byte at a time.
235     _net=""
236     for _o in $(seq 1 4) ; do
237         _net="$(($_net_ul & 255))${_net:+.}${_net}"
238         _net_ul=$(($_net_ul >> 8))
239     done
240
241     echo "${_net}/${_maskbits}"
242 }
243
244 ######################################################################
245
246 # CTDB fakery
247
248 # Evaluate an expression that probably calls functions or uses
249 # variables from the CTDB functions file.  This is used for test
250 # initialisation.
251 eventscript_call ()
252 {
253     (
254         . "$CTDB_BASE/functions"
255         "$@"
256     )
257 }
258
259 # For now this creates the same public addresses each time.  However,
260 # it could be made more flexible.
261 setup_public_addresses ()
262 {
263     if [ -f "$CTDB_PUBLIC_ADDRESSES" -a \
264             "${CTDB_PUBLIC_ADDRESSES%/*}" = "$EVENTSCRIPTS_TESTS_VAR_DIR" ] ; then
265         rm "$CTDB_PUBLIC_ADDRESSES"
266     fi
267
268     export CTDB_PUBLIC_ADDRESSES=$(mktemp \
269                                        --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR" \
270                                        "public-addresses-XXXXXXXX")
271
272     echo "Setting up CTDB_PUBLIC_ADDRESSES=${CTDB_PUBLIC_ADDRESSES}"
273     cat >"$CTDB_PUBLIC_ADDRESSES" <<EOF
274 10.0.0.1/24 dev123
275 10.0.0.2/24 dev123
276 10.0.0.3/24 dev123
277 10.0.0.4/24 dev123
278 10.0.0.5/24 dev123
279 10.0.0.6/24 dev123
280 10.0.1.1/24 dev456
281 10.0.1.2/24 dev456
282 10.0.1.3/24 dev456
283 EOF
284 }
285
286 # Need to cope with ctdb_get_pnn().  If a test changes PNN then it
287 # needs to be using a different state directory, otherwise the wrong
288 # PNN can already be cached in the state directory.
289 ctdb_set_pnn ()
290 {
291     export FAKE_CTDB_PNN="$1"
292     echo "Setting up PNN ${FAKE_CTDB_PNN}"
293
294     export CTDB_SCRIPT_VARDIR="$EVENTSCRIPTS_TESTS_VAR_DIR/script-state/${FAKE_CTDB_PNN}"
295     mkdir -p "$CTDB_SCRIPT_VARDIR"
296 }
297
298 setup_ctdb ()
299 {
300     setup_generic
301
302     export FAKE_CTDB_NUMNODES="${1:-3}"
303     echo "Setting up CTDB with ${FAKE_CTDB_NUMNODES} fake nodes"
304
305     ctdb_set_pnn "${2:-0}"
306
307     setup_public_addresses
308
309     export FAKE_CTDB_STATE="$EVENTSCRIPTS_TESTS_VAR_DIR/fake-ctdb"
310
311     export FAKE_CTDB_EXTRA_CONFIG="$EVENTSCRIPTS_TESTS_VAR_DIR/fake-config.sh"
312     rm -f "$FAKE_CTDB_EXTRA_CONFIG"
313
314     export FAKE_CTDB_IFACES_DOWN="$FAKE_CTDB_STATE/ifaces-down"
315     mkdir -p "$FAKE_CTDB_IFACES_DOWN"
316     rm -f "$FAKE_CTDB_IFACES_DOWN"/*
317
318     export FAKE_CTDB_SCRIPTSTATUS="$FAKE_CTDB_STATE/scriptstatus"
319     mkdir -p "$FAKE_CTDB_SCRIPTSTATUS"
320     rm -f "$FAKE_CTDB_SCRIPTSTATUS"/*
321
322     export CTDB_PARTIALLY_ONLINE_INTERFACES
323
324     export FAKE_CTDB_TUNABLES_OK="MonitorInterval TDBMutexEnabled DatabaseHashSize"
325     export FAKE_CTDB_TUNABLES_OBSOLETE="EventScriptUnhealthyOnTimeout"
326 }
327
328 setup_config ()
329 {
330     cat >"$FAKE_CTDB_EXTRA_CONFIG"
331 }
332
333 validate_percentage ()
334 {
335     case "$1" in
336         [0-9]|[0-9][0-9]|100) return 0 ;;
337         *) echo "WARNING: ${1} is an invalid percentage${2:+\" in }${2}${2:+\"}"
338            return 1
339     esac
340 }
341
342 setup_memcheck ()
343 {
344     _mem_usage="${1:-10}" # Default is 10%
345     _swap_usage="${2:-0}" # Default is  0%
346
347     setup_ctdb
348
349     _swap_total=5857276
350     _swap_free=$(( (100 - $_swap_usage) * $_swap_total / 100 ))
351
352     _mem_total=3940712
353     _mem_free=225268
354     _mem_buffers=146120
355     _mem_cached=$(( $_mem_total * (100 - $_mem_usage) / 100 - $_mem_free - $_mem_buffers ))
356
357     export FAKE_PROC_MEMINFO="\
358 MemTotal:        ${_mem_total} kB
359 MemFree:          ${_mem_free} kB
360 Buffers:          ${_mem_buffers} kB
361 Cached:          ${_mem_cached} kB
362 SwapCached:        56016 kB
363 Active:          2422104 kB
364 Inactive:        1019928 kB
365 Active(anon):    1917580 kB
366 Inactive(anon):   523080 kB
367 Active(file):     504524 kB
368 Inactive(file):   496848 kB
369 Unevictable:        4844 kB
370 Mlocked:            4844 kB
371 SwapTotal:       ${_swap_total} kB
372 SwapFree:        ${_swap_free} kB
373 ..."
374
375     export CTDB_MONITOR_MEMORY_USAGE
376     export CTDB_MONITOR_SWAP_USAGE
377 }
378
379 setup_fscheck ()
380 {
381     export FAKE_FS_USE="${1:-10}"  # Default is 10% usage
382
383     # Causes some variables to be exported
384     setup_ctdb
385
386     export CTDB_MONITOR_FILESYSTEM_USAGE
387 }
388
389 ctdb_get_interfaces ()
390 {
391     # The echo/subshell forces all the output onto 1 line.
392     echo $(ctdb ifaces -X | awk -F'|' 'FNR > 1 {print $2}')
393 }
394
395 ctdb_get_1_interface ()
396 {
397     _t=$(ctdb_get_interfaces)
398     echo ${_t%% *}
399 }
400
401 # Print all public addresses as: interface IP maskbits
402 # Each line is suitable for passing to takeip/releaseip
403 ctdb_get_all_public_addresses ()
404 {
405     _f="${CTDB_PUBLIC_ADDRESSES:-${CTDB_BASE}/public_addresses}"
406     while IFS="/$IFS" read _ip _maskbits _ifaces ; do
407         echo "$_ifaces $_ip $_maskbits"
408     done <"$_f"
409 }
410
411 # Print public addresses on this node as: interface IP maskbits
412 # Each line is suitable for passing to takeip/releaseip
413 ctdb_get_my_public_addresses ()
414 {
415     ctdb ip -v -X | {
416         read _x # skip header line
417
418         while IFS="|" read _x _ip _x _iface _x ; do
419             [ -n "$_iface" ] || continue
420             while IFS="/$IFS" read _i _maskbits _x ; do
421                 if [ "$_ip" = "$_i" ] ; then
422                     echo $_iface $_ip $_maskbits
423                     break
424                 fi
425             done <"${CTDB_PUBLIC_ADDRESSES:-${CTDB_BASE}/public_addresses}"
426         done
427     }
428 }
429
430 # Prints the 1st public address as: interface IP maskbits
431 # This is suitable for passing to takeip/releaseip
432 ctdb_get_1_public_address ()
433 {
434     ctdb_get_my_public_addresses | { head -n 1 ; cat >/dev/null ; }
435 }
436
437 ctdb_not_implemented ()
438 {
439     export CTDB_NOT_IMPLEMENTED="$1"
440     ctdb_not_implemented="\
441 DEBUG: ctdb: command \"$1\" not implemented in stub"
442 }
443
444 ctdb_fake_scriptstatus ()
445 {
446     _code="$1"
447     _status="$2"
448     _err_out="$3"
449
450     _d1=$(date '+%s.%N')
451     _d2=$(date '+%s.%N')
452
453     echo "$_code $_status $_err_out" >"$FAKE_CTDB_SCRIPTSTATUS/$script"
454 }
455
456 ######################################################################
457
458 setup_ctdb_policy_routing ()
459 {
460     service_name="per_ip_routing"
461
462     export CTDB_PER_IP_ROUTING_CONF="$CTDB_BASE/policy_routing"
463     export CTDB_PER_IP_ROUTING_RULE_PREF=100
464     export CTDB_PER_IP_ROUTING_TABLE_ID_LOW=1000
465     export CTDB_PER_IP_ROUTING_TABLE_ID_HIGH=2000
466
467     # Tests need to create and populate this file
468     rm -f "$CTDB_PER_IP_ROUTING_CONF"
469 }
470
471 # Create policy routing configuration in $CTDB_PER_IP_ROUTING_CONF.
472 # $1 is the number of assigned IPs to use (<num>, all), defaulting to
473 # 1.  If $2 is "default" then a default route is also added.
474 create_policy_routing_config ()
475 {
476     _num_ips="${1:-1}"
477     _should_add_default="$2"
478
479     ctdb_get_my_public_addresses |
480     if [ "$_num_ips" = "all" ] ; then
481         cat
482     else
483         { head -n "$_num_ips" ; cat >/dev/null ; }
484     fi |
485     while read _dev _ip _bits ; do
486         _net=$(ipv4_host_addr_to_net "$_ip" "$_bits")
487         _gw="${_net%.*}.254" # a dumb, calculated default
488
489         echo "$_ip $_net"
490
491         if [ "$_should_add_default" = "default" ] ; then
492             echo "$_ip 0.0.0.0/0 $_gw"
493         fi
494     done >"$CTDB_PER_IP_ROUTING_CONF"
495 }
496
497 # Check the routes against those that are expected.  $1 is the number
498 # of assigned IPs to use (<num>, all), defaulting to 1.  If $2 is
499 # "default" then expect default routes to have been added.
500 check_routes ()
501 {
502     _num_ips="${1:-1}"
503     _should_add_default="$2"
504
505     _policy_rules=""
506     _policy_routes=""
507
508     ctdb_get_my_public_addresses |
509     if [ "$_num_ips" = "all" ] ; then
510         cat
511     else
512         { head -n "$_num_ips" ; cat >/dev/null ; }
513     fi | {
514         while read _dev _ip _bits ; do
515             _net=$(ipv4_host_addr_to_net "$_ip" "$_bits")
516             _gw="${_net%.*}.254" # a dumb, calculated default
517
518             _policy_rules="${_policy_rules}
519 ${CTDB_PER_IP_ROUTING_RULE_PREF}:       from $_ip lookup ctdb.$_ip "
520             _policy_routes="${_policy_routes}
521 # ip route show table ctdb.$_ip
522 $_net dev $_dev  scope link "
523
524             if [ "$_should_add_default" = "default" ] ; then
525                 _policy_routes="${_policy_routes}
526 default via $_gw dev $_dev "
527             fi
528         done
529
530         ok <<EOF
531 # ip rule show
532 0:      from all lookup local ${_policy_rules}
533 32766:  from all lookup main 
534 32767:  from all lookup default ${_policy_routes}
535 EOF
536
537         simple_test_command dump_routes
538     } || test_fail
539 }
540
541 ######################################################################
542
543 ctdb_catdb_format_pairs ()
544 {
545     _count=0
546
547     while read _k _v ; do
548         _kn=$(echo -n "$_k" | wc -c)
549         _vn=$(echo -n "$_v" | wc -c)
550         cat <<EOF
551 key(${_kn}) = "${_k}"
552 dmaster: 0
553 rsn: 1
554 data(${_vn}) = "${_v}"
555
556 EOF
557         _count=$(($_count + 1))
558     done
559
560     echo "Dumped ${_count} records"
561 }
562
563 check_ctdb_tdb_statd_state ()
564 {
565     ctdb_get_my_public_addresses |
566     while read _x _sip _x ; do
567         for _cip ; do
568             echo "statd-state@${_sip}@${_cip}" "$FAKE_DATE_OUTPUT"
569         done
570     done |
571     ctdb_catdb_format_pairs | {
572         ok
573         simple_test_command ctdb catdb ctdb.tdb
574     } || test_fail
575 }
576
577 check_statd_callout_smnotify ()
578 {
579     _state_even=$(( $(date '+%s') / 2 * 2))
580     _state_odd=$(($_state_even + 1))
581
582     nfs_load_config
583
584     ctdb_get_my_public_addresses |
585     while read _x _sip _x ; do
586         for _cip ; do
587             cat <<EOF
588 --client=${_cip} --ip=${_sip} --server=${_sip} --stateval=${_state_even}
589 --client=${_cip} --ip=${_sip} --server=${NFS_HOSTNAME} --stateval=${_state_even}
590 --client=${_cip} --ip=${_sip} --server=${_sip} --stateval=${_state_odd}
591 --client=${_cip} --ip=${_sip} --server=${NFS_HOSTNAME} --stateval=${_state_odd}
592 EOF
593         done
594     done | {
595         ok
596         simple_test_event "notify"
597     } || test_fail
598 }
599
600 ######################################################################
601
602 setup_ctdb_natgw ()
603 {
604         debug "Setting up NAT gateway"
605
606         natgw_config_dir="${TEST_VAR_DIR}/natgw_config"
607         mkdir -p "$natgw_config_dir"
608
609         # These will accumulate, 1 per test... but will be cleaned up at
610         # the end.
611         export CTDB_NATGW_NODES=$(mktemp --tmpdir="$natgw_config_dir")
612
613         # Read from stdin
614         while read _ip _opts ; do
615                 case "$_opts" in
616                 master)
617                         export FAKE_CTDB_NATGW_MASTER="$_ip"
618                         echo "$_ip"
619                         ;;
620                 slave-only)
621                         printf "%s\tslave-only\n" "$_ip"
622                         ;;
623                 *)
624                         echo "$_ip"
625                         ;;
626                 esac
627         done >"$CTDB_NATGW_NODES"
628
629         # Assume all of the nodes are on a /24 network and have IPv4
630         # addresses:
631         read _ip <"$CTDB_NATGW_NODES"
632         export CTDB_NATGW_PRIVATE_NETWORK="${_ip%.*}.0/24"
633
634         # These are fixed.  Probably don't use the same network for the
635         # private node IPs.  To unset the default gateway just set it to
636         # "".  :-)
637         export CTDB_NATGW_PUBLIC_IP="10.1.1.121/24"
638         export CTDB_NATGW_PUBLIC_IFACE="eth1"
639         export CTDB_NATGW_DEFAULT_GATEWAY="10.1.1.254"
640         export CTDB_NATGW_SLAVE_ONLY=""
641 }
642
643 ok_natgw_master_ip_addr_show ()
644 {
645     _mac=$(echo "$CTDB_NATGW_PUBLIC_IFACE" | md5sum | sed -r -e 's@(..)(..)(..)(..)(..)(..).*@\1:\2:\3:\4:\5:\6@')
646
647     # This is based on CTDB_NATGW_PUBLIC_IP
648     _brd="10.1.1.255"
649
650 ok <<EOF
651 1: ${CTDB_NATGW_PUBLIC_IFACE}: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
652     link/ether ${_mac} brd ff:ff:ff:ff:ff:ff
653     inet ${CTDB_NATGW_PUBLIC_IP} brd ${_brd} scope global ${CTDB_NATGW_PUBLIC_IFACE}
654        valid_lft forever preferred_lft forever
655 EOF
656 }
657
658 ok_natgw_slave_ip_addr_show ()
659 {
660     _mac=$(echo "$CTDB_NATGW_PUBLIC_IFACE" | md5sum | sed -r -e 's@(..)(..)(..)(..)(..)(..).*@\1:\2:\3:\4:\5:\6@')
661 ok <<EOF
662 1: ${CTDB_NATGW_PUBLIC_IFACE}: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
663     link/ether ${_mac} brd ff:ff:ff:ff:ff:ff
664 EOF
665 }
666
667 ok_natgw_master_static_routes ()
668 {
669     _nl="
670 "
671     _t=""
672     for _i in $CTDB_NATGW_STATIC_ROUTES ; do
673         # This is intentionally different to the code in 11.natgw ;-)
674         case "$_i" in
675             *@*)
676                 _net=$(echo "$_i" | sed -e 's|@.*||')
677                 _gw=$(echo "$_i" | sed -e 's|.*@||')
678                 ;;
679             *)
680                 _net="$_i"
681                 _gw="$CTDB_NATGW_DEFAULT_GATEWAY"
682         esac
683
684         [ -n "$_gw" ] || continue
685         _t="${_t}${_t:+${_nl}}"
686         _t="${_t}${_net} via ${_gw} dev ethXXX  metric 10 "
687     done
688     _t=$(echo "$_t" | sort)
689     ok "$_t"
690 }
691
692 ok_natgw_slave_static_routes ()
693 {
694     _nl="
695 "
696     _t=""
697     for _i in $CTDB_NATGW_STATIC_ROUTES ; do
698         # This is intentionally different to the code in 11.natgw ;-)
699         _net=$(echo "$_i" | sed -e 's|@.*||')
700
701         # The interface for the private network isn't specified as
702         # part of the NATGW configuration and isn't part of the
703         # command to add the route.  It is implicitly added by "ip
704         # route" but our stub doesn't do this and adds "ethXXX".
705         _t="${_t}${_t:+${_nl}}"
706         _t="${_t}${_net} via ${FAKE_CTDB_NATGW_MASTER} dev ethXXX  metric 10 "
707     done
708     _t=$(echo "$_t" | sort)
709     ok "$_t"
710 }
711
712 ######################################################################
713
714 # Samba/winbind fakery
715
716 setup_samba ()
717 {
718     setup_ctdb
719
720     service_name="samba"
721
722     if [ "$1" != "down" ] ; then
723
724         debug "Marking Samba services as up, listening and managed by CTDB"
725         # Get into known state.
726         eventscript_call ctdb_service_managed
727
728         # All possible service names for all known distros.
729         for i in "smb" "nmb" "samba" ; do
730             service "$i" force-started
731         done
732
733         export CTDB_SAMBA_SKIP_SHARE_CHECK="no"
734         export CTDB_MANAGED_SERVICES="foo samba bar"
735
736         export FAKE_TCP_LISTEN="0.0.0.0:445 0.0.0.0:139"
737         export FAKE_WBINFO_FAIL="no"
738
739         # Some things in 50.samba are backgrounded and waited for.  If
740         # we don't sleep at all then timeouts can happen.  This avoids
741         # that...  :-)
742         export FAKE_SLEEP_FORCE=0.1
743     else
744         debug "Marking Samba services as down, not listening and not managed by CTDB"
745         # Get into known state.
746         eventscript_call ctdb_service_unmanaged
747
748         # All possible service names for all known distros.
749         for i in "smb" "nmb" "samba" ; do
750             service "$i" force-stopped
751         done
752
753         export CTDB_SAMBA_SKIP_SHARE_CHECK="no"
754         export CTDB_MANAGED_SERVICES="foo bar"
755         unset CTDB_MANAGES_SAMBA
756
757         export FAKE_TCP_LISTEN=""
758         export FAKE_WBINFO_FAIL="yes"
759     fi
760 }
761
762 setup_winbind ()
763 {
764     setup_ctdb
765
766     service_name="winbind"
767
768     if [ "$1" != "down" ] ; then
769
770         debug "Marking Winbind service as up and managed by CTDB"
771         # Get into known state.
772         eventscript_call ctdb_service_managed
773
774         service "winbind" force-started
775
776         export CTDB_MANAGED_SERVICES="foo winbind bar"
777
778         export FAKE_WBINFO_FAIL="no"
779
780     else
781         debug "Marking Winbind service as down and not managed by CTDB"
782         # Get into known state.
783         eventscript_call ctdb_service_unmanaged
784
785         service "winbind" force-stopped
786
787         export CTDB_MANAGED_SERVICES="foo bar"
788         unset CTDB_MANAGES_WINBIND
789
790         export FAKE_WBINFO_FAIL="yes"
791     fi
792 }
793
794 wbinfo_down ()
795 {
796     debug "Making wbinfo commands fail"
797     FAKE_WBINFO_FAIL="yes"
798 }
799
800 ######################################################################
801
802 # NFS fakery
803
804 setup_nfs ()
805 {
806     setup_ctdb
807
808     service_name="nfs"
809
810     export FAKE_RPCINFO_SERVICES=""
811
812     export CTDB_NFS_SKIP_SHARE_CHECK="no"
813
814     export RPCNFSDCOUNT
815
816     # This doesn't even need to exist
817     export CTDB_NFS_EXPORTS_FILE="$EVENTSCRIPTS_TESTS_VAR_DIR/etc-exports"
818
819     # Reset the failcounts for nfs services.
820     eventscript_call eval rm -f '$ctdb_fail_dir/nfs_*'
821
822     if [ "$1" != "down" ] ; then
823         debug "Setting up NFS environment: all RPC services up, NFS managed by CTDB"
824
825         eventscript_call ctdb_service_managed
826         service "nfs" force-started
827         service "nfslock" force-started
828
829         export CTDB_MANAGED_SERVICES="foo nfs bar"
830
831         rpc_services_up \
832             "portmapper" "nfs" "mountd" "rquotad" "nlockmgr" "status"
833
834         nfs_setup_fake_threads "nfsd"
835         nfs_setup_fake_threads "rpc.foobar"  # Just set the variable to empty
836     else
837         debug "Setting up NFS environment: all RPC services down, NFS not managed by CTDB"
838
839         eventscript_call ctdb_service_unmanaged
840         service "nfs" force-stopped
841         service "nfslock" force-stopped
842
843         export CTDB_MANAGED_SERVICES="foo bar"
844         unset CTDB_MANAGES_NFS
845     fi
846
847     # This is really nasty.  However, when we test NFS we don't
848     # actually test statd-callout. If we leave it there then left
849     # over, backgrounded instances of statd-callout will do horrible
850     # things with the "ctdb ip" stub and cause the actual
851     # statd-callout tests that follow to fail.
852     rm "${CTDB_BASE}/statd-callout"
853 }
854
855 setup_nfs_ganesha ()
856 {
857     setup_nfs "$@"
858     export CTDB_NFS_CALLOUT="${CTDB_BASE}/nfs-ganesha-callout"
859     if [ "$1" != "down" ] ; then
860         export CTDB_MANAGES_NFS="yes"
861     fi
862
863     export CTDB_NFS_SKIP_SHARE_CHECK="yes"
864 }
865
866 rpc_services_down ()
867 {
868     for _i ; do
869         debug "Marking RPC service \"${_i}\" as unavailable"
870         FAKE_RPCINFO_SERVICES=$(echo "$FAKE_RPCINFO_SERVICES" | sed -r -e "s@[[:space:]]*${_i}:[0-9]+:[0-9]+@@g")
871     done
872 }
873
874 rpc_services_up ()
875 {
876     for _i ; do
877         debug "Marking RPC service \"${_i}\" as available"
878         case "$_i" in
879             portmapper) _t="2:4" ;;
880             nfs)        _t="2:3" ;;
881             mountd)     _t="1:3" ;;
882             rquotad)    _t="1:2" ;;
883             nlockmgr)   _t="3:4" ;;
884             status)     _t="1:1" ;;
885             *) die "Internal error - unsupported RPC service \"${_i}\"" ;;
886         esac
887
888         FAKE_RPCINFO_SERVICES="${FAKE_RPCINFO_SERVICES}${FAKE_RPCINFO_SERVICES:+ }${_i}:${_t}"
889     done
890 }
891
892
893 nfs_load_config ()
894 {
895     _etc="$CTDB_SYS_ETCDIR" # shortcut for readability
896     for _c in "$_etc/sysconfig/nfs" "$_etc/default/nfs" "$_etc/ctdb/sysconfig/nfs" ; do
897         if [ -r "$_c" ] ; then
898             . "$_c"
899             break
900         fi
901     done
902 }
903
904 nfs_setup_fake_threads ()
905 {
906     _prog="$1" ; shift
907
908     case "$_prog" in
909         nfsd)
910             export PROCFS_PATH=$(mktemp -d --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
911             _threads="${PROCFS_PATH}/fs/nfsd/threads"
912             mkdir -p $(dirname "$_threads")
913             echo $# >"$_threads"
914             export FAKE_NFSD_THREAD_PIDS="$*"
915             ;;
916         *)
917             export FAKE_RPC_THREAD_PIDS="$*"
918             ;;
919     esac
920 }
921
922 program_stack_traces ()
923 {
924     _prog="$1"
925     _max="${2:-1}"
926
927     _count=1
928     for _pid in ${FAKE_NFSD_THREAD_PIDS:-$FAKE_RPC_THREAD_PIDS} ; do
929         [ $_count -le $_max ] || break
930
931         cat <<EOF
932 Stack trace for ${_prog}[${_pid}]:
933 [<ffffffff87654321>] fake_stack_trace_for_pid_${_pid}/stack+0x0/0xff
934 EOF
935         _count=$(($_count + 1))
936     done
937 }
938
939 guess_output ()
940 {
941     case "$1" in
942         $CTDB_NFS_CALLOUT\ start\ nlockmgr)
943             echo "&Starting nfslock: OK"
944             ;;
945         $CTDB_NFS_CALLOUT\ start\ nfs)
946             cat <<EOF
947 &Starting nfslock: OK
948 &Starting nfs: OK
949 EOF
950             ;;
951         *)
952             : # Nothing
953     esac
954 }
955
956 # Set the required result for a particular RPC program having failed
957 # for a certain number of iterations.  This is probably still a work
958 # in progress.  Note that we could hook aggressively
959 # nfs_check_rpc_service() to try to implement this but we're better
960 # off testing nfs_check_rpc_service() using independent code...  even
961 # if it is incomplete and hacky.  So, if the 60.nfs eventscript
962 # changes and the tests start to fail then it may be due to this
963 # function being incomplete.
964 rpc_set_service_failure_response ()
965 {
966     _rpc_service="$1"
967     _numfails="${2:-1}" # default 1
968
969     # Default
970     ok_null
971     if [ $_numfails -eq 0 ] ; then
972         return
973     fi
974
975     nfs_load_config
976
977     # A handy newline.  :-)
978     _nl="
979 "
980
981     _dir="${CTDB_NFS_CHECKS_DIR:-${CTDB_BASE}/nfs-checks.d}"
982
983     _file=$(ls "$_dir"/[0-9][0-9]."${_rpc_service}.check")
984     [ -r "$_file" ] || die "RPC check file \"$_file\" does not exist or is not unique"
985
986     _out=$(mktemp --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
987     _rc_file=$(mktemp --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
988
989     (
990         # Subshell to restrict scope variables...
991
992         # Defaults
993         family="tcp"
994         version=""
995         unhealthy_after=1
996         restart_every=0
997         service_stop_cmd=""
998         service_start_cmd=""
999         service_check_cmd=""
1000         service_debug_cmd=""
1001
1002         # Don't bother syntax checking, eventscript does that...
1003         . "$_file"
1004
1005         # Just use the first version, or use default.  This is dumb but
1006         # handles all the cases that we care about now...
1007         if [ -n "$version" ] ; then
1008             _ver="${version%% *}"
1009         else
1010             case "$_rpc_service" in
1011                 portmapper) _ver="" ;;
1012                 *)          _ver=1  ;;
1013             esac
1014         fi
1015         _rpc_check_out="\
1016 $_rpc_service failed RPC check:
1017 rpcinfo: RPC: Program not registered
1018 program $_rpc_service${_ver:+ version }${_ver} is not available"
1019
1020         if [ $unhealthy_after -gt 0 -a $_numfails -ge $unhealthy_after ] ; then
1021             _unhealthy=true
1022             echo 1 >"$_rc_file"
1023             echo "ERROR: ${_rpc_check_out}" >>"$_out"
1024         else
1025             _unhealthy=false
1026             echo 0 >"$_rc_file"
1027         fi
1028
1029         if [ $restart_every -gt 0 -a $(($_numfails % $restart_every)) -eq 0 ] ; then
1030             if ! $_unhealthy ; then
1031                 echo "WARNING: ${_rpc_check_out}" >>"$_out"
1032             fi
1033
1034             echo "Trying to restart service \"${_rpc_service}\"..." >>"$_out"
1035
1036             if [ -n "$service_debug_cmd" ] ; then
1037                 $service_debug_cmd 2>&1 >>"$_out"
1038             fi
1039
1040             guess_output "$service_start_cmd" >>"$_out"
1041         fi
1042     )
1043
1044     read _rc <"$_rc_file"
1045     required_result $_rc <"$_out"
1046
1047     rm -f "$_out" "$_rc_file"
1048 }
1049
1050 ######################################################################
1051
1052 # VSFTPD fakery
1053
1054 setup_vsftpd ()
1055 {
1056     service_name="vsftpd"
1057
1058     if [ "$1" != "down" ] ; then
1059         die "setup_vsftpd up not implemented!!!"
1060     else
1061         debug "Setting up VSFTPD environment: service down, not managed by CTDB"
1062
1063         eventscript_call ctdb_service_unmanaged
1064         service vsftpd force-stopped
1065
1066         export CTDB_MANAGED_SERVICES="foo"
1067         unset CTDB_MANAGES_VSFTPD
1068     fi
1069 }
1070
1071 ######################################################################
1072
1073 # HTTPD fakery
1074
1075 setup_httpd ()
1076 {
1077     if [ "$1" != "down" ] ; then
1078         die "setup_httpd up not implemented!!!"
1079     else
1080         debug "Setting up HTTPD environment: service down, not managed by CTDB"
1081
1082         for service_name in "apache2" "httpd" ; do
1083             eventscript_call ctdb_service_unmanaged
1084             service "$service_name" force-stopped
1085         done
1086
1087         export CTDB_MANAGED_SERVICES="foo"
1088         unset CTDB_MANAGES_HTTPD
1089     fi
1090 }
1091
1092 ######################################################################
1093
1094 # multipathd fakery
1095
1096 setup_multipathd ()
1097 {
1098     for i ; do
1099         case "$i" in
1100             \!*)
1101                 _t="${i#!}"
1102                 echo "Marking ${_t} as having no active paths"
1103                 FAKE_MULTIPATH_FAILURES="${FAKE_MULTIPATH_FAILURES}${FAKE_MULTIPATH+FAILURES:+ }${_t}"
1104                 ;;
1105             *)
1106                 _t="$i"         
1107         esac
1108         CTDB_MONITOR_MPDEVICES="${CTDB_MONITOR_MPDEVICES}${CTDB_MONITOR_MPDEVICES:+ }${_t}"
1109     done
1110
1111     export CTDB_MONITOR_MPDEVICES FAKE_MULTIPATH_FAILURES
1112     export FAKE_SLEEP_FORCE=0.1
1113 }
1114
1115 ######################################################################
1116
1117 # Result and test functions
1118
1119 # Set some globals and print the summary.
1120 define_test ()
1121 {
1122     desc="$1"
1123
1124     _f=$(basename "$0" ".sh")
1125
1126     # Remaining format should be NN.service.event.NNN or NN.service.NNN:
1127     _num="${_f##*.}"
1128     _f="${_f%.*}"
1129
1130     case "$_f" in
1131         [0-9][0-9].*.*)
1132             script="${_f%.*}"
1133             event="${_f##*.}"
1134             script_dir="${CTDB_BASE}/events.d"
1135             ;;
1136         [0-9][0-9].*)
1137             script="$_f"
1138             unset event
1139             script_dir="${CTDB_BASE}/events.d"
1140             ;;
1141         *.*)
1142             script="${_f%.*}"
1143             event="${_f##*.}"
1144             script_dir="${CTDB_BASE}"
1145             ;;
1146         *)
1147             script="${_f%.*}"
1148             unset event
1149             script_dir="${CTDB_BASE}"
1150     esac
1151
1152     [ -r "${script_dir}/${script}" ] || \
1153         die "Internal error - unable to find script \"${script_dir}/${script}\""
1154
1155     printf "%-17s %-10s %-4s - %s\n\n" "$script" "$event" "$_num" "$desc"
1156 }
1157
1158 # Run an eventscript once.  The test passes if the return code and
1159 # output match those required.
1160
1161 # Any args are passed to the eventscript.
1162
1163 simple_test ()
1164 {
1165     [ -n "$event" ] || die 'simple_test: $event not set'
1166
1167     args="$@"
1168
1169     test_header ()
1170     {
1171         echo "Running script \"$script $event${args:+ }$args\""
1172     }
1173
1174     extra_header ()
1175     {
1176         cat <<EOF
1177
1178 ##################################################
1179 CTDB_BASE="$CTDB_BASE"
1180 CTDB_SYS_ETCDIR="$CTDB_SYS_ETCDIR"
1181 ctdb client is "$(which ctdb)"
1182 ip command is "$(which ip)"
1183 EOF
1184     }
1185
1186     script_test "${script_dir}/${script}" "$event" "$@"
1187
1188     reset_test_header
1189     reset_extra_header
1190 }
1191
1192 simple_test_event ()
1193 {
1194     # If something has previously failed then don't continue.
1195     : ${_passed:=true}
1196     $_passed || return 1
1197
1198     event="$1" ; shift
1199     echo "=================================================="
1200     simple_test "$@"
1201 }
1202
1203 simple_test_command ()
1204 {
1205     unit_test "$@"
1206 }
1207
1208 # Run an NFS eventscript iteratively.
1209 #
1210 # - 1st argument is the number of iterations.
1211 #
1212 # - 2nd argument is the NFS/RPC service being tested
1213 #
1214 #   rpcinfo (or $service_check_cmd) is used on each iteration to test
1215 #   the availability of the service
1216 #
1217 #   If this is not set or null then no RPC service is checked and the
1218 #   required output is not reset on each iteration.  This is useful in
1219 #   baseline tests to confirm that the eventscript and test
1220 #   infrastructure is working correctly.
1221 #
1222 # - Subsequent arguments come in pairs: an iteration number and
1223 #   something to eval before that iteration.  Each time an iteration
1224 #   number is matched the associated argument is given to eval after
1225 #   the default setup is done.  The iteration numbers need to be given
1226 #   in ascending order.
1227 #
1228 #   These arguments can allow a service to be started or stopped
1229 #   before a particular iteration.
1230 #
1231 nfs_iterate_test ()
1232 {
1233     _repeats="$1"
1234     _rpc_service="$2"
1235     if [ -n "$2" ] ; then
1236         shift 2
1237     else
1238         shift
1239     fi
1240
1241     echo "Running $_repeats iterations of \"$script $event\" $args"
1242
1243     _iterate_failcount=0
1244     for _iteration in $(seq 1 $_repeats) ; do
1245         # This is not a numerical comparison because $1 will often not
1246         # be set.
1247         if [ "$_iteration" = "$1" ] ; then
1248             debug "##################################################"
1249             eval "$2"
1250             debug "##################################################"
1251             shift 2
1252         fi
1253         if [ -n "$_rpc_service" ] ; then
1254             _ok=false
1255             if [ -n "$service_check_cmd" ] ; then
1256                 if eval "$service_check_cmd" ; then
1257                     _ok=true
1258                 fi
1259             else
1260                 if rpcinfo -T tcp localhost "$_rpc_service" >/dev/null 2>&1 ; then
1261                     _ok=true
1262                 fi
1263             fi
1264
1265             if $_ok ; then
1266                 _iterate_failcount=0
1267             else
1268                 _iterate_failcount=$(($_iterate_failcount + 1))
1269             fi
1270             rpc_set_service_failure_response "$_rpc_service" $_iterate_failcount
1271         fi
1272         _out=$(simple_test 2>&1)
1273         _ret=$?
1274         if "$TEST_VERBOSE" || [ $_ret -ne 0 ] ; then
1275             echo "##################################################"
1276             echo "Iteration ${_iteration}:"
1277             echo "$_out"
1278         fi
1279         if [ $_ret -ne 0 ] ; then
1280             exit $_ret
1281         fi
1282     done
1283 }