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