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