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