messaging: Avoid a socket leak after fork
[Samba.git] / ctdb / config / functions
blob382632427a545122899a77f9f2cacb5c99d5e63a
1 # Hey Emacs, this is a -*- shell-script -*- !!!
3 # utility functions for ctdb event scripts
5 if [ -z "$CTDB_BASE" ] ; then
6     echo 'CTDB_BASE unset in CTDB functions file'
7     exit 1
8 fi
9 export CTDB_BASE
11 # CTDB_VARDIR is used elsewhere
12 # shellcheck disable=SC2034
13 CTDB_VARDIR="/usr/local/var/lib/ctdb"
14 ctdb_rundir="/usr/local/var/run/ctdb"
16 CTDB="${CTDB:-/usr/local/bin/ctdb}"
18 # Only (and always) override these variables in test code
20 if [ -z "$CTDB_SCRIPT_VARDIR" ] ; then
21     CTDB_SCRIPT_VARDIR="/usr/local/var/lib/ctdb/state"
24 if [ -z "$CTDB_SYS_ETCDIR" ] ; then
25     CTDB_SYS_ETCDIR="/etc"
28 if [ -z "$CTDB_HELPER_BINDIR" ] ; then
29     CTDB_HELPER_BINDIR="/usr/local/libexec/ctdb"
32 #######################################
33 # pull in a system config file, if any
35 rewrite_ctdb_options ()
37     case "$CTDB_DBDIR" in
38         tmpfs|tmpfs:*)
39             _opts_defaults="mode=700"
40             # Get any extra options specified after colon
41             if [ "$CTDB_DBDIR" = "tmpfs" ] ; then
42                 _opts=""
43             else
44                 _opts="${CTDB_DBDIR#tmpfs:}"
45             fi
46             # It is OK to repeat mount options - last value wins.
47             # CTDB_DBDIR_TMPFS_OPTIONS is used by ctdbd_wrapper
48             # shellcheck disable=SC2034
49             CTDB_DBDIR_TMPFS_OPTIONS="${_opts_defaults}${_opts:+,}${_opts}"
51             CTDB_DBDIR="${ctdb_rundir}/CTDB_DBDIR"
52             ;;
53         *)
54             # shellcheck disable=SC2034
55             CTDB_DBDIR_TMPFS_OPTIONS=""
56     esac
59 _loadconfig() {
61     if [ -z "$1" ] ; then
62         foo="${service_config:-${service_name}}"
63         if [ -n "$foo" ] ; then
64             loadconfig "$foo"
65             return
66         fi
67     fi
69     if [ "$1" != "ctdb" ] ; then
70         loadconfig "ctdb"
71     fi
73     if [ -z "$1" ] ; then
74         return
75     fi
77     if [ -f "${CTDB_SYS_ETCDIR}/sysconfig/$1" ]; then
78         . "${CTDB_SYS_ETCDIR}/sysconfig/$1"
79     elif [ -f "${CTDB_SYS_ETCDIR}/default/$1" ]; then
80         . "${CTDB_SYS_ETCDIR}/default/$1"
81     elif [ -f "${CTDB_BASE}/sysconfig/$1" ]; then
82         . "${CTDB_BASE}/sysconfig/$1"
83     fi
85     if [ "$1" = "ctdb" ] ; then
86         _config="${CTDBD_CONF:-${CTDB_BASE}/ctdbd.conf}"
87         if [ -r "$_config" ] ; then
88             . "$_config"
89         fi
90         rewrite_ctdb_options
91     fi
94 loadconfig () {
95     _loadconfig "$@"
98 ##############################################################
100 # CTDB_SCRIPT_DEBUGLEVEL can be overwritten by setting it in a
101 # configuration file.
102 debug ()
104     if [ "${CTDB_SCRIPT_DEBUGLEVEL:-NOTICE}" = "DEBUG" ] ; then
105         # If there are arguments then echo them.  Otherwise expect to
106         # use stdin, which allows us to pass lots of debug using a
107         # here document.
108         if [ -n "$1" ] ; then
109             echo "DEBUG: $*"
110         else
111             sed -e 's@^@DEBUG: @'
112         fi
113     else
114         if [ -z "$1" ] ; then
115             cat >/dev/null
116         fi
117     fi
120 die ()
122     _msg="$1"
123     _rc="${2:-1}"
125     echo "$_msg" >&2
126     exit "$_rc"
129 # Log given message or stdin to either syslog or a CTDB log file
130 # $1 is the tag passed to logger if syslog is in use.
131 script_log ()
133     _tag="$1" ; shift
135     case "$CTDB_LOGGING" in
136         file:*|"")
137             if [ -n "$CTDB_LOGGING" ] ; then
138                 _file="${CTDB_LOGGING#file:}"
139             else
140                 _file="/usr/local/var/log/log.ctdb"
141             fi
142             {
143                 if [ -n "$*" ] ; then
144                     echo "$*"
145                 else
146                     cat
147                 fi
148             } >>"$_file"
149             ;;
150         *)
151             # Handle all syslog:* variants here too.  There's no tool to do
152             # the lossy things, so just use logger.
153             logger -t "ctdbd: ${_tag}" "$@"
154             ;;
155     esac
158 # When things are run in the background in an eventscript then logging
159 # output might get lost.  This is the "solution".  :-)
160 background_with_logging ()
162     (
163         "$@" 2>&1 </dev/null |
164         script_log "${script_name}&"
165     )&
167     return 0
170 ##############################################################
171 # check number of args for different events
172 ctdb_check_args ()
174     case "$1" in
175         takeip|releaseip)
176             if [ $# != 4 ]; then
177                 echo "ERROR: must supply interface, IP and maskbits"
178                 exit 1
179             fi
180             ;;
181         updateip)
182             if [ $# != 5 ]; then
183                 echo "ERROR: must supply old interface, new interface, IP and maskbits"
184                 exit 1
185             fi
186             ;;
187     esac
190 ##############################################################
191 # determine on what type of system (init style) we are running
192 detect_init_style()
194     # only do detection if not already set:
195     [ -z "$CTDB_INIT_STYLE" ] || return
197     if [ -x /sbin/startproc ]; then
198         CTDB_INIT_STYLE="suse"
199     elif [ -x /sbin/start-stop-daemon ]; then
200         CTDB_INIT_STYLE="debian"
201     else
202         CTDB_INIT_STYLE="redhat"
203     fi
206 ######################################################
207 # simulate /sbin/service on platforms that don't have it
208 # _service() makes it easier to hook the service() function for
209 # testing.
210 _service ()
212   _service_name="$1"
213   _op="$2"
215   # do nothing, when no service was specified
216   [ -z "$_service_name" ] && return
218   if [ -x /sbin/service ]; then
219       $_nice /sbin/service "$_service_name" "$_op"
220   elif [ -x /usr/sbin/service ]; then
221       $_nice /usr/sbin/service "$_service_name" "$_op"
222   elif [ -x /bin/systemctl ]; then
223       $_nice /bin/systemctl "$_op" "$_service_name"
224   elif [ -x "${CTDB_SYS_ETCDIR}/init.d/${_service_name}" ]; then
225       $_nice "${CTDB_SYS_ETCDIR}/init.d/${_service_name}" "$_op"
226   elif [ -x "${CTDB_SYS_ETCDIR}/rc.d/init.d/${_service_name}" ]; then
227       $_nice "${CTDB_SYS_ETCDIR}/rc.d/init.d/${_service_name}" "$_op"
228   fi
231 service()
233     _nice=""
234     _service "$@"
237 ######################################################
238 # simulate /sbin/service (niced) on platforms that don't have it
239 nice_service()
241     _nice="nice"
242     _service "$@"
245 ######################################################
246 # Cached retrieval of PNN from local node.  This never changes so why
247 # open a client connection to the server each time this is needed?
248 ctdb_get_pnn ()
250     _pnn_file="${CTDB_SCRIPT_VARDIR}/my-pnn"
251     if [ ! -f "$_pnn_file" ] ; then
252         $CTDB pnn >"$_pnn_file"
253     fi
255     cat "$_pnn_file"
258 # Cached retrieval of private IP address from local node.  This never
259 # changes.
260 ctdb_get_ip_address ()
262     _ip_addr_file="${CTDB_SCRIPT_VARDIR}/my-ip-address"
263     if [ ! -f "$_ip_addr_file" ] ; then
264         $CTDB -X nodestatus |
265             awk -F '|' 'NR == 2 { print $3 }' >"$_ip_addr_file"
266     fi
268     # ip_address is used by caller
269     # shellcheck disable=SC2034
270     cat "$_ip_addr_file"
273 ######################################################
274 # wrapper around /proc/ settings to allow them to be hooked
275 # for testing
276 # 1st arg is relative path under /proc/, 2nd arg is value to set
277 set_proc ()
279     echo "$2" >"/proc/$1"
282 set_proc_maybe ()
284     if [ -w "/proc/$1" ] ; then
285         set_proc "$1" "$2"
286     fi
289 ######################################################
290 # wrapper around getting file contents from /proc/ to allow
291 # this to be hooked for testing
292 # 1st arg is relative path under /proc/
293 get_proc ()
295     cat "/proc/$1"
298 ######################################################
299 # Print up to $_max kernel stack traces for processes named $_program
300 program_stack_traces ()
302     _prog="$1"
303     _max="${2:-1}"
305     _count=1
306     for _pid in $(pidof "$_prog") ; do
307         [ "$_count" -le "$_max" ] || break
309         # Do this first to avoid racing with process exit
310         _stack=$(get_proc "${_pid}/stack" 2>/dev/null)
311         if [ -n "$_stack" ] ; then
312             echo "Stack trace for ${_prog}[${_pid}]:"
313             echo "$_stack"
314             _count=$((_count + 1))
315         fi
316     done
319 ######################################################
320 # Ensure $service_name is set
321 assert_service_name ()
323     [ -n "$service_name" ] || die "INTERNAL ERROR: \$service_name not set"
326 ######################################################
327 # check a set of directories is available
328 # return 1 on a missing directory
329 # directories are read from stdin
330 ######################################################
331 ctdb_check_directories_probe()
333     while IFS="" read d ; do
334         case "$d" in
335             *%*)
336                 continue
337                 ;;
338             *)
339                 [ -d "${d}/." ] || return 1
340         esac
341     done
344 ######################################################
345 # check a set of directories is available
346 # directories are read from stdin
347 ######################################################
348 ctdb_check_directories()
350     ctdb_check_directories_probe || {
351         echo "ERROR: $service_name directory \"$d\" not available"
352         exit 1
353     }
356 ######################################################
357 # check a set of tcp ports
358 # usage: ctdb_check_tcp_ports <ports...>
359 ######################################################
361 # This flag file is created when a service is initially started.  It
362 # is deleted the first time TCP port checks for that service succeed.
363 # Until then ctdb_check_tcp_ports() prints a more subtle "error"
364 # message if a port check fails.
365 _ctdb_check_tcp_common ()
367     assert_service_name
368     _d="${CTDB_SCRIPT_VARDIR}/failcount"
369     _ctdb_service_started_file="${_d}/${service_name}.started"
372 ctdb_check_tcp_init ()
374     _ctdb_check_tcp_common
375     mkdir -p "${_ctdb_service_started_file%/*}" # dirname
376     touch "$_ctdb_service_started_file"
379 # Check whether something is listening on all of the given TCP ports
380 # using the "ctdb checktcpport" command.
381 ctdb_check_tcp_ports()
383     if [ -z "$1" ] ; then
384         echo "INTERNAL ERROR: ctdb_check_tcp_ports - no ports specified"
385         exit 1
386     fi
388     for _p ; do  # process each function argument (port)
389         _cmd="$CTDB checktcpport $_p"
390         _out=$($_cmd 2>&1)
391         _ret=$?
392         case "$_ret" in
393             0)
394                 _ctdb_check_tcp_common
395                 if [ ! -f "$_ctdb_service_started_file" ] ; then
396                     echo "ERROR: $service_name tcp port $_p is not responding"
397                     debug "\"ctdb checktcpport $_p\" was able to bind to port"
398                 else
399                     echo "INFO: $service_name tcp port $_p is not responding"
400                 fi
402                 return 1
403                 ;;
404             98)
405                 # Couldn't bind, something already listening, next port...
406                 continue
407                 ;;
408             *)
409                 echo "ERROR: unexpected error running \"ctdb checktcpport\""
410                 debug <<EOF
411 $CTDB checktcpport (exited with $_ret) with output:
412 $_out"
414                 return $_ret
415         esac
416     done
418     # All ports listening
419     _ctdb_check_tcp_common
420     rm -f "$_ctdb_service_started_file"
421     return 0
424 ######################################################
425 # check a unix socket
426 # usage: ctdb_check_unix_socket SERVICE_NAME <socket_path>
427 ######################################################
428 ctdb_check_unix_socket() {
429     socket_path="$1"
430     [ -z "$socket_path" ] && return
432     if ! netstat --unix -a -n | grep -q "^unix.*LISTEN.*${socket_path}$"; then
433         echo "ERROR: $service_name socket $socket_path not found"
434         return 1
435     fi
438 ######################################################
439 # check a command returns zero status
440 # usage: ctdb_check_command <command>
441 ######################################################
442 ctdb_check_command ()
444     _out=$("$@" 2>&1) || {
445         echo "ERROR: $* returned error"
446         echo "$_out" | debug
447         exit 1
448     }
451 ################################################
452 # kill off any TCP connections with the given IP
453 ################################################
454 kill_tcp_connections ()
456     _iface="$1"
457     _ip="$2"
459     _oneway=false
460     if [ "$3" = "oneway" ] ; then
461         _oneway=true
462     fi
464     get_tcp_connections_for_ip "$_ip" | {
465         _killcount=0
466         _connections=""
467         _nl="
469         while read _dst _src; do
470             _destport="${_dst##*:}"
471             __oneway=$_oneway
472             case $_destport in
473                 # we only do one-way killtcp for CIFS
474                 139|445) __oneway=true ;;
475             esac
477             echo "Killing TCP connection $_src $_dst"
478             _connections="${_connections}${_nl}${_src} ${_dst}"
479             if ! $__oneway ; then
480                 _connections="${_connections}${_nl}${_dst} ${_src}"
481             fi
483             _killcount=$((_killcount + 1))
484         done
486         if [ $_killcount -eq 0 ] ; then
487             return
488         fi
490         echo "$_connections" | \
491                 "${CTDB_HELPER_BINDIR}/ctdb_killtcp" "$_iface" || {
492                 echo "Failed to kill TCP connections"
493                 return
494         }
496         _remaining=$(get_tcp_connections_for_ip "$_ip" | wc -l)
498         if [ "$_remaining" -eq 0 ] ; then
499                 echo "Killed $_killcount TCP connections to released IP $_ip"
500                 return
501         fi
503         _t="${_remaining}/${_killcount}"
504         echo "Failed to kill TCP connections for IP $_ip (${_t} remaining)"
505     }
508 ##################################################################
509 # kill off the local end for any TCP connections with the given IP
510 ##################################################################
511 kill_tcp_connections_local_only ()
513     kill_tcp_connections "$@" "oneway"
516 ##################################################################
517 # tickle any TCP connections with the given IP
518 ##################################################################
519 tickle_tcp_connections ()
521     _ip="$1"
523     # Get connections, both directions
524     _conns=$(get_tcp_connections_for_ip "$_ip" | \
525                     awk '{ print $1, $2 ; print $2, $1 }')
527     echo "$_conns" | awk '{ print "Tickle TCP connection", $1, $2 }'
528     echo "$_conns" | ctdb tickle
531 get_tcp_connections_for_ip ()
533     _ip="$1"
535     ss -tn state established "src [$_ip]" | awk 'NR > 1 {print $3, $4}'
538 ########################################################
540 add_ip_to_iface ()
542     _iface=$1
543     _ip=$2
544     _maskbits=$3
546     # Ensure interface is up
547     ip link set "$_iface" up || \
548         die "Failed to bringup interface $_iface"
550     # Only need to define broadcast for IPv4
551     case "$_ip" in
552         *:*) _bcast=""      ;;
553         *)   _bcast="brd +" ;;
554     esac
556     # Intentionally unquoted multi-word value here
557     # shellcheck disable=SC2086
558     ip addr add "$_ip/$_maskbits" $_bcast dev "$_iface" || {
559         echo "Failed to add $_ip/$_maskbits on dev $_iface"
560         return 1
561     }
563     # Wait 5 seconds for IPv6 addresses to stop being tentative...
564     if [ -z "$_bcast" ] ; then
565         for _x in $(seq 1 10) ; do
566             ip addr show to "${_ip}/128" | grep -q "tentative" || break
567             sleep 0.5
568         done
570         # If the address was a duplicate then it won't be on the
571         # interface so flag an error.
572         _t=$(ip addr show to "${_ip}/128")
573         case "$_t" in
574             "")
575                 echo "Failed to add $_ip/$_maskbits on dev $_iface"
576                 return 1
577                 ;;
578             *tentative*|*dadfailed*)
579                 echo "Failed to add $_ip/$_maskbits on dev $_iface"
580                 ip addr del "$_ip/$_maskbits" dev "$_iface"
581                 return 1
582                 ;;
583         esac
584     fi
587 delete_ip_from_iface()
589     _iface=$1
590     _ip=$2
591     _maskbits=$3
593     # This could be set globally for all interfaces but it is probably
594     # better to avoid surprises, so limit it the interfaces where CTDB
595     # has public IP addresses.  There isn't anywhere else convenient
596     # to do this so just set it each time.  This is much cheaper than
597     # remembering and re-adding secondaries.
598     set_proc "sys/net/ipv4/conf/${_iface}/promote_secondaries" 1
600     ip addr del "$_ip/$_maskbits" dev "$_iface" || {
601         echo "Failed to del $_ip on dev $_iface"
602         return 1
603     }
606 # If the given IP is hosted then print 2 items: maskbits and iface
607 ip_maskbits_iface ()
609     _addr="$1"
611     case "$_addr" in
612         *:*) _bits=128 ;;
613         *)   _bits=32  ;;
614     esac
615     ip addr show to "${_addr}/${_bits}" 2>/dev/null | \
616         awk 'NR == 1 { iface = $2; sub(":$", "", iface) ;
617                        sub("@.*", "", iface) }
618              $1 ~ /inet/ { mask = $2; sub(".*/", "", mask);
619                            print mask, iface }'
622 drop_ip ()
624     _addr="${1%/*}"  # Remove optional maskbits
626     # Intentional word splitting here
627     # shellcheck disable=SC2046
628     set -- $(ip_maskbits_iface "$_addr")
629     if [ -n "$1" ] ; then
630         _maskbits="$1"
631         _iface="$2"
632         echo "Removing public address $_addr/$_maskbits from device $_iface"
633         delete_ip_from_iface "$_iface" "$_addr" "$_maskbits" >/dev/null 2>&1
634     fi
637 drop_all_public_ips ()
639         # _x is intentionally ignored
640         # shellcheck disable=SC2034
641         while read _ip _x ; do
642                 drop_ip "$_ip"
643         done <"${CTDB_PUBLIC_ADDRESSES:-/dev/null}"
646 flush_route_cache ()
648     set_proc_maybe sys/net/ipv4/route/flush 1
649     set_proc_maybe sys/net/ipv6/route/flush 1
652 ########################################################
653 # Interface monitoring
655 # If the interface is a virtual one (e.g. VLAN) then get the
656 # underlying interface
657 interface_get_real ()
659     # Output of "ip link show <iface>"
660     _iface_info="$1"
662     # Extract the full interface description to see if it is a VLAN
663     _t=$(echo "$_iface_info" |
664                 awk 'NR == 1 { iface = $2; sub(":$", "", iface) ;
665                                print iface }')
666     case "$_t" in
667         *@*)
668             # VLAN: use the underlying interface, after the '@'
669             echo "${_t##*@}"
670             ;;
671         *)
672             # Not a regular VLAN.  For backward compatibility, assume
673             # there is some other sort of VLAN that doesn't have the
674             # '@' in the output and only use what is before a '.'.  If
675             # there is no '.' then this will be the whole interface
676             # name.
677             echo "${_t%%.*}"
678     esac
681 # Check whether an interface is operational
682 interface_monitor ()
684     _iface="$1"
686     _iface_info=$(ip link show "$_iface" 2>&1) || {
687         echo "ERROR: Monitored interface ${_iface} does not exist"
688         return 1
689     }
692     # If the interface is a virtual one (e.g. VLAN) then get the
693     # underlying interface.
694     _realiface=$(interface_get_real "$_iface_info")
696     if _bi=$(get_proc "net/bonding/${_realiface}" 2>/dev/null) ; then
697         # This is a bond: various monitoring strategies
698         echo "$_bi" | grep -q 'Currently Active Slave: None' && {
699             echo "ERROR: No active slaves for bond device ${_realiface}"
700             return 1
701         }
702         echo "$_bi" | grep -q '^MII Status: up' || {
703             echo "ERROR: public network interface ${_realiface} is down"
704             return 1
705         }
706         echo "$_bi" | grep -q '^Bonding Mode: IEEE 802.3ad Dynamic link aggregation' && {
707             # This works around a bug in the driver where the
708             # overall bond status can be up but none of the actual
709             # physical interfaces have a link.
710             echo "$_bi" | grep 'MII Status:' | tail -n +2 | grep -q '^MII Status: up' || {
711                 echo "ERROR: No active slaves for 802.ad bond device ${_realiface}"
712                 return 1
713             }
714         }
716         return 0
717     else
718         # Not a bond
719         case "$_iface" in
720             lo*)
721                 # loopback is always working
722                 return 0
723                 ;;
724             ib*)
725                 # we don't know how to test ib links
726                 return 0
727                 ;;
728             *)
729                 ethtool "$_iface" | grep -q 'Link detected: yes' || {
730                     # On some systems, this is not successful when a
731                     # cable is plugged but the interface has not been
732                     # brought up previously. Bring the interface up
733                     # and try again...
734                     ip link set "$_iface" up
735                     ethtool "$_iface" | grep -q 'Link detected: yes' || {
736                         echo "ERROR: No link on the public network interface ${_iface}"
737                         return 1
738                     }
739                 }
740                 return 0
741                 ;;
742         esac
743     fi
746 ########################################################
747 # Simple counters
748 _ctdb_counter_common () {
749     _service_name="${1:-${service_name:-${script_name}}}"
750     _counter_file="${CTDB_SCRIPT_VARDIR}/failcount/${_service_name}"
751     mkdir -p "${_counter_file%/*}" # dirname
753 # Some code passes an argument
754 # shellcheck disable=SC2120
755 ctdb_counter_init () {
756     _ctdb_counter_common "$1"
758     >"$_counter_file"
760 ctdb_counter_incr () {
761     _ctdb_counter_common "$1"
763     # unary counting using newlines!
764     echo >>"$_counter_file"
766 ctdb_counter_get () {
767     _ctdb_counter_common "$1"
768     # unary counting!
769     stat -c "%s" "$_counter_file" 2>/dev/null || echo 0
772 ########################################################
774 ctdb_setup_service_state_dir ()
776         _s="${1:-${service_name}}"
778         _service_state_dir="${CTDB_SCRIPT_VARDIR}/service_state/${_s}"
779         mkdir -p "$_service_state_dir" ||
780                 die "Error creating state dir \"${_service_state_dir}\""
782         echo "$_service_state_dir"
785 ########################################################
786 # Managed status history, for auto-start/stop
788 _ctdb_managed_common ()
790     _ctdb_managed_file="${CTDB_SCRIPT_VARDIR}/managed_history/${service_name}"
793 ctdb_service_managed ()
795     _ctdb_managed_common
796     mkdir -p "${_ctdb_managed_file%/*}" # dirname
797     touch "$_ctdb_managed_file"
800 ctdb_service_unmanaged ()
802     _ctdb_managed_common
803     rm -f "$_ctdb_managed_file"
806 is_ctdb_previously_managed_service ()
808     _ctdb_managed_common
809     [ -f "$_ctdb_managed_file" ]
812 ##################################################################
813 # Reconfigure a service on demand
815 _ctdb_service_reconfigure_common ()
817     _d="${CTDB_SCRIPT_VARDIR}/service_status/${service_name}"
818     mkdir -p "$_d"
819     _ctdb_service_reconfigure_flag="$_d/reconfigure"
822 ctdb_service_needs_reconfigure ()
824     _ctdb_service_reconfigure_common
825     [ -e "$_ctdb_service_reconfigure_flag" ]
828 ctdb_service_set_reconfigure ()
830     _ctdb_service_reconfigure_common
831     >"$_ctdb_service_reconfigure_flag"
834 ctdb_service_unset_reconfigure ()
836     _ctdb_service_reconfigure_common
837     rm -f "$_ctdb_service_reconfigure_flag"
840 ctdb_service_reconfigure ()
842     echo "Reconfiguring service \"${service_name}\"..."
843     ctdb_service_unset_reconfigure
844     service_reconfigure || return $?
845     # Intentionally have this use $service_name as default
846     # shellcheck disable=SC2119
847     ctdb_counter_init
850 # Default service_reconfigure() function does nothing.
851 service_reconfigure ()
853     :
856 ##################################################################
857 # Does CTDB manage this service? - and associated auto-start/stop
859 ctdb_compat_managed_service ()
861     if [ "$1" = "yes" -a "$2" = "$service_name" ] ; then
862         CTDB_MANAGED_SERVICES="$CTDB_MANAGED_SERVICES $2"
863     fi
866 is_ctdb_managed_service ()
868     assert_service_name
870     # $t is used just for readability and to allow better accurate
871     # matching via leading/trailing spaces
872     t=" $CTDB_MANAGED_SERVICES "
874     # Return 0 if "<space>$service_name<space>" appears in $t
875     if [ "${t#* ${service_name} }" != "${t}" ] ; then
876         return 0
877     fi
879     # If above didn't match then update $CTDB_MANAGED_SERVICES for
880     # backward compatibility and try again.
881     ctdb_compat_managed_service "$CTDB_MANAGES_VSFTPD"   "vsftpd"
882     ctdb_compat_managed_service "$CTDB_MANAGES_SAMBA"    "samba"
883     ctdb_compat_managed_service "$CTDB_MANAGES_WINBIND"  "winbind"
884     ctdb_compat_managed_service "$CTDB_MANAGES_HTTPD"    "apache2"
885     ctdb_compat_managed_service "$CTDB_MANAGES_HTTPD"    "httpd"
886     ctdb_compat_managed_service "$CTDB_MANAGES_ISCSI"    "iscsi"
887     ctdb_compat_managed_service "$CTDB_MANAGES_CLAMD"    "clamd"
888     ctdb_compat_managed_service "$CTDB_MANAGES_NFS"      "nfs"
890     t=" $CTDB_MANAGED_SERVICES "
892     # Return 0 if "<space>$service_name<space>" appears in $t
893     [ "${t#* ${service_name} }" != "${t}" ]
896 ctdb_start_stop_service ()
898     assert_service_name
900     # Allow service-start/service-stop pseudo-events to start/stop
901     # services when we're not auto-starting/stopping and we're not
902     # monitoring.
903     case "$event_name" in
904         service-start)
905             if is_ctdb_managed_service ; then
906                 die 'service-start event not permitted when service is managed'
907             fi
908             if [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] ; then
909                 die 'service-start event not permitted with CTDB_SERVICE_AUTOSTARTSTOP=yes'
910             fi
911             ctdb_service_start
912             exit $?
913             ;;
914         service-stop)
915             if is_ctdb_managed_service ; then
916                 die 'service-stop event not permitted when service is managed'
917             fi
918             if [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] ; then
919                 die 'service-stop event not permitted with CTDB_SERVICE_AUTOSTARTSTOP=yes'
920             fi
921             ctdb_service_stop
922             exit $?
923             ;;
924     esac
926     # Do nothing unless configured to...
927     [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] || return 0
929     [ "$event_name" = "monitor" ] || return 0
931     if is_ctdb_managed_service ; then
932         if ! is_ctdb_previously_managed_service ; then
933             echo "Starting service \"$service_name\" - now managed"
934             background_with_logging ctdb_service_start
935             exit $?
936         fi
937     else
938         if is_ctdb_previously_managed_service ; then
939             echo "Stopping service \"$service_name\" - no longer managed"
940             background_with_logging ctdb_service_stop
941             exit $?
942         fi
943     fi
946 ctdb_service_start ()
948     # The service is marked managed if we've ever tried to start it.
949     ctdb_service_managed
951     service_start || return $?
953     # Intentionally have this use $service_name as default
954     # shellcheck disable=SC2119
955     ctdb_counter_init
956     ctdb_check_tcp_init
959 ctdb_service_stop ()
961     ctdb_service_unmanaged
962     service_stop
965 # Default service_start() and service_stop() functions.
967 # These may be overridden in an eventscript.
968 service_start ()
970     service "$service_name" start
973 service_stop ()
975     service "$service_name" stop
978 ##################################################################
980 # This exists only for backward compatibility with 3rd party scripts
981 # that call it
982 ctdb_standard_event_handler ()
984     :
987 iptables_wrapper ()
989     _family="$1" ; shift
990     if [ "$_family" = "inet6" ] ; then
991         _iptables_cmd="ip6tables"
992     else
993         _iptables_cmd="iptables"
994     fi
996     # iptables doesn't like being re-entered, so flock-wrap it.
997     flock -w 30 "${CTDB_SCRIPT_VARDIR}/iptables.flock" "$_iptables_cmd" "$@"
1000 # AIX (and perhaps others?) doesn't have mktemp
1001 # type is commonly supported and more portable than which(1)
1002 # shellcheck disable=SC2039
1003 if ! type mktemp >/dev/null 2>&1 ; then
1004     mktemp ()
1005     {
1006         _dir=false
1007         if [ "$1" = "-d" ] ; then
1008             _dir=true
1009             shift
1010         fi
1011         _d="${TMPDIR:-/tmp}"
1012         _hex10=$(dd if=/dev/urandom count=20 2>/dev/null | \
1013             md5sum | \
1014             sed -e 's@\(..........\).*@\1@')
1015         _t="${_d}/tmp.${_hex10}"
1016         (
1017             umask 077
1018             if $_dir ; then
1019                 mkdir "$_t"
1020             else
1021                 >"$_t"
1022             fi
1023         )
1024         echo "$_t"
1025     }
1028 ######################################################################
1029 # NFS callout handling
1031 nfs_callout_init ()
1033         _state_dir="$1"
1035         if [ -z "$CTDB_NFS_CALLOUT" ] ; then
1036                 CTDB_NFS_CALLOUT="${CTDB_BASE}/nfs-linux-kernel-callout"
1037         fi
1038         # Always export, for statd callout
1039         export CTDB_NFS_CALLOUT
1041         # If the callout wants to use this then it must create it
1042         export CTDB_NFS_CALLOUT_STATE_DIR="${_state_dir}/callout-state"
1044         # Export, if set, for use by clustered NFS callouts
1045         if [ -n "$CTDB_NFS_STATE_FS_TYPE" ] ; then
1046                 export CTDB_NFS_STATE_FS_TYPE
1047         fi
1048         if [ -n "$CTDB_NFS_STATE_MNT" ] ; then
1049                 export CTDB_NFS_STATE_MNT
1050         fi
1052         nfs_callout_cache="${_state_dir}/nfs_callout_cache"
1053         nfs_callout_cache_callout="${nfs_callout_cache}/CTDB_NFS_CALLOUT"
1054         nfs_callout_cache_ops="${nfs_callout_cache}/ops"
1057 nfs_callout_register ()
1059     mkdir -p "$nfs_callout_cache_ops"
1060     rm -f "$nfs_callout_cache_ops"/*
1062     echo "$CTDB_NFS_CALLOUT" >"$nfs_callout_cache_callout"
1064     _t=$(eval "$CTDB_NFS_CALLOUT" "register")
1065     if [ -n "$_t" ] ; then
1066         echo "$_t" |
1067             while IFS="" read _op ; do
1068                 touch "${nfs_callout_cache_ops}/${_op}"
1069             done
1070     else
1071         touch "${nfs_callout_cache_ops}/ALL"
1072     fi
1075 nfs_callout ()
1077     # Re-run registration if $CTDB_NFS_CALLOUT has changed
1078     _prev=""
1079     if [ -r "$nfs_callout_cache_callout" ] ; then
1080         read _prev <"$nfs_callout_cache_callout"
1081     fi
1082     if [ "$CTDB_NFS_CALLOUT" != "$_prev" ] ; then
1083         nfs_callout_register
1084     fi
1086     # Run the operation if it is registered...
1087     if [ -e "${nfs_callout_cache_ops}/${1}" ] || \
1088            [ -e "${nfs_callout_cache_ops}/ALL" ]; then
1089         eval "$CTDB_NFS_CALLOUT" "$@"
1090     fi
1093 ########################################################
1094 # tickle handling
1095 ########################################################
1097 update_tickles ()
1099         _port="$1"
1101         tickledir="${CTDB_SCRIPT_VARDIR}/tickles"
1102         mkdir -p "$tickledir"
1104         # What public IPs do I hold?
1105         _pnn=$(ctdb_get_pnn)
1106         _ips=$($CTDB -X ip | awk -F'|' -v pnn="$_pnn" '$3 == pnn {print $2}')
1108         # IPs and port as ss filters
1109         _ip_filter=""
1110         for _ip in $_ips ; do
1111             _ip_filter="${_ip_filter}${_ip_filter:+ || }src [${_ip}]"
1112         done
1113         _port_filter="sport == :${_port}"
1115         # Record connections to our public IPs in a temporary file.
1116         # This temporary file is in CTDB's private state directory and
1117         # $$ is used to avoid a very rare race involving CTDB's script
1118         # debugging.  No security issue, nothing to see here...
1119         _my_connections="${tickledir}/${_port}.connections.$$"
1120         # Parentheses are needed around the filters for precedence but
1121         # the parentheses can't be empty!
1122         ss -tn state established \
1123            "${_ip_filter:+( ${_ip_filter} )}" \
1124            "${_port_filter:+( ${_port_filter} )}" |
1125         awk 'NR > 1 {print $4, $3}' |
1126         sort >"$_my_connections"
1128         # Record our current tickles in a temporary file
1129         _my_tickles="${tickledir}/${_port}.tickles.$$"
1130         for _i in $_ips ; do
1131                 $CTDB -X gettickles "$_i" "$_port" |
1132                 awk -F'|' 'NR > 1 { printf "%s:%s %s:%s\n", $2, $3, $4, $5 }'
1133         done |
1134         sort >"$_my_tickles"
1136         # Add tickles for connections that we haven't already got tickles for
1137         comm -23 "$_my_connections" "$_my_tickles" | \
1138                 $CTDB addtickle
1140         # Remove tickles for connections that are no longer there
1141         comm -13 "$_my_connections" "$_my_tickles" | \
1142                 $CTDB deltickle
1144         rm -f "$_my_connections" "$_my_tickles"
1146         # Remove stale files from killed scripts
1147         # Files can't have spaces in name, more portable than -print0/-0
1148         # shellcheck disable=SC2038
1149         (cd "$tickledir" && find . -type f -mmin +10 | xargs -r rm)
1152 ########################################################
1153 # load a site local config file
1154 ########################################################
1156 [ -n "$CTDB_RC_LOCAL" -a -x "$CTDB_RC_LOCAL" ] && {
1157         . "$CTDB_RC_LOCAL"
1160 [ -x "${CTDB_BASE}/rc.local" ] && {
1161         . "${CTDB_BASE}/rc.local"
1164 [ -d "${CTDB_BASE}/rc.local.d" ] && {
1165         for i in "${CTDB_BASE}/rc.local.d"/* ; do
1166                 [ -x "$i" ] && . "$i"
1167         done
1170 script_name="${0##*/}"       # basename
1171 event_name="$1"