ctdb-scripts: Add default filesystem usage warnings
[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     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_VARDIR="$EVENTSCRIPTS_TESTS_VAR_DIR/ctdb/${FAKE_CTDB_PNN}"
295     mkdir -p "$CTDB_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     # Reset the failcounts for nfs services.
809     eventscript_call eval rm -f '$ctdb_fail_dir/nfs_*'
810
811     if [ "$1" != "down" ] ; then
812         debug "Setting up NFS environment: all RPC services up, NFS managed by CTDB"
813
814         eventscript_call ctdb_service_managed
815         service "nfs" force-started
816         service "nfslock" force-started
817
818         export CTDB_MANAGED_SERVICES="foo nfs bar"
819
820         rpc_services_up \
821             "portmapper" "nfs" "mountd" "rquotad" "nlockmgr" "status"
822
823         nfs_setup_fake_threads "nfsd"
824         nfs_setup_fake_threads "rpc.foobar"  # Just set the variable to empty
825     else
826         debug "Setting up NFS environment: all RPC services down, NFS not managed by CTDB"
827
828         eventscript_call ctdb_service_unmanaged
829         service "nfs" force-stopped
830         service "nfslock" force-stopped
831
832         export CTDB_MANAGED_SERVICES="foo bar"
833         unset CTDB_MANAGES_NFS
834     fi
835
836     # This is really nasty.  However, when we test NFS we don't
837     # actually test statd-callout. If we leave it there then left
838     # over, backgrounded instances of statd-callout will do horrible
839     # things with the "ctdb ip" stub and cause the actual
840     # statd-callout tests that follow to fail.
841     rm "${CTDB_BASE}/statd-callout"
842 }
843
844 setup_nfs_ganesha ()
845 {
846     setup_nfs "$@"
847     export CTDB_NFS_CALLOUT="${CTDB_BASE}/nfs-ganesha-callout"
848     if [ "$1" != "down" ] ; then
849         export CTDB_MANAGES_NFS="yes"
850     fi
851
852     export CTDB_NFS_SKIP_SHARE_CHECK="yes"
853 }
854
855 rpc_services_down ()
856 {
857     for _i ; do
858         debug "Marking RPC service \"${_i}\" as unavailable"
859         FAKE_RPCINFO_SERVICES=$(echo "$FAKE_RPCINFO_SERVICES" | sed -r -e "s@[[:space:]]*${_i}:[0-9]+:[0-9]+@@g")
860     done
861 }
862
863 rpc_services_up ()
864 {
865     for _i ; do
866         debug "Marking RPC service \"${_i}\" as available"
867         case "$_i" in
868             portmapper) _t="2:4" ;;
869             nfs)        _t="2:3" ;;
870             mountd)     _t="1:3" ;;
871             rquotad)    _t="1:2" ;;
872             nlockmgr)   _t="3:4" ;;
873             status)     _t="1:1" ;;
874             *) die "Internal error - unsupported RPC service \"${_i}\"" ;;
875         esac
876
877         FAKE_RPCINFO_SERVICES="${FAKE_RPCINFO_SERVICES}${FAKE_RPCINFO_SERVICES:+ }${_i}:${_t}"
878     done
879 }
880
881
882 nfs_load_config ()
883 {
884     _etc="$CTDB_ETCDIR" # shortcut for readability
885     for _c in "$_etc/sysconfig/nfs" "$_etc/default/nfs" "$_etc/ctdb/sysconfig/nfs" ; do
886         if [ -r "$_c" ] ; then
887             . "$_c"
888             break
889         fi
890     done
891 }
892
893 nfs_setup_fake_threads ()
894 {
895     _prog="$1" ; shift
896
897     case "$_prog" in
898         nfsd)
899             export PROCFS_PATH=$(mktemp -d --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
900             _threads="${PROCFS_PATH}/fs/nfsd/threads"
901             mkdir -p $(dirname "$_threads")
902             echo $# >"$_threads"
903             export FAKE_NFSD_THREAD_PIDS="$*"
904             ;;
905         *)
906             export FAKE_RPC_THREAD_PIDS="$*"
907             ;;
908     esac
909 }
910
911 program_stack_traces ()
912 {
913     _prog="$1"
914     _max="${2:-1}"
915
916     _count=1
917     for _pid in ${FAKE_NFSD_THREAD_PIDS:-$FAKE_RPC_THREAD_PIDS} ; do
918         [ $_count -le $_max ] || break
919
920         cat <<EOF
921 Stack trace for ${_prog}[${_pid}]:
922 [<ffffffff87654321>] fake_stack_trace_for_pid_${_pid}/stack+0x0/0xff
923 EOF
924         _count=$(($_count + 1))
925     done
926 }
927
928 guess_output ()
929 {
930     case "$1" in
931         $CTDB_NFS_CALLOUT\ start\ nlockmgr)
932             echo "&Starting nfslock: OK"
933             ;;
934         $CTDB_NFS_CALLOUT\ start\ nfs)
935             cat <<EOF
936 &Starting nfslock: OK
937 &Starting nfs: OK
938 EOF
939             ;;
940         *)
941             : # Nothing
942     esac
943 }
944
945 # Set the required result for a particular RPC program having failed
946 # for a certain number of iterations.  This is probably still a work
947 # in progress.  Note that we could hook aggressively
948 # nfs_check_rpc_service() to try to implement this but we're better
949 # off testing nfs_check_rpc_service() using independent code...  even
950 # if it is incomplete and hacky.  So, if the 60.nfs eventscript
951 # changes and the tests start to fail then it may be due to this
952 # function being incomplete.
953 rpc_set_service_failure_response ()
954 {
955     _rpc_service="$1"
956     _numfails="${2:-1}" # default 1
957
958     # Default
959     ok_null
960     if [ $_numfails -eq 0 ] ; then
961         return
962     fi
963
964     nfs_load_config
965
966     # A handy newline.  :-)
967     _nl="
968 "
969
970     _dir="${CTDB_NFS_CHECKS_DIR:-${CTDB_BASE}/nfs-checks.d}"
971
972     _file=$(ls "$_dir"/[0-9][0-9]."${_rpc_service}.check")
973     [ -r "$_file" ] || die "RPC check file \"$_file\" does not exist or is not unique"
974
975     _out=$(mktemp --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
976     _rc_file=$(mktemp --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
977
978     (
979         # Subshell to restrict scope variables...
980
981         # Defaults
982         family="tcp"
983         version=""
984         unhealthy_after=1
985         restart_every=0
986         service_stop_cmd=""
987         service_start_cmd=""
988         service_check_cmd=""
989         service_debug_cmd=""
990
991         # Don't bother syntax checking, eventscript does that...
992         . "$_file"
993
994         # Just use the first version, or use default.  This is dumb but
995         # handles all the cases that we care about now...
996         if [ -n "$version" ] ; then
997             _ver="${version%% *}"
998         else
999             case "$_rpc_service" in
1000                 portmapper) _ver="" ;;
1001                 *)          _ver=1  ;;
1002             esac
1003         fi
1004         _rpc_check_out="\
1005 $_rpc_service failed RPC check:
1006 rpcinfo: RPC: Program not registered
1007 program $_rpc_service${_ver:+ version }${_ver} is not available"
1008
1009         if [ $unhealthy_after -gt 0 -a $_numfails -ge $unhealthy_after ] ; then
1010             _unhealthy=true
1011             echo 1 >"$_rc_file"
1012             echo "ERROR: ${_rpc_check_out}" >>"$_out"
1013         else
1014             _unhealthy=false
1015             echo 0 >"$_rc_file"
1016         fi
1017
1018         if [ $restart_every -gt 0 -a $(($_numfails % $restart_every)) -eq 0 ] ; then
1019             if ! $_unhealthy ; then
1020                 echo "WARNING: ${_rpc_check_out}" >>"$_out"
1021             fi
1022
1023             echo "Trying to restart service \"${_rpc_service}\"..." >>"$_out"
1024
1025             if [ -n "$service_debug_cmd" ] ; then
1026                 $service_debug_cmd 2>&1 >>"$_out"
1027             fi
1028
1029             guess_output "$service_start_cmd" >>"$_out"
1030         fi
1031     )
1032
1033     read _rc <"$_rc_file"
1034     required_result $_rc <"$_out"
1035
1036     rm -f "$_out" "$_rc_file"
1037 }
1038
1039 ######################################################################
1040
1041 # VSFTPD fakery
1042
1043 setup_vsftpd ()
1044 {
1045     service_name="vsftpd"
1046
1047     if [ "$1" != "down" ] ; then
1048         die "setup_vsftpd up not implemented!!!"
1049     else
1050         debug "Setting up VSFTPD environment: service down, not managed by CTDB"
1051
1052         eventscript_call ctdb_service_unmanaged
1053         service vsftpd force-stopped
1054
1055         export CTDB_MANAGED_SERVICES="foo"
1056         unset CTDB_MANAGES_VSFTPD
1057     fi
1058 }
1059
1060 ######################################################################
1061
1062 # HTTPD fakery
1063
1064 setup_httpd ()
1065 {
1066     if [ "$1" != "down" ] ; then
1067         die "setup_httpd up not implemented!!!"
1068     else
1069         debug "Setting up HTTPD environment: service down, not managed by CTDB"
1070
1071         for service_name in "apache2" "httpd" ; do
1072             eventscript_call ctdb_service_unmanaged
1073             service "$service_name" force-stopped
1074         done
1075
1076         export CTDB_MANAGED_SERVICES="foo"
1077         unset CTDB_MANAGES_HTTPD
1078     fi
1079 }
1080
1081 ######################################################################
1082
1083 # multipathd fakery
1084
1085 setup_multipathd ()
1086 {
1087     for i ; do
1088         case "$i" in
1089             \!*)
1090                 _t="${i#!}"
1091                 echo "Marking ${_t} as having no active paths"
1092                 FAKE_MULTIPATH_FAILURES="${FAKE_MULTIPATH_FAILURES}${FAKE_MULTIPATH+FAILURES:+ }${_t}"
1093                 ;;
1094             *)
1095                 _t="$i"         
1096         esac
1097         CTDB_MONITOR_MPDEVICES="${CTDB_MONITOR_MPDEVICES}${CTDB_MONITOR_MPDEVICES:+ }${_t}"
1098     done
1099
1100     export CTDB_MONITOR_MPDEVICES FAKE_MULTIPATH_FAILURES
1101     export FAKE_SLEEP_FORCE=0.1
1102 }
1103
1104 ######################################################################
1105
1106 # Result and test functions
1107
1108 # Set some globals and print the summary.
1109 define_test ()
1110 {
1111     desc="$1"
1112
1113     _f=$(basename "$0" ".sh")
1114
1115     # Remaining format should be NN.service.event.NNN or NN.service.NNN:
1116     _num="${_f##*.}"
1117     _f="${_f%.*}"
1118
1119     case "$_f" in
1120         [0-9][0-9].*.*)
1121             script="${_f%.*}"
1122             event="${_f##*.}"
1123             script_dir="${CTDB_BASE}/events.d"
1124             ;;
1125         [0-9][0-9].*)
1126             script="$_f"
1127             unset event
1128             script_dir="${CTDB_BASE}/events.d"
1129             ;;
1130         *.*)
1131             script="${_f%.*}"
1132             event="${_f##*.}"
1133             script_dir="${CTDB_BASE}"
1134             ;;
1135         *)
1136             script="${_f%.*}"
1137             unset event
1138             script_dir="${CTDB_BASE}"
1139     esac
1140
1141     [ -r "${script_dir}/${script}" ] || \
1142         die "Internal error - unable to find script \"${script_dir}/${script}\""
1143
1144     printf "%-17s %-10s %-4s - %s\n\n" "$script" "$event" "$_num" "$desc"
1145 }
1146
1147 # Run an eventscript once.  The test passes if the return code and
1148 # output match those required.
1149
1150 # Any args are passed to the eventscript.
1151
1152 simple_test ()
1153 {
1154     [ -n "$event" ] || die 'simple_test: $event not set'
1155
1156     args="$@"
1157
1158     test_header ()
1159     {
1160         echo "Running script \"$script $event${args:+ }$args\""
1161     }
1162
1163     extra_header ()
1164     {
1165         cat <<EOF
1166
1167 ##################################################
1168 CTDB_BASE="$CTDB_BASE"
1169 CTDB_ETCDIR="$CTDB_ETCDIR"
1170 ctdb client is "$(which ctdb)"
1171 ip command is "$(which ip)"
1172 EOF
1173     }
1174
1175     script_test "${script_dir}/${script}" "$event" "$@"
1176
1177     reset_test_header
1178     reset_extra_header
1179 }
1180
1181 simple_test_event ()
1182 {
1183     # If something has previously failed then don't continue.
1184     : ${_passed:=true}
1185     $_passed || return 1
1186
1187     event="$1" ; shift
1188     echo "=================================================="
1189     simple_test "$@"
1190 }
1191
1192 simple_test_command ()
1193 {
1194     unit_test "$@"
1195 }
1196
1197 # Run an NFS eventscript iteratively.
1198 #
1199 # - 1st argument is the number of iterations.
1200 #
1201 # - 2nd argument is the NFS/RPC service being tested
1202 #
1203 #   rpcinfo (or $service_check_cmd) is used on each iteration to test
1204 #   the availability of the service
1205 #
1206 #   If this is not set or null then no RPC service is checked and the
1207 #   required output is not reset on each iteration.  This is useful in
1208 #   baseline tests to confirm that the eventscript and test
1209 #   infrastructure is working correctly.
1210 #
1211 # - Subsequent arguments come in pairs: an iteration number and
1212 #   something to eval before that iteration.  Each time an iteration
1213 #   number is matched the associated argument is given to eval after
1214 #   the default setup is done.  The iteration numbers need to be given
1215 #   in ascending order.
1216 #
1217 #   These arguments can allow a service to be started or stopped
1218 #   before a particular iteration.
1219 #
1220 nfs_iterate_test ()
1221 {
1222     _repeats="$1"
1223     _rpc_service="$2"
1224     if [ -n "$2" ] ; then
1225         shift 2
1226     else
1227         shift
1228     fi
1229
1230     echo "Running $_repeats iterations of \"$script $event\" $args"
1231
1232     _iterate_failcount=0
1233     for _iteration in $(seq 1 $_repeats) ; do
1234         # This is not a numerical comparison because $1 will often not
1235         # be set.
1236         if [ "$_iteration" = "$1" ] ; then
1237             debug "##################################################"
1238             eval "$2"
1239             debug "##################################################"
1240             shift 2
1241         fi
1242         if [ -n "$_rpc_service" ] ; then
1243             _ok=false
1244             if [ -n "$service_check_cmd" ] ; then
1245                 if eval "$service_check_cmd" ; then
1246                     _ok=true
1247                 fi
1248             else
1249                 if rpcinfo -T tcp localhost "$_rpc_service" >/dev/null 2>&1 ; then
1250                     _ok=true
1251                 fi
1252             fi
1253
1254             if $_ok ; then
1255                 _iterate_failcount=0
1256             else
1257                 _iterate_failcount=$(($_iterate_failcount + 1))
1258             fi
1259             rpc_set_service_failure_response "$_rpc_service" $_iterate_failcount
1260         fi
1261         _out=$(simple_test 2>&1)
1262         _ret=$?
1263         if "$TEST_VERBOSE" || [ $_ret -ne 0 ] ; then
1264             echo "##################################################"
1265             echo "Iteration ${_iteration}:"
1266             echo "$_out"
1267         fi
1268         if [ $_ret -ne 0 ] ; then
1269             exit $_ret
1270         fi
1271     done
1272 }