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