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