ctdb-scripts: Add exportfs cache to NFS Linux kernel callout
[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 _master _dev ; do
615         echo "$_ip"
616         if [ "$_master" = "master" ] ; then
617             export FAKE_CTDB_NATGW_MASTER="$_ip"
618         fi
619     done >"$CTDB_NATGW_NODES"
620
621     # Assume all of the nodes are on a /24 network and have IPv4
622     # addresses:
623     read _ip <"$CTDB_NATGW_NODES"
624     export CTDB_NATGW_PRIVATE_NETWORK="${_ip%.*}.0/24"
625
626     # These are fixed.  Probably don't use the same network for the
627     # private node IPs.  To unset the default gateway just set it to
628     # "".  :-)
629     export CTDB_NATGW_PUBLIC_IP="10.1.1.121/24"
630     export CTDB_NATGW_PUBLIC_IFACE="eth1"
631     export CTDB_NATGW_DEFAULT_GATEWAY="10.1.1.254"
632     export CTDB_NATGW_SLAVE_ONLY=""
633 }
634
635 ok_natgw_master_ip_addr_show ()
636 {
637     _mac=$(echo "$CTDB_NATGW_PUBLIC_IFACE" | md5sum | sed -r -e 's@(..)(..)(..)(..)(..)(..).*@\1:\2:\3:\4:\5:\6@')
638
639     # This is based on CTDB_NATGW_PUBLIC_IP
640     _brd="10.1.1.255"
641
642 ok <<EOF
643 1: ${CTDB_NATGW_PUBLIC_IFACE}: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
644     link/ether ${_mac} brd ff:ff:ff:ff:ff:ff
645     inet ${CTDB_NATGW_PUBLIC_IP} brd ${_brd} scope global ${CTDB_NATGW_PUBLIC_IFACE}
646        valid_lft forever preferred_lft forever
647 EOF
648 }
649
650 ok_natgw_slave_ip_addr_show ()
651 {
652     _mac=$(echo "$CTDB_NATGW_PUBLIC_IFACE" | md5sum | sed -r -e 's@(..)(..)(..)(..)(..)(..).*@\1:\2:\3:\4:\5:\6@')
653 ok <<EOF
654 1: ${CTDB_NATGW_PUBLIC_IFACE}: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
655     link/ether ${_mac} brd ff:ff:ff:ff:ff:ff
656 EOF
657 }
658
659 ok_natgw_master_static_routes ()
660 {
661     _nl="
662 "
663     _t=""
664     for _i in $CTDB_NATGW_STATIC_ROUTES ; do
665         # This is intentionally different to the code in 11.natgw ;-)
666         case "$_i" in
667             *@*)
668                 _net=$(echo "$_i" | sed -e 's|@.*||')
669                 _gw=$(echo "$_i" | sed -e 's|.*@||')
670                 ;;
671             *)
672                 _net="$_i"
673                 _gw="$CTDB_NATGW_DEFAULT_GATEWAY"
674         esac
675
676         [ -n "$_gw" ] || continue
677         _t="${_t}${_t:+${_nl}}"
678         _t="${_t}${_net} via ${_gw} dev ethXXX  metric 10 "
679     done
680     _t=$(echo "$_t" | sort)
681     ok "$_t"
682 }
683
684 ok_natgw_slave_static_routes ()
685 {
686     _nl="
687 "
688     _t=""
689     for _i in $CTDB_NATGW_STATIC_ROUTES ; do
690         # This is intentionally different to the code in 11.natgw ;-)
691         _net=$(echo "$_i" | sed -e 's|@.*||')
692
693         # The interface for the private network isn't specified as
694         # part of the NATGW configuration and isn't part of the
695         # command to add the route.  It is implicitly added by "ip
696         # route" but our stub doesn't do this and adds "ethXXX".
697         _t="${_t}${_t:+${_nl}}"
698         _t="${_t}${_net} via ${FAKE_CTDB_NATGW_MASTER} dev ethXXX  metric 10 "
699     done
700     _t=$(echo "$_t" | sort)
701     ok "$_t"
702 }
703
704 ######################################################################
705
706 # Samba/winbind fakery
707
708 setup_samba ()
709 {
710     setup_ctdb
711
712     service_name="samba"
713
714     if [ "$1" != "down" ] ; then
715
716         debug "Marking Samba services as up, listening and managed by CTDB"
717         # Get into known state.
718         eventscript_call ctdb_service_managed
719
720         # All possible service names for all known distros.
721         for i in "smb" "nmb" "samba" ; do
722             service "$i" force-started
723         done
724
725         export CTDB_SAMBA_SKIP_SHARE_CHECK="no"
726         export CTDB_MANAGED_SERVICES="foo samba bar"
727
728         export FAKE_TCP_LISTEN="0.0.0.0:445 0.0.0.0:139"
729         export FAKE_WBINFO_FAIL="no"
730
731         # Some things in 50.samba are backgrounded and waited for.  If
732         # we don't sleep at all then timeouts can happen.  This avoids
733         # that...  :-)
734         export FAKE_SLEEP_FORCE=0.1
735     else
736         debug "Marking Samba services as down, not listening and not managed by CTDB"
737         # Get into known state.
738         eventscript_call ctdb_service_unmanaged
739
740         # All possible service names for all known distros.
741         for i in "smb" "nmb" "samba" ; do
742             service "$i" force-stopped
743         done
744
745         export CTDB_SAMBA_SKIP_SHARE_CHECK="no"
746         export CTDB_MANAGED_SERVICES="foo bar"
747         unset CTDB_MANAGES_SAMBA
748
749         export FAKE_TCP_LISTEN=""
750         export FAKE_WBINFO_FAIL="yes"
751     fi
752 }
753
754 setup_winbind ()
755 {
756     setup_ctdb
757
758     service_name="winbind"
759
760     if [ "$1" != "down" ] ; then
761
762         debug "Marking Winbind service as up and managed by CTDB"
763         # Get into known state.
764         eventscript_call ctdb_service_managed
765
766         service "winbind" force-started
767
768         export CTDB_MANAGED_SERVICES="foo winbind bar"
769
770         export FAKE_WBINFO_FAIL="no"
771
772     else
773         debug "Marking Winbind service as down and not managed by CTDB"
774         # Get into known state.
775         eventscript_call ctdb_service_unmanaged
776
777         service "winbind" force-stopped
778
779         export CTDB_MANAGED_SERVICES="foo bar"
780         unset CTDB_MANAGES_WINBIND
781
782         export FAKE_WBINFO_FAIL="yes"
783     fi
784 }
785
786 wbinfo_down ()
787 {
788     debug "Making wbinfo commands fail"
789     FAKE_WBINFO_FAIL="yes"
790 }
791
792 ######################################################################
793
794 # NFS fakery
795
796 setup_nfs ()
797 {
798     setup_ctdb
799
800     service_name="nfs"
801
802     export FAKE_RPCINFO_SERVICES=""
803
804     export CTDB_NFS_SKIP_SHARE_CHECK="no"
805
806     export RPCNFSDCOUNT
807
808     # This doesn't even need to exist
809     export CTDB_NFS_EXPORTS_FILE="$EVENTSCRIPTS_TESTS_VAR_DIR/etc-exports"
810
811     # Reset the failcounts for nfs services.
812     eventscript_call eval rm -f '$ctdb_fail_dir/nfs_*'
813
814     if [ "$1" != "down" ] ; then
815         debug "Setting up NFS environment: all RPC services up, NFS managed by CTDB"
816
817         eventscript_call ctdb_service_managed
818         service "nfs" force-started
819         service "nfslock" force-started
820
821         export CTDB_MANAGED_SERVICES="foo nfs bar"
822
823         rpc_services_up \
824             "portmapper" "nfs" "mountd" "rquotad" "nlockmgr" "status"
825
826         nfs_setup_fake_threads "nfsd"
827         nfs_setup_fake_threads "rpc.foobar"  # Just set the variable to empty
828     else
829         debug "Setting up NFS environment: all RPC services down, NFS not managed by CTDB"
830
831         eventscript_call ctdb_service_unmanaged
832         service "nfs" force-stopped
833         service "nfslock" force-stopped
834
835         export CTDB_MANAGED_SERVICES="foo bar"
836         unset CTDB_MANAGES_NFS
837     fi
838
839     # This is really nasty.  However, when we test NFS we don't
840     # actually test statd-callout. If we leave it there then left
841     # over, backgrounded instances of statd-callout will do horrible
842     # things with the "ctdb ip" stub and cause the actual
843     # statd-callout tests that follow to fail.
844     rm "${CTDB_BASE}/statd-callout"
845 }
846
847 setup_nfs_ganesha ()
848 {
849     setup_nfs "$@"
850     export CTDB_NFS_CALLOUT="${CTDB_BASE}/nfs-ganesha-callout"
851     if [ "$1" != "down" ] ; then
852         export CTDB_MANAGES_NFS="yes"
853     fi
854
855     export CTDB_NFS_SKIP_SHARE_CHECK="yes"
856 }
857
858 rpc_services_down ()
859 {
860     for _i ; do
861         debug "Marking RPC service \"${_i}\" as unavailable"
862         FAKE_RPCINFO_SERVICES=$(echo "$FAKE_RPCINFO_SERVICES" | sed -r -e "s@[[:space:]]*${_i}:[0-9]+:[0-9]+@@g")
863     done
864 }
865
866 rpc_services_up ()
867 {
868     for _i ; do
869         debug "Marking RPC service \"${_i}\" as available"
870         case "$_i" in
871             portmapper) _t="2:4" ;;
872             nfs)        _t="2:3" ;;
873             mountd)     _t="1:3" ;;
874             rquotad)    _t="1:2" ;;
875             nlockmgr)   _t="3:4" ;;
876             status)     _t="1:1" ;;
877             *) die "Internal error - unsupported RPC service \"${_i}\"" ;;
878         esac
879
880         FAKE_RPCINFO_SERVICES="${FAKE_RPCINFO_SERVICES}${FAKE_RPCINFO_SERVICES:+ }${_i}:${_t}"
881     done
882 }
883
884
885 nfs_load_config ()
886 {
887     _etc="$CTDB_SYS_ETCDIR" # shortcut for readability
888     for _c in "$_etc/sysconfig/nfs" "$_etc/default/nfs" "$_etc/ctdb/sysconfig/nfs" ; do
889         if [ -r "$_c" ] ; then
890             . "$_c"
891             break
892         fi
893     done
894 }
895
896 nfs_setup_fake_threads ()
897 {
898     _prog="$1" ; shift
899
900     case "$_prog" in
901         nfsd)
902             export PROCFS_PATH=$(mktemp -d --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
903             _threads="${PROCFS_PATH}/fs/nfsd/threads"
904             mkdir -p $(dirname "$_threads")
905             echo $# >"$_threads"
906             export FAKE_NFSD_THREAD_PIDS="$*"
907             ;;
908         *)
909             export FAKE_RPC_THREAD_PIDS="$*"
910             ;;
911     esac
912 }
913
914 program_stack_traces ()
915 {
916     _prog="$1"
917     _max="${2:-1}"
918
919     _count=1
920     for _pid in ${FAKE_NFSD_THREAD_PIDS:-$FAKE_RPC_THREAD_PIDS} ; do
921         [ $_count -le $_max ] || break
922
923         cat <<EOF
924 Stack trace for ${_prog}[${_pid}]:
925 [<ffffffff87654321>] fake_stack_trace_for_pid_${_pid}/stack+0x0/0xff
926 EOF
927         _count=$(($_count + 1))
928     done
929 }
930
931 guess_output ()
932 {
933     case "$1" in
934         $CTDB_NFS_CALLOUT\ start\ nlockmgr)
935             echo "&Starting nfslock: OK"
936             ;;
937         $CTDB_NFS_CALLOUT\ start\ nfs)
938             cat <<EOF
939 &Starting nfslock: OK
940 &Starting nfs: OK
941 EOF
942             ;;
943         *)
944             : # Nothing
945     esac
946 }
947
948 # Set the required result for a particular RPC program having failed
949 # for a certain number of iterations.  This is probably still a work
950 # in progress.  Note that we could hook aggressively
951 # nfs_check_rpc_service() to try to implement this but we're better
952 # off testing nfs_check_rpc_service() using independent code...  even
953 # if it is incomplete and hacky.  So, if the 60.nfs eventscript
954 # changes and the tests start to fail then it may be due to this
955 # function being incomplete.
956 rpc_set_service_failure_response ()
957 {
958     _rpc_service="$1"
959     _numfails="${2:-1}" # default 1
960
961     # Default
962     ok_null
963     if [ $_numfails -eq 0 ] ; then
964         return
965     fi
966
967     nfs_load_config
968
969     # A handy newline.  :-)
970     _nl="
971 "
972
973     _dir="${CTDB_NFS_CHECKS_DIR:-${CTDB_BASE}/nfs-checks.d}"
974
975     _file=$(ls "$_dir"/[0-9][0-9]."${_rpc_service}.check")
976     [ -r "$_file" ] || die "RPC check file \"$_file\" does not exist or is not unique"
977
978     _out=$(mktemp --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
979     _rc_file=$(mktemp --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
980
981     (
982         # Subshell to restrict scope variables...
983
984         # Defaults
985         family="tcp"
986         version=""
987         unhealthy_after=1
988         restart_every=0
989         service_stop_cmd=""
990         service_start_cmd=""
991         service_check_cmd=""
992         service_debug_cmd=""
993
994         # Don't bother syntax checking, eventscript does that...
995         . "$_file"
996
997         # Just use the first version, or use default.  This is dumb but
998         # handles all the cases that we care about now...
999         if [ -n "$version" ] ; then
1000             _ver="${version%% *}"
1001         else
1002             case "$_rpc_service" in
1003                 portmapper) _ver="" ;;
1004                 *)          _ver=1  ;;
1005             esac
1006         fi
1007         _rpc_check_out="\
1008 $_rpc_service failed RPC check:
1009 rpcinfo: RPC: Program not registered
1010 program $_rpc_service${_ver:+ version }${_ver} is not available"
1011
1012         if [ $unhealthy_after -gt 0 -a $_numfails -ge $unhealthy_after ] ; then
1013             _unhealthy=true
1014             echo 1 >"$_rc_file"
1015             echo "ERROR: ${_rpc_check_out}" >>"$_out"
1016         else
1017             _unhealthy=false
1018             echo 0 >"$_rc_file"
1019         fi
1020
1021         if [ $restart_every -gt 0 -a $(($_numfails % $restart_every)) -eq 0 ] ; then
1022             if ! $_unhealthy ; then
1023                 echo "WARNING: ${_rpc_check_out}" >>"$_out"
1024             fi
1025
1026             echo "Trying to restart service \"${_rpc_service}\"..." >>"$_out"
1027
1028             if [ -n "$service_debug_cmd" ] ; then
1029                 $service_debug_cmd 2>&1 >>"$_out"
1030             fi
1031
1032             guess_output "$service_start_cmd" >>"$_out"
1033         fi
1034     )
1035
1036     read _rc <"$_rc_file"
1037     required_result $_rc <"$_out"
1038
1039     rm -f "$_out" "$_rc_file"
1040 }
1041
1042 ######################################################################
1043
1044 # VSFTPD fakery
1045
1046 setup_vsftpd ()
1047 {
1048     service_name="vsftpd"
1049
1050     if [ "$1" != "down" ] ; then
1051         die "setup_vsftpd up not implemented!!!"
1052     else
1053         debug "Setting up VSFTPD environment: service down, not managed by CTDB"
1054
1055         eventscript_call ctdb_service_unmanaged
1056         service vsftpd force-stopped
1057
1058         export CTDB_MANAGED_SERVICES="foo"
1059         unset CTDB_MANAGES_VSFTPD
1060     fi
1061 }
1062
1063 ######################################################################
1064
1065 # HTTPD fakery
1066
1067 setup_httpd ()
1068 {
1069     if [ "$1" != "down" ] ; then
1070         die "setup_httpd up not implemented!!!"
1071     else
1072         debug "Setting up HTTPD environment: service down, not managed by CTDB"
1073
1074         for service_name in "apache2" "httpd" ; do
1075             eventscript_call ctdb_service_unmanaged
1076             service "$service_name" force-stopped
1077         done
1078
1079         export CTDB_MANAGED_SERVICES="foo"
1080         unset CTDB_MANAGES_HTTPD
1081     fi
1082 }
1083
1084 ######################################################################
1085
1086 # multipathd fakery
1087
1088 setup_multipathd ()
1089 {
1090     for i ; do
1091         case "$i" in
1092             \!*)
1093                 _t="${i#!}"
1094                 echo "Marking ${_t} as having no active paths"
1095                 FAKE_MULTIPATH_FAILURES="${FAKE_MULTIPATH_FAILURES}${FAKE_MULTIPATH+FAILURES:+ }${_t}"
1096                 ;;
1097             *)
1098                 _t="$i"         
1099         esac
1100         CTDB_MONITOR_MPDEVICES="${CTDB_MONITOR_MPDEVICES}${CTDB_MONITOR_MPDEVICES:+ }${_t}"
1101     done
1102
1103     export CTDB_MONITOR_MPDEVICES FAKE_MULTIPATH_FAILURES
1104     export FAKE_SLEEP_FORCE=0.1
1105 }
1106
1107 ######################################################################
1108
1109 # Result and test functions
1110
1111 # Set some globals and print the summary.
1112 define_test ()
1113 {
1114     desc="$1"
1115
1116     _f=$(basename "$0" ".sh")
1117
1118     # Remaining format should be NN.service.event.NNN or NN.service.NNN:
1119     _num="${_f##*.}"
1120     _f="${_f%.*}"
1121
1122     case "$_f" in
1123         [0-9][0-9].*.*)
1124             script="${_f%.*}"
1125             event="${_f##*.}"
1126             script_dir="${CTDB_BASE}/events.d"
1127             ;;
1128         [0-9][0-9].*)
1129             script="$_f"
1130             unset event
1131             script_dir="${CTDB_BASE}/events.d"
1132             ;;
1133         *.*)
1134             script="${_f%.*}"
1135             event="${_f##*.}"
1136             script_dir="${CTDB_BASE}"
1137             ;;
1138         *)
1139             script="${_f%.*}"
1140             unset event
1141             script_dir="${CTDB_BASE}"
1142     esac
1143
1144     [ -r "${script_dir}/${script}" ] || \
1145         die "Internal error - unable to find script \"${script_dir}/${script}\""
1146
1147     printf "%-17s %-10s %-4s - %s\n\n" "$script" "$event" "$_num" "$desc"
1148 }
1149
1150 # Run an eventscript once.  The test passes if the return code and
1151 # output match those required.
1152
1153 # Any args are passed to the eventscript.
1154
1155 simple_test ()
1156 {
1157     [ -n "$event" ] || die 'simple_test: $event not set'
1158
1159     args="$@"
1160
1161     test_header ()
1162     {
1163         echo "Running script \"$script $event${args:+ }$args\""
1164     }
1165
1166     extra_header ()
1167     {
1168         cat <<EOF
1169
1170 ##################################################
1171 CTDB_BASE="$CTDB_BASE"
1172 CTDB_SYS_ETCDIR="$CTDB_SYS_ETCDIR"
1173 ctdb client is "$(which ctdb)"
1174 ip command is "$(which ip)"
1175 EOF
1176     }
1177
1178     script_test "${script_dir}/${script}" "$event" "$@"
1179
1180     reset_test_header
1181     reset_extra_header
1182 }
1183
1184 simple_test_event ()
1185 {
1186     # If something has previously failed then don't continue.
1187     : ${_passed:=true}
1188     $_passed || return 1
1189
1190     event="$1" ; shift
1191     echo "=================================================="
1192     simple_test "$@"
1193 }
1194
1195 simple_test_command ()
1196 {
1197     unit_test "$@"
1198 }
1199
1200 # Run an NFS eventscript iteratively.
1201 #
1202 # - 1st argument is the number of iterations.
1203 #
1204 # - 2nd argument is the NFS/RPC service being tested
1205 #
1206 #   rpcinfo (or $service_check_cmd) is used on each iteration to test
1207 #   the availability of the service
1208 #
1209 #   If this is not set or null then no RPC service is checked and the
1210 #   required output is not reset on each iteration.  This is useful in
1211 #   baseline tests to confirm that the eventscript and test
1212 #   infrastructure is working correctly.
1213 #
1214 # - Subsequent arguments come in pairs: an iteration number and
1215 #   something to eval before that iteration.  Each time an iteration
1216 #   number is matched the associated argument is given to eval after
1217 #   the default setup is done.  The iteration numbers need to be given
1218 #   in ascending order.
1219 #
1220 #   These arguments can allow a service to be started or stopped
1221 #   before a particular iteration.
1222 #
1223 nfs_iterate_test ()
1224 {
1225     _repeats="$1"
1226     _rpc_service="$2"
1227     if [ -n "$2" ] ; then
1228         shift 2
1229     else
1230         shift
1231     fi
1232
1233     echo "Running $_repeats iterations of \"$script $event\" $args"
1234
1235     _iterate_failcount=0
1236     for _iteration in $(seq 1 $_repeats) ; do
1237         # This is not a numerical comparison because $1 will often not
1238         # be set.
1239         if [ "$_iteration" = "$1" ] ; then
1240             debug "##################################################"
1241             eval "$2"
1242             debug "##################################################"
1243             shift 2
1244         fi
1245         if [ -n "$_rpc_service" ] ; then
1246             _ok=false
1247             if [ -n "$service_check_cmd" ] ; then
1248                 if eval "$service_check_cmd" ; then
1249                     _ok=true
1250                 fi
1251             else
1252                 if rpcinfo -T tcp localhost "$_rpc_service" >/dev/null 2>&1 ; then
1253                     _ok=true
1254                 fi
1255             fi
1256
1257             if $_ok ; then
1258                 _iterate_failcount=0
1259             else
1260                 _iterate_failcount=$(($_iterate_failcount + 1))
1261             fi
1262             rpc_set_service_failure_response "$_rpc_service" $_iterate_failcount
1263         fi
1264         _out=$(simple_test 2>&1)
1265         _ret=$?
1266         if "$TEST_VERBOSE" || [ $_ret -ne 0 ] ; then
1267             echo "##################################################"
1268             echo "Iteration ${_iteration}:"
1269             echo "$_out"
1270         fi
1271         if [ $_ret -ne 0 ] ; then
1272             exit $_ret
1273         fi
1274     done
1275 }