9d5dff71533d71ea3df6d9013cd935499e23c45e
[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 # Check the routes against those that are expected.  $1 is the number
367 # of assigned IPs to use (<num>, all), defaulting to 1.  If $2 is
368 # "default" then expect default routes to have been added.
369 check_routes ()
370 {
371     _num_ips="${1:-1}"
372     _should_add_default="$2"
373
374     _policy_rules=""
375     _policy_routes=""
376
377     ctdb_get_my_public_addresses |
378     if [ "$_num_ips" = "all" ] ; then
379         cat
380     else
381         { head -n "$_num_ips" ; cat >/dev/null ; }
382     fi | {
383         while read _dev _ip _bits ; do
384             _net=$(ipv4_host_addr_to_net "$_ip" "$_bits")
385             _gw="${_net%.*}.254" # a dumb, calculated default
386
387             _policy_rules="${_policy_rules}
388 ${CTDB_PER_IP_ROUTING_RULE_PREF}:       from $_ip lookup ctdb.$_ip "
389             _policy_routes="${_policy_routes}
390 # ip route show table ctdb.$_ip
391 $_net dev $_dev  scope link "
392
393             if [ "$_should_add_default" = "default" ] ; then
394                 _policy_routes="${_policy_routes}
395 default via $_gw dev $_dev "
396             fi
397         done
398
399         ok <<EOF
400 # ip rule show
401 0:      from all lookup local ${_policy_rules}
402 32766:  from all lookup main 
403 32767:  from all lookup default ${_policy_routes}
404 EOF
405
406         simple_test_command dump_routes
407     } || test_fail
408 }
409
410 ######################################################################
411
412 setup_ctdb_lvs ()
413 {
414         lvs_state_dir="${EVENTSCRIPTS_TESTS_VAR_DIR}/lvs"
415         mkdir -p "$lvs_state_dir"
416
417         export FAKE_LVS_STATE_DIR="${lvs_state_dir}/state"
418         mkdir "$FAKE_LVS_STATE_DIR"
419
420         lvs_header=$(ipvsadm -l -n)
421
422         export CTDB_LVS_PUBLIC_IP="$1"
423         export CTDB_LVS_PUBLIC_IFACE="$2"
424
425         [ -n "$CTDB_LVS_PUBLIC_IP" ] || return 0
426         [ -n "$CTDB_LVS_PUBLIC_IFACE" ] || return 0
427
428         export CTDB_LVS_NODES=$(mktemp --tmpdir="$lvs_state_dir")
429         export FAKE_CTDB_LVS_MASTER=""
430
431         # Read from stdin
432         _pnn=0
433         while read _ip _opts ; do
434                 case "$_opts" in
435                 master)
436                         FAKE_CTDB_LVS_MASTER="$_pnn"
437                         echo "$_ip"
438                         ;;
439                 slave-only)
440                         printf "%s\tslave-only\n" "$_ip"
441                         ;;
442                 *)
443                         echo "$_ip"
444                         ;;
445                 esac
446                 _pnn=$(($_pnn + 1))
447         done >"$CTDB_LVS_NODES"
448 }
449
450 check_ipvsadm ()
451 {
452         if [ "$1" = "NULL" ] ; then
453                 required_result 0 <<EOF
454 $lvs_header
455 EOF
456         else
457                 required_result 0 <<EOF
458 $lvs_header
459 $(cat)
460 EOF
461         fi
462
463         simple_test_command ipvsadm -l -n
464 }
465
466 check_lvs_ip ()
467 {
468         _scope="$1"
469
470         if [ "$_scope" = "NULL" ] ; then
471                 required_result 0 <<EOF
472 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
473     link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
474 EOF
475         else
476                 required_result 0 <<EOF
477 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
478     link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
479     inet ${CTDB_LVS_PUBLIC_IP}/32 scope ${_scope} lo
480        valid_lft forever preferred_lft forever
481 EOF
482         fi
483
484         simple_test_command ip addr show dev lo
485 }
486
487 ######################################################################
488
489 ctdb_catdb_format_pairs ()
490 {
491     _count=0
492
493     while read _k _v ; do
494         _kn=$(echo -n "$_k" | wc -c)
495         _vn=$(echo -n "$_v" | wc -c)
496         cat <<EOF
497 key(${_kn}) = "${_k}"
498 dmaster: 0
499 rsn: 1
500 data(${_vn}) = "${_v}"
501
502 EOF
503         _count=$(($_count + 1))
504     done
505
506     echo "Dumped ${_count} records"
507 }
508
509 check_ctdb_tdb_statd_state ()
510 {
511     ctdb_get_my_public_addresses |
512     while read _x _sip _x ; do
513         for _cip ; do
514             echo "statd-state@${_sip}@${_cip}" "$FAKE_DATE_OUTPUT"
515         done
516     done |
517     ctdb_catdb_format_pairs | {
518         ok
519         simple_test_command ctdb catdb ctdb.tdb
520     } || exit $?
521 }
522
523 check_statd_callout_smnotify ()
524 {
525     _state_even=$(( $(date '+%s') / 2 * 2))
526     _state_odd=$(($_state_even + 1))
527
528     nfs_load_config
529
530     ctdb_get_my_public_addresses |
531     while read _x _sip _x ; do
532         for _cip ; do
533             cat <<EOF
534 SM_NOTIFY: ${_sip} -> ${_cip}, MON_NAME=${_sip}, STATE=${_state_even}
535 SM_NOTIFY: ${_sip} -> ${_cip}, MON_NAME=${NFS_HOSTNAME}, STATE=${_state_even}
536 SM_NOTIFY: ${_sip} -> ${_cip}, MON_NAME=${_sip}, STATE=${_state_odd}
537 SM_NOTIFY: ${_sip} -> ${_cip}, MON_NAME=${NFS_HOSTNAME}, STATE=${_state_odd}
538 EOF
539         done
540     done | {
541         ok
542         simple_test_event "notify"
543     } || exit $?
544 }
545
546 ######################################################################
547
548 # Samba/winbind fakery
549
550 setup_samba ()
551 {
552     setup_ctdb
553
554     service_name="samba"
555
556     if [ "$1" != "down" ] ; then
557
558         debug "Marking Samba services as up, listening and managed by CTDB"
559
560         # All possible service names for all known distros.
561         for i in "smb" "nmb" "samba" "smbd" "nmbd" ; do
562             service "$i" force-started
563         done
564
565         export CTDB_SAMBA_SKIP_SHARE_CHECK="no"
566         export CTDB_MANAGES_SAMBA="yes"
567
568         export FAKE_TCP_LISTEN="0.0.0.0:445 0.0.0.0:139"
569         export FAKE_WBINFO_FAIL="no"
570
571         # Some things in 50.samba are backgrounded and waited for.  If
572         # we don't sleep at all then timeouts can happen.  This avoids
573         # that...  :-)
574         export FAKE_SLEEP_FORCE=0.1
575     else
576         debug "Marking Samba services as down, not listening and not managed by CTDB"
577
578         # All possible service names for all known distros.
579         for i in "smb" "nmb" "samba" "smbd" "nmbd" ; do
580             service "$i" force-stopped
581         done
582
583         export CTDB_SAMBA_SKIP_SHARE_CHECK="no"
584         export CTDB_MANAGES_SAMBA=""
585
586         export FAKE_TCP_LISTEN=""
587         export FAKE_WBINFO_FAIL="yes"
588     fi
589 }
590
591 samba_setup_fake_threads ()
592 {
593         export FAKE_SMBD_THREAD_PIDS="$*"
594
595         _nl="
596 "
597         _out=""
598         _count=0
599         for _pid ; do
600                 [ "$_count" -lt 5 ] || break
601                 _t=$(program_stack_trace "smbd" $_pid)
602                 _out="${_out:+${_out}${_nl}}${_t}"
603                 _count=$((_count + 1))
604         done
605         SAMBA_STACK_TRACES="$_out"
606 }
607
608 setup_winbind ()
609 {
610     setup_ctdb
611
612     service_name="winbind"
613
614     if [ "$1" != "down" ] ; then
615
616         debug "Marking Winbind service as up and managed by CTDB"
617
618         service "winbind" force-started
619
620         export CTDB_MANAGES_WINBIND="yes"
621
622         export FAKE_WBINFO_FAIL="no"
623
624     else
625         debug "Marking Winbind service as down and not managed by CTDB"
626
627         service "winbind" force-stopped
628
629         export CTDB_MANAGES_WINBIND=""
630
631         export FAKE_WBINFO_FAIL="yes"
632     fi
633 }
634
635 wbinfo_down ()
636 {
637     debug "Making wbinfo commands fail"
638     FAKE_WBINFO_FAIL="yes"
639 }
640
641 ######################################################################
642
643 # NFS fakery
644
645 setup_nfs ()
646 {
647     setup_ctdb
648
649     service_name="nfs"
650
651     export FAKE_RPCINFO_SERVICES=""
652
653     export CTDB_NFS_SKIP_SHARE_CHECK="no"
654
655     export RPCNFSDCOUNT
656
657     # This doesn't even need to exist
658     export CTDB_NFS_EXPORTS_FILE="$EVENTSCRIPTS_TESTS_VAR_DIR/etc-exports"
659
660     # Reset the failcounts for nfs services.
661     eventscript_call eval rm -f '$ctdb_fail_dir/nfs_*'
662
663     if [ "$1" != "down" ] ; then
664         debug "Setting up NFS environment: all RPC services up, NFS managed by CTDB"
665
666         service "nfs" force-started
667         service "nfslock" force-started
668
669         export CTDB_MANAGES_NFS="yes"
670
671         rpc_services_up \
672             "portmapper" "nfs" "mountd" "rquotad" "nlockmgr" "status"
673
674         nfs_setup_fake_threads "nfsd"
675         nfs_setup_fake_threads "rpc.foobar"  # Just set the variable to empty
676     else
677         debug "Setting up NFS environment: all RPC services down, NFS not managed by CTDB"
678
679         service "nfs" force-stopped
680         service "nfslock" force-stopped
681
682         export CTDB_MANAGES_NFS=""
683     fi
684
685     # This is really nasty.  However, when we test NFS we don't
686     # actually test statd-callout. If we leave it there then left
687     # over, backgrounded instances of statd-callout will do horrible
688     # things with the "ctdb ip" stub and cause the actual
689     # statd-callout tests that follow to fail.
690     rm "${CTDB_BASE}/statd-callout"
691 }
692
693 setup_nfs_ganesha ()
694 {
695     setup_nfs "$@"
696     export CTDB_NFS_CALLOUT="${CTDB_BASE}/nfs-ganesha-callout"
697     if [ "$1" != "down" ] ; then
698         export CTDB_MANAGES_NFS="yes"
699     fi
700
701     export CTDB_NFS_SKIP_SHARE_CHECK="yes"
702 }
703
704 rpc_services_down ()
705 {
706     for _i ; do
707         debug "Marking RPC service \"${_i}\" as unavailable"
708         FAKE_RPCINFO_SERVICES=$(echo "$FAKE_RPCINFO_SERVICES" | sed -r -e "s@[[:space:]]*${_i}:[0-9]+:[0-9]+@@g")
709     done
710 }
711
712 rpc_services_up ()
713 {
714     for _i ; do
715         debug "Marking RPC service \"${_i}\" as available"
716         case "$_i" in
717             portmapper) _t="2:4" ;;
718             nfs)        _t="2:3" ;;
719             mountd)     _t="1:3" ;;
720             rquotad)    _t="1:2" ;;
721             nlockmgr)   _t="3:4" ;;
722             status)     _t="1:1" ;;
723             *) die "Internal error - unsupported RPC service \"${_i}\"" ;;
724         esac
725
726         FAKE_RPCINFO_SERVICES="${FAKE_RPCINFO_SERVICES}${FAKE_RPCINFO_SERVICES:+ }${_i}:${_t}"
727     done
728 }
729
730
731 nfs_load_config ()
732 {
733     _etc="$CTDB_SYS_ETCDIR" # shortcut for readability
734     for _c in "$_etc/sysconfig/nfs" "$_etc/default/nfs" "$_etc/ctdb/sysconfig/nfs" ; do
735         if [ -r "$_c" ] ; then
736             . "$_c"
737             break
738         fi
739     done
740 }
741
742 nfs_setup_fake_threads ()
743 {
744     _prog="$1" ; shift
745
746     case "$_prog" in
747         nfsd)
748             export PROCFS_PATH=$(mktemp -d --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
749             _threads="${PROCFS_PATH}/fs/nfsd/threads"
750             mkdir -p $(dirname "$_threads")
751             echo $# >"$_threads"
752             export FAKE_NFSD_THREAD_PIDS="$*"
753             ;;
754         *)
755             export FAKE_RPC_THREAD_PIDS="$*"
756             ;;
757     esac
758 }
759
760 program_stack_trace ()
761 {
762         _prog="$1"
763         _pid="$2"
764
765         cat <<EOF
766 Stack trace for ${_prog}[${_pid}]:
767 [<ffffffff87654321>] fake_stack_trace_for_pid_${_pid}/stack+0x0/0xff
768 EOF
769 }
770
771 program_stack_traces ()
772 {
773     _prog="$1"
774     _max="${2:-1}"
775
776     _count=1
777     for _pid in ${FAKE_NFSD_THREAD_PIDS:-$FAKE_RPC_THREAD_PIDS} ; do
778         [ $_count -le $_max ] || break
779
780         program_stack_trace "$_prog" "$_pid"
781         _count=$(($_count + 1))
782     done
783 }
784
785 guess_output ()
786 {
787     case "$1" in
788         $CTDB_NFS_CALLOUT\ start\ nlockmgr)
789             echo "&Starting nfslock: OK"
790             ;;
791         $CTDB_NFS_CALLOUT\ start\ nfs)
792             cat <<EOF
793 &Starting nfslock: OK
794 &Starting nfs: OK
795 EOF
796             ;;
797         *)
798             : # Nothing
799     esac
800 }
801
802 # Set the required result for a particular RPC program having failed
803 # for a certain number of iterations.  This is probably still a work
804 # in progress.  Note that we could hook aggressively
805 # nfs_check_rpc_service() to try to implement this but we're better
806 # off testing nfs_check_rpc_service() using independent code...  even
807 # if it is incomplete and hacky.  So, if the 60.nfs eventscript
808 # changes and the tests start to fail then it may be due to this
809 # function being incomplete.
810 rpc_set_service_failure_response ()
811 {
812     _rpc_service="$1"
813     _numfails="${2:-1}" # default 1
814
815     # Default
816     ok_null
817     if [ $_numfails -eq 0 ] ; then
818         return
819     fi
820
821     nfs_load_config
822
823     # A handy newline.  :-)
824     _nl="
825 "
826
827     _dir="${CTDB_NFS_CHECKS_DIR:-${CTDB_BASE}/nfs-checks.d}"
828
829     _file=$(ls "$_dir"/[0-9][0-9]."${_rpc_service}.check")
830     [ -r "$_file" ] || die "RPC check file \"$_file\" does not exist or is not unique"
831
832     _out=$(mktemp --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
833     _rc_file=$(mktemp --tmpdir="$EVENTSCRIPTS_TESTS_VAR_DIR")
834
835     (
836         # Subshell to restrict scope variables...
837
838         # Defaults
839         family="tcp"
840         version=""
841         unhealthy_after=1
842         restart_every=0
843         service_stop_cmd=""
844         service_start_cmd=""
845         service_check_cmd=""
846         service_debug_cmd=""
847
848         # Don't bother syntax checking, eventscript does that...
849         . "$_file"
850
851         # Just use the first version, or use default.  This is dumb but
852         # handles all the cases that we care about now...
853         if [ -n "$version" ] ; then
854             _ver="${version%% *}"
855         else
856             case "$_rpc_service" in
857                 portmapper) _ver="" ;;
858                 *)          _ver=1  ;;
859             esac
860         fi
861         _rpc_check_out="\
862 $_rpc_service failed RPC check:
863 rpcinfo: RPC: Program not registered
864 program $_rpc_service${_ver:+ version }${_ver} is not available"
865
866         if [ $unhealthy_after -gt 0 -a $_numfails -ge $unhealthy_after ] ; then
867             _unhealthy=true
868             echo 1 >"$_rc_file"
869             echo "ERROR: ${_rpc_check_out}" >>"$_out"
870         else
871             _unhealthy=false
872             echo 0 >"$_rc_file"
873         fi
874
875         if [ $restart_every -gt 0 ] && \
876                    [ $(($_numfails % $restart_every)) -eq 0 ] ; then
877             if ! $_unhealthy ; then
878                 echo "WARNING: ${_rpc_check_out}" >>"$_out"
879             fi
880
881             echo "Trying to restart service \"${_rpc_service}\"..." >>"$_out"
882
883             if [ -n "$service_debug_cmd" ] ; then
884                 $service_debug_cmd 2>&1 >>"$_out"
885             fi
886
887             guess_output "$service_start_cmd" >>"$_out"
888         fi
889     )
890
891     read _rc <"$_rc_file"
892     required_result $_rc <"$_out"
893
894     rm -f "$_out" "$_rc_file"
895 }
896
897
898 # VSFTPD fakery
899
900 setup_vsftpd ()
901 {
902         debug "Setting up VSFTPD environment: service $1, not managed by CTDB"
903
904         _service_name="vsftpd"
905
906         if [ "$1" != "down" ] ; then
907                 service "$_service_name" start
908         else
909                 service "$_service_name" force-stopped
910         fi
911
912         export CTDB_MANAGES_VSFTPD=""
913 }
914
915 ######################################################################
916
917 # HTTPD fakery
918
919 setup_httpd ()
920 {
921         debug "Setting up HTTPD environment: service $1, not managed by CTDB"
922
923         if [ "$1" != "down" ] ; then
924                 for _service_name in "apache2" "httpd" ; do
925                         service "$_service_name" start
926                 done
927         else
928                 for _service_name in "apache2" "httpd" ; do
929                         service "$_service_name" force-stopped
930                 done
931         fi
932
933         export CTDB_MANAGES_HTTPD=""
934 }
935
936 ######################################################################
937
938 # Result and test functions
939
940 # Set some globals and print the summary.
941 define_test ()
942 {
943     desc="$1"
944
945     _f=$(basename "$0" ".sh")
946
947     # Remaining format should be NN.service.event.NNN or NN.service.NNN:
948     _num="${_f##*.}"
949     _f="${_f%.*}"
950
951     case "$_f" in
952         [0-9][0-9].*.*)
953             script="${_f%.*}"
954             event="${_f##*.}"
955             script_dir="${CTDB_BASE}/events.d"
956             ;;
957         [0-9][0-9].*)
958             script="$_f"
959             unset event
960             script_dir="${CTDB_BASE}/events.d"
961             ;;
962         *.*)
963             script="${_f%.*}"
964             event="${_f##*.}"
965             script_dir="${CTDB_BASE}"
966             ;;
967         *)
968             script="${_f%.*}"
969             unset event
970             script_dir="${CTDB_BASE}"
971     esac
972
973     [ -r "${script_dir}/${script}" ] || \
974         die "Internal error - unable to find script \"${script_dir}/${script}\""
975
976     printf "%-17s %-10s %-4s - %s\n\n" "$script" "$event" "$_num" "$desc"
977
978     _f="${TEST_SUBDIR}/scripts/${script}.sh"
979     if [ -r "$_f" ] ; then
980             . "$_f"
981     fi
982
983     ctdb_set_pnn 0
984 }
985
986 # Run an eventscript once.  The test passes if the return code and
987 # output match those required.
988
989 # Any args are passed to the eventscript.
990
991 simple_test ()
992 {
993     [ -n "$event" ] || die 'simple_test: $event not set'
994
995     args="$@"
996
997     test_header ()
998     {
999         echo "Running script \"$script $event${args:+ }$args\""
1000     }
1001
1002     extra_header ()
1003     {
1004         cat <<EOF
1005
1006 ##################################################
1007 CTDB_BASE="$CTDB_BASE"
1008 CTDB_SYS_ETCDIR="$CTDB_SYS_ETCDIR"
1009 ctdb client is "$(which ctdb)"
1010 ip command is "$(which ip)"
1011 EOF
1012     }
1013
1014     script_test "${script_dir}/${script}" "$event" "$@"
1015
1016     reset_test_header
1017     reset_extra_header
1018 }
1019
1020 simple_test_event ()
1021 {
1022     # If something has previously failed then don't continue.
1023     : ${_passed:=true}
1024     $_passed || return 1
1025
1026     event="$1" ; shift
1027     echo "=================================================="
1028     simple_test "$@"
1029 }
1030
1031 simple_test_command ()
1032 {
1033     unit_test "$@"
1034 }
1035
1036 # Run an NFS eventscript iteratively.
1037 #
1038 # - 1st argument is the number of iterations.
1039 #
1040 # - 2nd argument is the NFS/RPC service being tested
1041 #
1042 #   rpcinfo (or $service_check_cmd) is used on each iteration to test
1043 #   the availability of the service
1044 #
1045 #   If this is not set or null then no RPC service is checked and the
1046 #   required output is not reset on each iteration.  This is useful in
1047 #   baseline tests to confirm that the eventscript and test
1048 #   infrastructure is working correctly.
1049 #
1050 # - Subsequent arguments come in pairs: an iteration number and
1051 #   something to eval before that iteration.  Each time an iteration
1052 #   number is matched the associated argument is given to eval after
1053 #   the default setup is done.  The iteration numbers need to be given
1054 #   in ascending order.
1055 #
1056 #   These arguments can allow a service to be started or stopped
1057 #   before a particular iteration.
1058 #
1059 nfs_iterate_test ()
1060 {
1061     _repeats="$1"
1062     _rpc_service="$2"
1063     if [ -n "$2" ] ; then
1064         shift 2
1065     else
1066         shift
1067     fi
1068
1069     echo "Running $_repeats iterations of \"$script $event\" $args"
1070
1071     _iterate_failcount=0
1072     for _iteration in $(seq 1 $_repeats) ; do
1073         # This is not a numerical comparison because $1 will often not
1074         # be set.
1075         if [ "$_iteration" = "$1" ] ; then
1076             debug "##################################################"
1077             eval "$2"
1078             debug "##################################################"
1079             shift 2
1080         fi
1081         if [ -n "$_rpc_service" ] ; then
1082             _ok=false
1083             if [ -n "$service_check_cmd" ] ; then
1084                 if eval "$service_check_cmd" ; then
1085                     _ok=true
1086                 fi
1087             else
1088                 if rpcinfo -T tcp localhost "$_rpc_service" >/dev/null 2>&1 ; then
1089                     _ok=true
1090                 fi
1091             fi
1092
1093             if $_ok ; then
1094                 _iterate_failcount=0
1095             else
1096                 _iterate_failcount=$(($_iterate_failcount + 1))
1097             fi
1098             rpc_set_service_failure_response "$_rpc_service" $_iterate_failcount
1099         fi
1100         _out=$(simple_test 2>&1)
1101         _ret=$?
1102         if "$TEST_VERBOSE" || [ $_ret -ne 0 ] ; then
1103             echo "##################################################"
1104             echo "Iteration ${_iteration}:"
1105             echo "$_out"
1106         fi
1107         if [ $_ret -ne 0 ] ; then
1108             exit $_ret
1109         fi
1110     done
1111 }