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