ctdb-scripts: Rename variable CTDB_ETCDIR to CTDB_SYS_ETCDIR
[obnox/samba/samba-obnox.git] / ctdb / config / functions
1 # Hey Emacs, this is a -*- shell-script -*- !!!
2
3 # utility functions for ctdb event scripts
4
5 if [ -z "$CTDB_BASE" ] ; then
6     echo 'CTDB_BASE unset in CTDB functions file'
7     exit 1
8 fi
9
10 CTDB_VARDIR="/usr/local/var/lib/ctdb"
11
12 # Only (and always) override these variables in test code
13
14 if [ -z "$CTDB_SCRIPT_VARDIR" ] ; then
15     CTDB_SCRIPT_VARDIR="/usr/local/var/lib/ctdb/state"
16 fi
17
18 if [ -z "$CTDB_SYS_ETCDIR" ] ; then
19     CTDB_SYS_ETCDIR="/etc"
20 fi
21
22 #######################################
23 # pull in a system config file, if any
24 _loadconfig() {
25
26     if [ -z "$1" ] ; then
27         foo="${service_config:-${service_name}}"
28         if [ -n "$foo" ] ; then
29             loadconfig "$foo"
30             return
31         fi
32     fi
33
34     if [ "$1" != "ctdb" ] ; then
35         loadconfig "ctdb"
36     fi
37
38     if [ -z "$1" ] ; then
39         return
40     fi
41
42     if [ -f $CTDB_SYS_ETCDIR/sysconfig/$1 ]; then
43         . $CTDB_SYS_ETCDIR/sysconfig/$1
44     elif [ -f $CTDB_SYS_ETCDIR/default/$1 ]; then
45         . $CTDB_SYS_ETCDIR/default/$1
46     elif [ -f $CTDB_BASE/sysconfig/$1 ]; then
47         . $CTDB_BASE/sysconfig/$1
48     fi
49
50     if [ "$1" = "ctdb" ] ; then
51         _config="${CTDB_BASE}/ctdbd.conf"
52         if [ -r "$_config" ] ; then
53             . "$_config"
54         fi
55     fi
56 }
57
58 loadconfig () {
59     _loadconfig "$@"
60 }
61
62 ##############################################################
63
64 # CTDB_SCRIPT_DEBUGLEVEL can be overwritten by setting it in a
65 # configuration file.
66 debug ()
67 {
68     if [ ${CTDB_SCRIPT_DEBUGLEVEL:-2} -ge 4 ] ; then
69         # If there are arguments then echo them.  Otherwise expect to
70         # use stdin, which allows us to pass lots of debug using a
71         # here document.
72         if [ -n "$1" ] ; then
73             echo "DEBUG: $*"
74         else
75             sed -e 's@^@DEBUG: @'
76         fi
77     else
78         if [ -z "$1" ] ; then
79             cat >/dev/null
80         fi
81     fi
82 }
83
84 die ()
85 {
86     _msg="$1"
87     _rc="${2:-1}"
88
89     echo "$_msg"
90     exit $_rc
91 }
92
93 # Log given message or stdin to either syslog or a CTDB log file
94 # $1 is the tag passed to logger if syslog is in use.
95 script_log ()
96 {
97     _tag="$1" ; shift
98
99     case "$CTDB_LOGGING" in
100         file:*|"")
101             if [ -n "$CTDB_LOGGING" ] ; then
102                 _file="${CTDB_LOGGING#file:}"
103             else
104                 _file="/var/log/log.ctdb"
105             fi
106             {
107                 if [ -n "$*" ] ; then
108                     echo "$*"
109                 else
110                     cat
111                 fi
112             } >>"$_file"
113             ;;
114         *)
115             # Handle all syslog:* variants here too.  There's no tool to do
116             # the lossy things, so just use logger.
117             logger -t "ctdbd: ${_tag}" $*
118             ;;
119     esac
120 }
121
122 # When things are run in the background in an eventscript then logging
123 # output might get lost.  This is the "solution".  :-)
124 background_with_logging ()
125 {
126     (
127         "$@" 2>&1 </dev/null |
128         script_log "${script_name}&"
129     )&
130
131     return 0
132 }
133
134 ##############################################################
135 # check number of args for different events
136 ctdb_check_args ()
137 {
138     case "$1" in
139         takeip|releaseip)
140             if [ $# != 4 ]; then
141                 echo "ERROR: must supply interface, IP and maskbits"
142                 exit 1
143             fi
144             ;;
145         updateip)
146             if [ $# != 5 ]; then
147                 echo "ERROR: must supply old interface, new interface, IP and maskbits"
148                 exit 1
149             fi
150             ;;
151     esac
152 }
153
154 ##############################################################
155 # determine on what type of system (init style) we are running
156 detect_init_style()
157 {
158     # only do detection if not already set:
159     [ -z "$CTDB_INIT_STYLE" ] || return
160
161     if [ -x /sbin/startproc ]; then
162         CTDB_INIT_STYLE="suse"
163     elif [ -x /sbin/start-stop-daemon ]; then
164         CTDB_INIT_STYLE="debian"
165     else
166         CTDB_INIT_STYLE="redhat"
167     fi
168 }
169
170 ######################################################
171 # simulate /sbin/service on platforms that don't have it
172 # _service() makes it easier to hook the service() function for
173 # testing.
174 _service ()
175 {
176   _service_name="$1"
177   _op="$2"
178
179   # do nothing, when no service was specified
180   [ -z "$_service_name" ] && return
181
182   if [ -x /sbin/service ]; then
183       $_nice /sbin/service "$_service_name" "$_op"
184   elif [ -x /usr/sbin/service ]; then
185       $_nice /usr/sbin/service "$_service_name" "$_op"
186   elif [ -x $CTDB_SYS_ETCDIR/init.d/$_service_name ]; then
187       $_nice $CTDB_SYS_ETCDIR/init.d/$_service_name "$_op"
188   elif [ -x $CTDB_SYS_ETCDIR/rc.d/init.d/$_service_name ]; then
189       $_nice $CTDB_SYS_ETCDIR/rc.d/init.d/$_service_name "$_op"
190   fi
191 }
192
193 service()
194 {
195     _nice=""
196     _service "$@"
197 }
198
199 ######################################################
200 # simulate /sbin/service (niced) on platforms that don't have it
201 nice_service()
202 {
203     _nice="nice"
204     _service "$@"
205 }
206
207 ######################################################
208 # Cached retrieval of PNN from local node.  This never changes so why
209 # open a client connection to the server each time this is needed?
210 # This sets $pnn - this avoid an unnecessary subprocess.
211 ctdb_get_pnn ()
212 {
213     _pnn_file="${CTDB_SCRIPT_VARDIR}/my-pnn"
214     if [ ! -f "$_pnn_file" ] ; then
215         ctdb pnn | sed -e 's@.*:@@' >"$_pnn_file"
216     fi
217
218     read pnn <"$_pnn_file"
219 }
220
221 ######################################################
222 # wrapper around /proc/ settings to allow them to be hooked
223 # for testing
224 # 1st arg is relative path under /proc/, 2nd arg is value to set
225 set_proc ()
226 {
227     echo "$2" >"/proc/$1"
228 }
229
230 set_proc_maybe ()
231 {
232     if [ -w "/proc/$1" ] ; then
233         set_proc "$1" "$2"
234     fi
235 }
236
237 ######################################################
238 # wrapper around getting file contents from /proc/ to allow
239 # this to be hooked for testing
240 # 1st arg is relative path under /proc/
241 get_proc ()
242 {
243     cat "/proc/$1"
244 }
245
246 ######################################################
247 # Print up to $_max kernel stack traces for processes named $_program
248 program_stack_traces ()
249 {
250     _prog="$1"
251     _max="${2:-1}"
252
253     _count=1
254     for _pid in $(pidof "$_prog") ; do
255         [ $_count -le $_max ] || break
256
257         # Do this first to avoid racing with process exit
258         _stack=$(get_proc "${_pid}/stack" 2>/dev/null)
259         if [ -n "$_stack" ] ; then
260             echo "Stack trace for ${_prog}[${_pid}]:"
261             echo "$_stack"
262             _count=$(($_count + 1))
263         fi
264     done
265 }
266
267 ######################################################
268 # Ensure $service_name is set
269 assert_service_name ()
270 {
271     [ -n "$service_name" ] || die "INTERNAL ERROR: \$service_name not set"
272 }
273
274 ######################################################
275 # check a set of directories is available
276 # return 1 on a missing directory
277 # directories are read from stdin
278 ######################################################
279 ctdb_check_directories_probe()
280 {
281     while IFS="" read d ; do
282         case "$d" in
283             *%*)
284                 continue
285                 ;;
286             *)
287                 [ -d "${d}/." ] || return 1
288         esac
289     done
290 }
291
292 ######################################################
293 # check a set of directories is available
294 # directories are read from stdin
295 ######################################################
296 ctdb_check_directories()
297 {
298     ctdb_check_directories_probe || {
299         echo "ERROR: $service_name directory \"$d\" not available"
300         exit 1
301     }
302 }
303
304 ######################################################
305 # check a set of tcp ports
306 # usage: ctdb_check_tcp_ports <ports...>
307 ######################################################
308
309 # This flag file is created when a service is initially started.  It
310 # is deleted the first time TCP port checks for that service succeed.
311 # Until then ctdb_check_tcp_ports() prints a more subtle "error"
312 # message if a port check fails.
313 _ctdb_check_tcp_common ()
314 {
315     assert_service_name
316     _d="${CTDB_SCRIPT_VARDIR}/failcount"
317     _ctdb_service_started_file="${_d}/${service_name}.started"
318 }
319
320 ctdb_check_tcp_init ()
321 {
322     _ctdb_check_tcp_common
323     mkdir -p "${_ctdb_service_started_file%/*}" # dirname
324     touch "$_ctdb_service_started_file"
325 }
326
327 # Check whether something is listening on all of the given TCP ports
328 # using the "ctdb checktcpport" command.
329 ctdb_check_tcp_ports()
330 {
331     if [ -z "$1" ] ; then
332         echo "INTERNAL ERROR: ctdb_check_tcp_ports - no ports specified"
333         exit 1
334     fi
335
336     for _p ; do  # process each function argument (port)
337         _cmd="ctdb checktcpport $_p"
338         _out=$($_cmd 2>&1)
339         _ret=$?
340         case "$_ret" in
341             0)
342                 _ctdb_check_tcp_common
343                 if [ ! -f "$_ctdb_service_started_file" ] ; then
344                     echo "ERROR: $service_name tcp port $_p is not responding"
345                     debug "\"ctdb checktcpport $_p\" was able to bind to port"
346                 else
347                     echo "INFO: $service_name tcp port $_p is not responding"
348                 fi
349
350                 return 1
351                 ;;
352             98)
353                 # Couldn't bind, something already listening, next port...
354                 continue
355                 ;;
356             *)
357                 echo "ERROR: unexpected error running \"ctdb checktcpport\""
358                 debug <<EOF
359 ctdb checktcpport (exited with $_ret) with output:
360 $_out"
361 EOF
362                 return $_ret
363         esac
364     done
365
366     # All ports listening
367     _ctdb_check_tcp_common
368     rm -f "$_ctdb_service_started_file"
369     return 0
370 }
371
372 ######################################################
373 # check a unix socket
374 # usage: ctdb_check_unix_socket SERVICE_NAME <socket_path>
375 ######################################################
376 ctdb_check_unix_socket() {
377     socket_path="$1"
378     [ -z "$socket_path" ] && return
379
380     if ! netstat --unix -a -n | grep -q "^unix.*LISTEN.*${socket_path}$"; then
381         echo "ERROR: $service_name socket $socket_path not found"
382         return 1
383     fi
384 }
385
386 ######################################################
387 # check a command returns zero status
388 # usage: ctdb_check_command <command>
389 ######################################################
390 ctdb_check_command ()
391 {
392     _out=$("$@" 2>&1) || {
393         echo "ERROR: $* returned error"
394         echo "$_out" | debug
395         exit 1
396     }
397 }
398
399 ################################################
400 # kill off any TCP connections with the given IP
401 ################################################
402 kill_tcp_connections ()
403 {
404     _ip="$1"
405
406     _oneway=false
407     if [ "$2" = "oneway" ] ; then
408         _oneway=true
409     fi
410
411     get_tcp_connections_for_ip "$_ip" | {
412         _killcount=0
413         _connections=""
414         _nl="
415 "
416         while read _dst _src; do
417             _destport="${_dst##*:}"
418             __oneway=$_oneway
419             case $_destport in
420                 # we only do one-way killtcp for CIFS
421                 139|445) __oneway=true ;;
422             esac
423
424             echo "Killing TCP connection $_src $_dst"
425             _connections="${_connections}${_nl}${_src} ${_dst}"
426             if ! $__oneway ; then
427                 _connections="${_connections}${_nl}${_dst} ${_src}"
428             fi
429
430             _killcount=$(($_killcount + 1))
431         done
432
433         if [ $_killcount -eq 0 ] ; then
434             return
435         fi
436
437         echo "$_connections" | ctdb killtcp || {
438             echo "Failed to send killtcp control"
439             return
440         }
441
442         _count=0
443         while : ; do
444             _remaining=$(get_tcp_connections_for_ip $_ip | wc -l)
445
446             if [ $_remaining -eq 0 ] ; then
447                 echo "Killed $_killcount TCP connections to released IP $_ip"
448                 return
449             fi
450
451             _count=$(($_count + 1))
452             if [ $_count -gt 3 ] ; then
453                 echo "Timed out killing tcp connections for IP $_ip ($_remaining remaining)"
454                 return
455             fi
456
457             echo "Waiting for $_remaining connections to be killed for IP $_ip"
458             sleep 1
459         done
460     }
461 }
462
463 ##################################################################
464 # kill off the local end for any TCP connections with the given IP
465 ##################################################################
466 kill_tcp_connections_local_only ()
467 {
468     kill_tcp_connections "$1" "oneway"
469 }
470
471 ##################################################################
472 # tickle any TCP connections with the given IP
473 ##################################################################
474 tickle_tcp_connections ()
475 {
476     _ip="$1"
477
478     get_tcp_connections_for_ip "$_ip" |
479     {
480         _failed=false
481
482         while read dest src; do
483             echo "Tickle TCP connection $src $dest"
484             ctdb tickle $src $dest >/dev/null 2>&1 || _failed=true
485             echo "Tickle TCP connection $dest $src"
486             ctdb tickle $dest $src >/dev/null 2>&1 || _failed=true
487         done
488
489         if $_failed ; then
490             echo "Failed to send tickle control"
491         fi
492     }
493 }
494
495 get_tcp_connections_for_ip ()
496 {
497     _ip="$1"
498
499     netstat -tn | awk -v ip=$_ip \
500         'index($1, "tcp") == 1 && \
501          (index($4, ip ":") == 1 || index($4, "::ffff:" ip ":") == 1) \
502          && $6 == "ESTABLISHED" \
503          {print $4" "$5}'
504 }
505
506 ########################################################
507
508 add_ip_to_iface ()
509 {
510     _iface=$1
511     _ip=$2
512     _maskbits=$3
513
514     # Ensure interface is up
515     ip link set "$_iface" up || \
516         die "Failed to bringup interface $_iface"
517
518     # Only need to define broadcast for IPv4
519     case "$ip" in
520         *:*) _bcast=""      ;;
521         *)   _bcast="brd +" ;;
522     esac
523
524     ip addr add "$_ip/$_maskbits" $_bcast dev "$_iface" || {
525         echo "Failed to add $_ip/$_maskbits on dev $_iface"
526         return 1
527     }
528
529     # Wait 5 seconds for IPv6 addresses to stop being tentative...
530     if [ -z "$_bcast" ] ; then
531         for _x in $(seq 1 10) ; do
532             ip addr show to "${_ip}/128" | grep -q "tentative" || break
533             sleep 0.5
534         done
535
536         # If the address was a duplicate then it won't be on the
537         # interface so flag an error.
538         _t=$(ip addr show to "${_ip}/128")
539         case "$_t" in
540             "")
541                 echo "Failed to add $_ip/$_maskbits on dev $_iface"
542                 return 1
543                 ;;
544             *tentative*|*dadfailed*)
545                 echo "Failed to add $_ip/$_maskbits on dev $_iface"
546                 ip addr del "$_ip/$_maskbits" dev "$_iface"
547                 return 1
548                 ;;
549         esac
550     fi
551 }
552
553 delete_ip_from_iface()
554 {
555     _iface=$1
556     _ip=$2
557     _maskbits=$3
558
559     # This could be set globally for all interfaces but it is probably
560     # better to avoid surprises, so limit it the interfaces where CTDB
561     # has public IP addresses.  There isn't anywhere else convenient
562     # to do this so just set it each time.  This is much cheaper than
563     # remembering and re-adding secondaries.
564     set_proc "sys/net/ipv4/conf/${_iface}/promote_secondaries" 1
565
566     ip addr del "$_ip/$_maskbits" dev "$_iface" || {
567         echo "Failed to del $_ip on dev $_iface"
568         return 1
569     }
570 }
571
572 # If the given IP is hosted then print 2 items: maskbits and iface
573 ip_maskbits_iface ()
574 {
575     _addr="$1"
576
577     case "$_addr" in
578         *:*) _family="inet6" ; _bits=128 ;;
579         *)   _family="inet"  ; _bits=32  ;;
580     esac
581
582     ip addr show to "${_addr}/${_bits}" 2>/dev/null | \
583         awk -v family="${_family}" \
584             'NR == 1 { iface = $2; sub(":$", "", iface) ; \
585                        sub("@.*", "", iface) } \
586              $1 ~ /inet/ { mask = $2; sub(".*/", "", mask); \
587                            print mask, iface, family }'
588 }
589
590 drop_ip ()
591 {
592     _addr="${1%/*}"  # Remove optional maskbits
593
594     set -- $(ip_maskbits_iface $_addr)
595     if [ -n "$1" ] ; then
596         _maskbits="$1"
597         _iface="$2"
598         echo "Removing public address $_addr/$_maskbits from device $_iface"
599         delete_ip_from_iface $_iface $_addr $_maskbits >/dev/null 2>&1
600     fi
601 }
602
603 drop_all_public_ips ()
604 {
605     while read _ip _x ; do
606         drop_ip "$_ip"
607     done <"${CTDB_PUBLIC_ADDRESSES:-/dev/null}"
608 }
609
610 flush_route_cache ()
611 {
612     set_proc_maybe sys/net/ipv4/route/flush 1
613     set_proc_maybe sys/net/ipv6/route/flush 1
614 }
615
616 ########################################################
617 # Simple counters
618 _ctdb_counter_common () {
619     _service_name="${1:-${service_name:-${script_name}}}"
620     _counter_file="${CTDB_SCRIPT_VARDIR}/failcount/${_service_name}"
621     mkdir -p "${_counter_file%/*}" # dirname
622 }
623 ctdb_counter_init () {
624     _ctdb_counter_common "$1"
625
626     >"$_counter_file"
627 }
628 ctdb_counter_incr () {
629     _ctdb_counter_common "$1"
630
631     # unary counting!
632     echo -n 1 >> "$_counter_file"
633 }
634 ctdb_counter_get () {
635     _ctdb_counter_common "$1"
636     # unary counting!
637     stat -c "%s" "$_counter_file" 2>/dev/null || echo 0
638 }
639 ctdb_check_counter () {
640     _msg="${1:-error}"  # "error"  - anything else is silent on fail
641     _op="${2:--ge}"  # an integer operator supported by test
642     _limit="${3:-${service_fail_limit}}"
643     shift 3
644
645     _size=$(ctdb_counter_get "$1")
646
647     _hit=false
648     if [ "$_op" != "%" ] ; then
649         if [ $_size $_op $_limit ] ; then
650             _hit=true
651         fi
652     else
653         if [ $(($_size $_op $_limit)) -eq 0 ] ; then
654             _hit=true
655         fi
656     fi
657     if $_hit ; then
658         if [ "$_msg" = "error" ] ; then
659             echo "ERROR: $_size consecutive failures for $_service_name, marking node unhealthy"
660             exit 1              
661         else
662             return 1
663         fi
664     fi
665 }
666
667 ########################################################
668
669 ctdb_setup_service_state_dir ()
670 {
671     service_state_dir="${CTDB_SCRIPT_VARDIR}/service_state/${1:-${service_name}}"
672     mkdir -p "$service_state_dir" || {
673         echo "Error creating state dir \"$service_state_dir\""
674         exit 1
675     }
676 }
677
678 ########################################################
679 # Managed status history, for auto-start/stop
680
681 _ctdb_managed_common ()
682 {
683     _ctdb_managed_file="${CTDB_SCRIPT_VARDIR}/managed_history/${service_name}"
684 }
685
686 ctdb_service_managed ()
687 {
688     _ctdb_managed_common
689     mkdir -p "${_ctdb_managed_file%/*}" # dirname
690     touch "$_ctdb_managed_file"
691 }
692
693 ctdb_service_unmanaged ()
694 {
695     _ctdb_managed_common
696     rm -f "$_ctdb_managed_file"
697 }
698
699 is_ctdb_previously_managed_service ()
700 {
701     _ctdb_managed_common
702     [ -f "$_ctdb_managed_file" ]
703 }
704
705 ##################################################################
706 # Reconfigure a service on demand
707
708 _ctdb_service_reconfigure_common ()
709 {
710     _d="${CTDB_SCRIPT_VARDIR}/service_status/${service_name}"
711     mkdir -p "$_d"
712     _ctdb_service_reconfigure_flag="$_d/reconfigure"
713 }
714
715 ctdb_service_needs_reconfigure ()
716 {
717     _ctdb_service_reconfigure_common
718     [ -e "$_ctdb_service_reconfigure_flag" ]
719 }
720
721 ctdb_service_set_reconfigure ()
722 {
723     _ctdb_service_reconfigure_common
724     >"$_ctdb_service_reconfigure_flag"
725 }
726
727 ctdb_service_unset_reconfigure ()
728 {
729     _ctdb_service_reconfigure_common
730     rm -f "$_ctdb_service_reconfigure_flag"
731 }
732
733 ctdb_service_reconfigure ()
734 {
735     echo "Reconfiguring service \"${service_name}\"..."
736     ctdb_service_unset_reconfigure
737     service_reconfigure || return $?
738     ctdb_counter_init
739 }
740
741 # Default service_reconfigure() function does nothing.
742 service_reconfigure ()
743 {
744     :
745 }
746
747 ctdb_reconfigure_take_lock ()
748 {
749     _ctdb_service_reconfigure_common
750     _lock="${_d}/reconfigure_lock"
751     mkdir -p "${_lock%/*}" # dirname
752     touch "$_lock"
753
754     (
755         flock 0
756         # This is overkill but will work if we need to extend this to
757         # allow certain events to run multiple times in parallel
758         # (e.g. takeip) and write multiple PIDs to the file.
759         read _locker_event 
760         if [ -n "$_locker_event" ] ; then
761             while read _pid ; do
762                 if [ -n "$_pid" -a "$_pid" != $$ ] && \
763                     kill -0 "$_pid" 2>/dev/null ; then
764                     exit 1
765                 fi
766             done
767         fi
768
769         printf "%s\n%s\n" "$event_name" $$ >"$_lock"
770         exit 0
771     ) <"$_lock"
772 }
773
774 ctdb_reconfigure_release_lock ()
775 {
776     _ctdb_service_reconfigure_common
777     _lock="${_d}/reconfigure_lock"
778
779     rm -f "$_lock"
780 }
781
782 ctdb_replay_monitor_status ()
783 {
784     echo "Replaying previous status for this script due to reconfigure..."
785     # Leading separator ('|') is missing in some versions...
786     _out=$(ctdb scriptstatus -X | grep -E "^\|?monitor\|${script_name}\|")
787     # Output looks like this:
788     # |monitor|60.nfs|1|ERROR|1314764004.030861|1314764004.035514|foo bar|
789     # This is the cheapest way of getting fields in the middle.
790     set -- $(IFS="|" ; echo $_out)
791     _code="$3"
792     _status="$4"
793     # The error output field can include colons so we'll try to
794     # preserve them.  The weak checking at the beginning tries to make
795     # this work for both broken (no leading '|') and fixed output.
796     _out="${_out%|}"
797     _err_out="${_out#*monitor|${script_name}|*|*|*|*|}"
798     case "$_status" in
799         OK) : ;;  # Do nothing special.
800         TIMEDOUT)
801             # Recast this as an error, since we can't exit with the
802             # correct negative number.
803             _code=1
804             _err_out="[Replay of TIMEDOUT scriptstatus - note incorrect return code.] ${_err_out}"
805             ;;
806         DISABLED)
807             # Recast this as an OK, since we can't exit with the
808             # correct negative number.
809             _code=0
810             _err_out="[Replay of DISABLED scriptstatus - note incorrect return code.] ${_err_out}"
811             ;;
812         *) : ;;  # Must be ERROR, do nothing special.
813     esac
814     if [ -n "$_err_out" ] ; then
815         echo "$_err_out"
816     fi
817     exit $_code
818 }
819
820 ctdb_service_check_reconfigure ()
821 {
822     assert_service_name
823
824     # We only care about some events in this function.  For others we
825     # return now.
826     case "$event_name" in
827         monitor|ipreallocated|reconfigure) : ;;
828         *) return 0 ;;
829     esac
830
831     if ctdb_reconfigure_take_lock ; then
832         # No events covered by this function are running, so proceed
833         # with gay abandon.
834         case "$event_name" in
835             reconfigure)
836                 (ctdb_service_reconfigure)
837                 exit $?
838                 ;;
839             ipreallocated)
840                 if ctdb_service_needs_reconfigure ; then
841                     ctdb_service_reconfigure
842                 fi
843                 ;;
844         esac
845
846         ctdb_reconfigure_release_lock
847     else
848         # Somebody else is running an event we don't want to collide
849         # with.  We proceed with caution.
850         case "$event_name" in
851             reconfigure)
852                 # Tell whoever called us to retry.
853                 exit 2
854                 ;;
855             ipreallocated)
856                 # Defer any scheduled reconfigure and just run the
857                 # rest of the ipreallocated event, as per the
858                 # eventscript.  There's an assumption here that the
859                 # event doesn't depend on any scheduled reconfigure.
860                 # This is true in the current code.
861                 return 0
862                 ;;
863             monitor)
864                 # There is most likely a reconfigure in progress so
865                 # the service is possibly unstable.  As above, we
866                 # defer any scheduled reconfigured.  We also replay
867                 # the previous monitor status since that's the best
868                 # information we have.
869                 ctdb_replay_monitor_status
870                 ;;
871         esac
872     fi
873 }
874
875 ##################################################################
876 # Does CTDB manage this service? - and associated auto-start/stop
877
878 ctdb_compat_managed_service ()
879 {
880     if [ "$1" = "yes" -a "$2" = "$service_name" ] ; then
881         CTDB_MANAGED_SERVICES="$CTDB_MANAGED_SERVICES $2"
882     fi
883 }
884
885 is_ctdb_managed_service ()
886 {
887     assert_service_name
888
889     # $t is used just for readability and to allow better accurate
890     # matching via leading/trailing spaces
891     t=" $CTDB_MANAGED_SERVICES "
892
893     # Return 0 if "<space>$service_name<space>" appears in $t
894     if [ "${t#* ${service_name} }" != "${t}" ] ; then
895         return 0
896     fi
897
898     # If above didn't match then update $CTDB_MANAGED_SERVICES for
899     # backward compatibility and try again.
900     ctdb_compat_managed_service "$CTDB_MANAGES_VSFTPD"   "vsftpd"
901     ctdb_compat_managed_service "$CTDB_MANAGES_SAMBA"    "samba"
902     ctdb_compat_managed_service "$CTDB_MANAGES_WINBIND"  "winbind"
903     ctdb_compat_managed_service "$CTDB_MANAGES_HTTPD"    "apache2"
904     ctdb_compat_managed_service "$CTDB_MANAGES_HTTPD"    "httpd"
905     ctdb_compat_managed_service "$CTDB_MANAGES_ISCSI"    "iscsi"
906     ctdb_compat_managed_service "$CTDB_MANAGES_CLAMD"    "clamd"
907     ctdb_compat_managed_service "$CTDB_MANAGES_NFS"      "nfs"
908
909     t=" $CTDB_MANAGED_SERVICES "
910
911     # Return 0 if "<space>$service_name<space>" appears in $t
912     [ "${t#* ${service_name} }" != "${t}" ]
913 }
914
915 ctdb_start_stop_service ()
916 {
917     assert_service_name
918
919     # Allow service-start/service-stop pseudo-events to start/stop
920     # services when we're not auto-starting/stopping and we're not
921     # monitoring.
922     case "$event_name" in
923         service-start)
924             if is_ctdb_managed_service ; then
925                 die 'service-start event not permitted when service is managed'
926             fi
927             if [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] ; then
928                 die 'service-start event not permitted with $CTDB_SERVICE_AUTOSTARTSTOP = yes'
929             fi
930             ctdb_service_start
931             exit $?
932             ;;
933         service-stop)
934             if is_ctdb_managed_service ; then
935                 die 'service-stop event not permitted when service is managed'
936             fi
937             if [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] ; then
938                 die 'service-stop event not permitted with $CTDB_SERVICE_AUTOSTARTSTOP = yes'
939             fi
940             ctdb_service_stop
941             exit $?
942             ;;
943     esac
944
945     # Do nothing unless configured to...
946     [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] || return 0
947
948     [ "$event_name" = "monitor" ] || return 0
949
950     if is_ctdb_managed_service ; then
951         if ! is_ctdb_previously_managed_service ; then
952             echo "Starting service \"$service_name\" - now managed"
953             background_with_logging ctdb_service_start
954             exit $?
955         fi
956     else
957         if is_ctdb_previously_managed_service ; then
958             echo "Stopping service \"$service_name\" - no longer managed"
959             background_with_logging ctdb_service_stop
960             exit $?
961         fi
962     fi
963 }
964
965 ctdb_service_start ()
966 {
967     # The service is marked managed if we've ever tried to start it.
968     ctdb_service_managed
969
970     service_start || return $?
971
972     ctdb_counter_init
973     ctdb_check_tcp_init
974 }
975
976 ctdb_service_stop ()
977 {
978     ctdb_service_unmanaged
979     service_stop
980 }
981
982 # Default service_start() and service_stop() functions.
983  
984 # These may be overridden in an eventscript.
985 service_start ()
986 {
987     service "$service_name" start
988 }
989
990 service_stop ()
991 {
992     service "$service_name" stop
993 }
994
995 ##################################################################
996
997 ctdb_standard_event_handler ()
998 {
999     :
1000 }
1001
1002 iptables_wrapper ()
1003 {
1004     _family="$1" ; shift
1005     if [ "$_family" = "inet6" ] ; then
1006         _iptables_cmd="ip6tables"
1007     else
1008         _iptables_cmd="iptables"
1009     fi
1010
1011     # iptables doesn't like being re-entered, so flock-wrap it.
1012     flock -w 30 "${CTDB_SCRIPT_VARDIR}/iptables.flock" "$_iptables_cmd" "$@"
1013 }
1014
1015 # AIX (and perhaps others?) doesn't have mktemp
1016 if ! type mktemp >/dev/null 2>&1 ; then
1017     mktemp ()
1018     {
1019         _dir=false
1020         if [ "$1" = "-d" ] ; then
1021             _dir=true
1022             shift
1023         fi
1024         _d="${TMPDIR:-/tmp}"
1025         _hex10=$(dd if=/dev/urandom count=20 2>/dev/null | \
1026             md5sum | \
1027             sed -e 's@\(..........\).*@\1@')
1028         _t="${_d}/tmp.${_hex10}"
1029         (
1030             umask 077
1031             if $_dir ; then
1032                 mkdir "$_t"
1033             else
1034                 >"$_t"
1035             fi
1036         )
1037         echo "$_t"
1038     }
1039 fi
1040
1041 ########################################################
1042 # tickle handling
1043 ########################################################
1044
1045 update_tickles ()
1046 {
1047         _port="$1"
1048
1049         tickledir="${CTDB_SCRIPT_VARDIR}/tickles"
1050         mkdir -p "$tickledir"
1051
1052         ctdb_get_pnn
1053
1054         # What public IPs do I hold?
1055         _ips=$(ctdb -X ip | awk -F'|' -v pnn=$pnn '$3 == pnn {print $2}')
1056
1057         # IPs as a regexp choice
1058         _ipschoice="($(echo $_ips | sed -e 's/ /|/g' -e 's/\./\\\\./g'))"
1059
1060         # Record connections to our public IPs in a temporary file
1061         _my_connections="${tickledir}/${_port}.connections"
1062         rm -f "$_my_connections"
1063         netstat -tn |
1064         awk -v destpat="^${_ipschoice}:${_port}\$" \
1065           '$1 == "tcp" && $6 == "ESTABLISHED" && $4 ~ destpat {print $5, $4}' |
1066         sort >"$_my_connections"
1067
1068         # Record our current tickles in a temporary file
1069         _my_tickles="${tickledir}/${_port}.tickles"
1070         rm -f "$_my_tickles"
1071         for _i in $_ips ; do
1072                 ctdb -X gettickles $_i $_port |
1073                 awk -F'|' 'NR > 1 { printf "%s:%s %s:%s\n", $2, $3, $4, $5 }'
1074         done |
1075         sort >"$_my_tickles"
1076
1077         # Add tickles for connections that we haven't already got tickles for
1078         comm -23 "$_my_connections" "$_my_tickles" |
1079         while read _src _dst ; do
1080                 ctdb addtickle $_src $_dst
1081         done
1082
1083         # Remove tickles for connections that are no longer there
1084         comm -13 "$_my_connections" "$_my_tickles" |
1085         while read _src _dst ; do
1086                 ctdb deltickle $_src $_dst
1087         done
1088
1089         rm -f "$_my_connections" "$_my_tickles" 
1090 }
1091
1092 ########################################################
1093 # load a site local config file
1094 ########################################################
1095
1096 [ -n "$CTDB_RC_LOCAL" -a -x "$CTDB_RC_LOCAL" ] && {
1097         . "$CTDB_RC_LOCAL"
1098 }
1099
1100 [ -x $CTDB_BASE/rc.local ] && {
1101         . $CTDB_BASE/rc.local
1102 }
1103
1104 [ -d $CTDB_BASE/rc.local.d ] && {
1105         for i in $CTDB_BASE/rc.local.d/* ; do
1106                 [ -x "$i" ] && . "$i"
1107         done
1108 }
1109
1110 script_name="${0##*/}"       # basename
1111 service_fail_limit=1
1112 event_name="$1"