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'
11 # CTDB_VARDIR is used elsewhere
12 # shellcheck disable=SC2034
13 CTDB_VARDIR="/usr/local/var/lib/ctdb"
15 CTDB="${CTDB:-/usr/local/bin/ctdb}"
17 # Only (and always) override these variables in test code
19 if [ -z "$CTDB_SCRIPT_VARDIR" ] ; then
20 CTDB_SCRIPT_VARDIR="/usr/local/var/lib/ctdb/scripts"
23 if [ -z "$CTDB_SYS_ETCDIR" ] ; then
24 CTDB_SYS_ETCDIR="/etc"
27 if [ -z "$CTDB_HELPER_BINDIR" ] ; then
28 CTDB_HELPER_BINDIR="/usr/local/libexec/ctdb"
31 #######################################
32 # pull in a system config file, if any
38 if [ -f "${CTDB_SYS_ETCDIR}/sysconfig/${_i}" ]; then
39 . "${CTDB_SYS_ETCDIR}/sysconfig/${_i}"
41 elif [ -f "${CTDB_SYS_ETCDIR}/default/${_i}" ]; then
42 . "${CTDB_SYS_ETCDIR}/default/${_i}"
48 # load_script_options [ component script ]
49 # script is an event script name relative to a component
50 # component is currently ignored
51 load_script_options ()
53 if [ $# -eq 2 ] ; then
55 elif [ $# -eq 0 ] ; then
58 die "usage: load_script_options [ component script ]"
61 _options="${CTDB_BASE}/script.options"
63 if [ -r "$_options" ] ; then
67 if [ -n "$_script" ] ; then
68 _s="${CTDB_BASE}/events/legacy/${_script}"
72 _options="${_s}.options"
74 if [ -r "$_options" ] ; then
79 ##############################################################
90 # Log given message or stdin to either syslog or a CTDB log file
91 # $1 is the tag passed to logger if syslog is in use.
96 case "$CTDB_LOGGING" in
98 if [ -n "$CTDB_LOGGING" ] ; then
99 _file="${CTDB_LOGGING#file:}"
101 _file="/usr/local/var/log/log.ctdb"
104 if [ -n "$*" ] ; then
112 # Handle all syslog:* variants here too. There's no tool to do
113 # the lossy things, so just use logger.
114 logger -t "ctdbd: ${_tag}" "$@"
119 # When things are run in the background in an eventscript then logging
120 # output might get lost. This is the "solution". :-)
121 background_with_logging ()
124 "$@" 2>&1 </dev/null |
125 script_log "${script_name}&"
131 ##############################################################
132 # check number of args for different events
138 echo "ERROR: must supply interface, IP and maskbits"
144 echo "ERROR: must supply old interface, new interface, IP and maskbits"
151 ##############################################################
152 # determine on what type of system (init style) we are running
155 # only do detection if not already set:
156 if [ -n "$CTDB_INIT_STYLE" ] ; then
160 if [ -x /sbin/startproc ]; then
161 CTDB_INIT_STYLE="suse"
162 elif [ -x /sbin/start-stop-daemon ]; then
163 CTDB_INIT_STYLE="debian"
165 CTDB_INIT_STYLE="redhat"
169 ######################################################
170 # simulate /sbin/service on platforms that don't have it
171 # _service() makes it easier to hook the service() function for
178 # do nothing, when no service was specified
179 [ -z "$_service_name" ] && return
181 if [ -x /sbin/service ]; then
182 $_nice /sbin/service "$_service_name" "$_op"
183 elif [ -x /usr/sbin/service ]; then
184 $_nice /usr/sbin/service "$_service_name" "$_op"
185 elif [ -x /bin/systemctl ]; then
186 $_nice /bin/systemctl "$_op" "$_service_name"
187 elif [ -x "${CTDB_SYS_ETCDIR}/init.d/${_service_name}" ]; then
188 $_nice "${CTDB_SYS_ETCDIR}/init.d/${_service_name}" "$_op"
189 elif [ -x "${CTDB_SYS_ETCDIR}/rc.d/init.d/${_service_name}" ]; then
190 $_nice "${CTDB_SYS_ETCDIR}/rc.d/init.d/${_service_name}" "$_op"
200 ######################################################
201 # simulate /sbin/service (niced) on platforms that don't have it
208 ######################################################
209 # Cached retrieval of PNN from local node. This never changes so why
210 # open a client connection to the server each time this is needed?
213 _pnn_file="${CTDB_SCRIPT_VARDIR}/my-pnn"
214 if [ ! -f "$_pnn_file" ] ; then
215 $CTDB pnn >"$_pnn_file"
221 # Cached retrieval of private IP address from local node. This never
223 ctdb_get_ip_address ()
225 _ip_addr_file="${CTDB_SCRIPT_VARDIR}/my-ip-address"
226 if [ ! -f "$_ip_addr_file" ] ; then
227 $CTDB -X nodestatus |
228 awk -F '|' 'NR == 2 { print $3 }' >"$_ip_addr_file"
234 # Cached retrieval of database options for use by event scripts.
236 # If the variables are already set then they should not be overwritten
237 # - this should only happen during event script testing.
238 ctdb_get_db_options ()
240 _db_opts_file="${CTDB_SCRIPT_VARDIR}/db_options.cache"
242 if [ ! -f "$_db_opts_file" ] ; then
244 ctdb_translate_option "database" \
245 "volatile database directory" \
247 ctdb_translate_option "database" \
248 "persistent database directory" \
249 "CTDB_DBDIR_PERSISTENT"
250 ctdb_translate_option "database" \
251 "state database directory" \
259 ctdb_translate_option ()
265 # ctdb-config already prints an error if something goes wrong
266 _t=$("${CTDB_HELPER_BINDIR}/ctdb-config" get "$_section" "$_opt") || \
268 echo "${_variable}=\"${_t}\""
271 ######################################################
272 # wrapper around /proc/ settings to allow them to be hooked
274 # 1st arg is relative path under /proc/, 2nd arg is value to set
277 echo "$2" >"/proc/$1"
282 if [ -w "/proc/$1" ] ; then
287 ######################################################
288 # wrapper around getting file contents from /proc/ to allow
289 # this to be hooked for testing
290 # 1st arg is relative path under /proc/
296 ######################################################
297 # Print up to $_max kernel stack traces for processes named $_program
298 program_stack_traces ()
304 for _pid in $(pidof "$_prog") ; do
305 [ "$_count" -le "$_max" ] || break
307 # Do this first to avoid racing with process exit
308 _stack=$(get_proc "${_pid}/stack" 2>/dev/null)
309 if [ -n "$_stack" ] ; then
310 echo "Stack trace for ${_prog}[${_pid}]:"
312 _count=$((_count + 1))
317 ######################################################
318 # Ensure $service_name is set
319 assert_service_name ()
321 # service_name is set by the event script
322 # shellcheck disable=SC2154
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
339 [ -d "${d}/." ] || return 1
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"
356 ######################################################
357 # check a set of tcp ports
358 # usage: ctdb_check_tcp_ports <ports...>
359 ######################################################
361 # Check whether something is listening on all of the given TCP ports
362 # using the "ctdb checktcpport" command.
363 ctdb_check_tcp_ports()
365 if [ -z "$1" ] ; then
366 echo "INTERNAL ERROR: ctdb_check_tcp_ports - no ports specified"
370 for _p ; do # process each function argument (port)
371 _cmd="$CTDB checktcpport $_p"
376 echo "$service_name not listening on TCP port $_p"
380 # Couldn't bind, something already listening, next port
384 echo "unexpected error (${_ret}) running \"${_cmd}\""
385 if [ -n "$_out" ] ; then
393 # All ports listening
397 ######################################################
398 # check a unix socket
399 # usage: ctdb_check_unix_socket SOCKPATH
400 ######################################################
401 ctdb_check_unix_socket()
405 if [ -z "$_sockpath" ] ; then
406 echo "ERROR: ctdb_check_unix_socket() requires socket path"
410 _out=$(ss -l -x "src ${_sockpath}" | tail -n +2)
411 if [ -z "$_out" ] ; then
412 echo "ERROR: ${service_name} not listening on ${_sockpath}"
417 ################################################
418 # kill off any TCP connections with the given IP
419 ################################################
420 kill_tcp_connections ()
426 if [ "$3" = "oneway" ] ; then
430 get_tcp_connections_for_ip "$_ip" | {
435 while read _dst _src; do
436 _destport="${_dst##*:}"
439 # we only do one-way killtcp for CIFS
440 139|445) __oneway=true ;;
443 _connections="${_connections}${_nl}${_src} ${_dst}"
444 if ! $__oneway ; then
445 _connections="${_connections}${_nl}${_dst} ${_src}"
448 _killcount=$((_killcount + 1))
451 if [ $_killcount -eq 0 ] ; then
455 if [ -n "$CTDB_KILLTCP_DEBUGLEVEL" ]; then
456 _debuglevel="$CTDB_KILLTCP_DEBUGLEVEL"
458 _debuglevel="$CTDB_DEBUGLEVEL"
460 echo "$_connections" | \
461 CTDB_DEBUGLEVEL="$_debuglevel" \
462 "${CTDB_HELPER_BINDIR}/ctdb_killtcp" "$_iface" || {
463 echo "Failed to kill TCP connections"
467 _connections=$(get_tcp_connections_for_ip "$_ip")
468 if [ -z "$_connections" ] ; then
471 _remaining=$(echo "$_connections" | wc -l)
474 _actually_killed=$((_killcount - _remaining))
476 _t="${_actually_killed}/${_killcount}"
477 echo "Killed ${_t} TCP connections to released IP $_ip"
479 if [ -n "$_connections" ] ; then
480 echo "Remaining connections:"
481 echo "$_connections" | sed -e 's|^| |'
486 ##################################################################
487 # kill off the local end for any TCP connections with the given IP
488 ##################################################################
489 kill_tcp_connections_local_only ()
491 kill_tcp_connections "$@" "oneway"
494 ##################################################################
495 # tickle any TCP connections with the given IP
496 ##################################################################
497 tickle_tcp_connections ()
501 # Get connections, both directions
502 _conns=$(get_tcp_connections_for_ip "$_ip" | \
503 awk '{ print $1, $2 ; print $2, $1 }')
505 echo "$_conns" | awk '{ print "Tickle TCP connection", $1, $2 }'
506 echo "$_conns" | ctdb tickle
509 get_tcp_connections_for_ip ()
513 ss -tn state established "src [$_ip]" | awk 'NR > 1 {print $3, $4}'
516 ########################################################
524 # Ensure interface is up
525 ip link set "$_iface" up || \
526 die "Failed to bringup interface $_iface"
528 # Only need to define broadcast for IPv4
534 # Intentionally unquoted multi-word value here
535 # shellcheck disable=SC2086
536 ip addr add "$_ip/$_maskbits" $_bcast dev "$_iface" || {
537 echo "Failed to add $_ip/$_maskbits on dev $_iface"
541 # Wait 5 seconds for IPv6 addresses to stop being tentative...
542 if [ -z "$_bcast" ] ; then
543 for _x in $(seq 1 10) ; do
544 ip addr show to "${_ip}/128" | grep -q "tentative" || break
548 # If the address was a duplicate then it won't be on the
549 # interface so flag an error.
550 _t=$(ip addr show to "${_ip}/128")
553 echo "Failed to add $_ip/$_maskbits on dev $_iface"
556 *tentative*|*dadfailed*)
557 echo "Failed to add $_ip/$_maskbits on dev $_iface"
558 ip addr del "$_ip/$_maskbits" dev "$_iface"
565 delete_ip_from_iface()
571 # This could be set globally for all interfaces but it is probably
572 # better to avoid surprises, so limit it the interfaces where CTDB
573 # has public IP addresses. There isn't anywhere else convenient
574 # to do this so just set it each time. This is much cheaper than
575 # remembering and re-adding secondaries.
576 set_proc "sys/net/ipv4/conf/${_iface}/promote_secondaries" 1
578 ip addr del "$_ip/$_maskbits" dev "$_iface" || {
579 echo "Failed to del $_ip on dev $_iface"
584 # If the given IP is hosted then print 2 items: maskbits and iface
593 ip addr show to "${_addr}/${_bits}" 2>/dev/null | \
594 awk 'NR == 1 { iface = $2; sub(":$", "", iface) ;
595 sub("@.*", "", iface) }
596 $1 ~ /inet/ { mask = $2; sub(".*/", "", mask);
602 _addr="${1%/*}" # Remove optional maskbits
604 # Intentional word splitting here
605 # shellcheck disable=SC2046
606 set -- $(ip_maskbits_iface "$_addr")
607 if [ -n "$1" ] ; then
610 echo "Removing public address $_addr/$_maskbits from device $_iface"
611 delete_ip_from_iface "$_iface" "$_addr" "$_maskbits" >/dev/null 2>&1
615 drop_all_public_ips ()
617 # _x is intentionally ignored
618 # shellcheck disable=SC2034
619 while read _ip _x ; do
624 done <"${CTDB_BASE}/public_addresses"
629 set_proc_maybe sys/net/ipv4/route/flush 1
630 set_proc_maybe sys/net/ipv6/route/flush 1
633 ########################################################
634 # Interface monitoring
636 # If the interface is a virtual one (e.g. VLAN) then get the
637 # underlying interface
638 interface_get_real ()
642 # If $_iface is a VLAN (i.e. contains an '@') then strip every
643 # before the '@', otherwise print the whole interface
647 # Check whether an interface is operational
652 _iface_info=$(ip -br link show "$_iface" 2>&1) || {
653 echo "ERROR: Monitored interface ${_iface} does not exist"
658 # If the interface is a virtual one (e.g. VLAN) then get the
659 # underlying interface.
660 _realiface=$(interface_get_real "${_iface_info%% *}")
662 if _bi=$(get_proc "net/bonding/${_realiface}" 2>/dev/null) ; then
663 # This is a bond: various monitoring strategies
664 echo "$_bi" | grep -q 'Currently Active Slave: None' && {
665 echo "ERROR: No active slaves for bond device ${_realiface}"
668 echo "$_bi" | grep -q '^MII Status: up' || {
669 echo "ERROR: public network interface ${_realiface} is down"
672 echo "$_bi" | grep -q '^Bonding Mode: IEEE 802.3ad Dynamic link aggregation' && {
673 # This works around a bug in the driver where the
674 # overall bond status can be up but none of the actual
675 # physical interfaces have a link.
676 echo "$_bi" | grep 'MII Status:' | tail -n +2 | grep -q '^MII Status: up' || {
677 echo "ERROR: No active slaves for 802.ad bond device ${_realiface}"
687 # loopback is always working
691 # we don't know how to test ib links
695 ethtool "$_iface" | grep -q 'Link detected: yes' || {
696 # On some systems, this is not successful when a
697 # cable is plugged but the interface has not been
698 # brought up previously. Bring the interface up
700 ip link set "$_iface" up
701 ethtool "$_iface" | grep -q 'Link detected: yes' || {
702 echo "ERROR: No link on the public network interface ${_iface}"
712 ########################################################
714 _ctdb_counter_common ()
716 [ $# -le 1 ] || die "usage: _ctdb_counter_common [name]"
718 if [ $# -eq 1 ] ; then
719 _counter_name="${1}.failcount"
721 _counter_name="failcount"
724 if [ -z "$script_state_dir" ] ; then
725 die "ctdb_counter_* functions need ctdb_setup_state_dir()"
728 _counter_file="${script_state_dir}/${_counter_name}"
730 # Some code passes an argument
731 # shellcheck disable=SC2120
732 ctdb_counter_init () {
733 _ctdb_counter_common "$1"
737 ctdb_counter_incr () {
738 _ctdb_counter_common "$1"
740 # unary counting using newlines!
741 echo >>"$_counter_file"
743 ctdb_counter_get () {
744 _ctdb_counter_common "$1"
746 _val=$(wc -c < "$_counter_file" 2>/dev/null || echo 0)
747 # Strip leading spaces from ouput of wc (on freebsd)
748 # shellcheck disable=SC2086
752 ########################################################
754 # ctdb_setup_state_dir <type> <name>
755 # Sets/creates script_state_dir)
756 ctdb_setup_state_dir ()
758 [ $# -eq 2 ] || die "usage: ctdb_setup_state_dir <type> <name>"
763 script_state_dir="${CTDB_SCRIPT_VARDIR}/${_type}/${_name}"
765 mkdir -p "$script_state_dir" || \
766 die "Error creating script state dir \"${script_state_dir}\""
769 ##################################################################
770 # Reconfigure a service on demand
772 _ctdb_service_reconfigure_common ()
774 if [ -z "$script_state_dir" ] ; then
775 die "ctdb_service_*_reconfigure() needs ctdb_setup_state_dir()"
778 _ctdb_service_reconfigure_flag="${script_state_dir}/need_reconfigure"
781 ctdb_service_needs_reconfigure ()
783 _ctdb_service_reconfigure_common
784 [ -e "$_ctdb_service_reconfigure_flag" ]
787 ctdb_service_set_reconfigure ()
789 _ctdb_service_reconfigure_common
790 : >"$_ctdb_service_reconfigure_flag"
793 ctdb_service_unset_reconfigure ()
795 _ctdb_service_reconfigure_common
796 rm -f "$_ctdb_service_reconfigure_flag"
799 ctdb_service_reconfigure ()
801 echo "Reconfiguring service \"${service_name}\"..."
802 ctdb_service_unset_reconfigure
803 service_reconfigure || return $?
804 # Intentionally have this use $service_name as default
805 # shellcheck disable=SC2119
809 # Default service_reconfigure() function does nothing.
810 service_reconfigure ()
815 # Default service_start() and service_stop() functions.
817 # These may be overridden in an eventscript.
820 service "$service_name" start
825 service "$service_name" stop
828 ##################################################################
830 # This exists only for backward compatibility with 3rd party scripts
832 ctdb_standard_event_handler ()
840 if [ "$_family" = "inet6" ] ; then
841 _iptables_cmd="ip6tables"
843 _iptables_cmd="iptables"
846 # iptables doesn't like being re-entered, so flock-wrap it.
847 flock -w 30 "${CTDB_SCRIPT_VARDIR}/iptables.flock" "$_iptables_cmd" "$@"
850 # AIX (and perhaps others?) doesn't have mktemp
851 # type is commonly supported and more portable than which(1)
852 # shellcheck disable=SC2039
853 if ! type mktemp >/dev/null 2>&1 ; then
857 if [ "$1" = "-d" ] ; then
862 _hex10=$(dd if=/dev/urandom count=20 2>/dev/null | \
865 _t="${_d}/tmp.${_hex10}"
878 ######################################################################
879 # NFS callout handling
885 if [ -z "$CTDB_NFS_CALLOUT" ] ; then
886 CTDB_NFS_CALLOUT="${CTDB_BASE}/nfs-linux-kernel-callout"
888 # Always export, for statd callout
889 export CTDB_NFS_CALLOUT
891 # If the callout wants to use this then it must create it
892 export CTDB_NFS_CALLOUT_STATE_DIR="${_state_dir}/callout-state"
894 # Export, if set, for use by clustered NFS callouts
895 if [ -n "$CTDB_NFS_STATE_FS_TYPE" ] ; then
896 export CTDB_NFS_STATE_FS_TYPE
898 if [ -n "$CTDB_NFS_STATE_MNT" ] ; then
899 export CTDB_NFS_STATE_MNT
902 nfs_callout_cache="${_state_dir}/nfs_callout_cache"
903 nfs_callout_cache_callout="${nfs_callout_cache}/CTDB_NFS_CALLOUT"
904 nfs_callout_cache_ops="${nfs_callout_cache}/ops"
907 nfs_callout_register ()
909 mkdir -p "$nfs_callout_cache_ops"
910 rm -f "$nfs_callout_cache_ops"/*
912 echo "$CTDB_NFS_CALLOUT" >"$nfs_callout_cache_callout"
914 _t=$("$CTDB_NFS_CALLOUT" "register")
915 if [ -n "$_t" ] ; then
917 while IFS="" read _op ; do
918 touch "${nfs_callout_cache_ops}/${_op}"
921 touch "${nfs_callout_cache_ops}/ALL"
927 # Re-run registration if $CTDB_NFS_CALLOUT has changed
929 if [ -r "$nfs_callout_cache_callout" ] ; then
930 read _prev <"$nfs_callout_cache_callout"
932 if [ "$CTDB_NFS_CALLOUT" != "$_prev" ] ; then
936 # Run the operation if it is registered...
937 if [ -e "${nfs_callout_cache_ops}/${1}" ] || \
938 [ -e "${nfs_callout_cache_ops}/ALL" ]; then
939 "$CTDB_NFS_CALLOUT" "$@"
943 ########################################################
945 ########################################################
951 tickledir="${CTDB_SCRIPT_VARDIR}/tickles"
952 mkdir -p "$tickledir"
954 # What public IPs do I hold?
956 _ips=$($CTDB -X ip | awk -F'|' -v pnn="$_pnn" '$3 == pnn {print $2}')
958 # IPs and port as ss filters
960 for _ip in $_ips ; do
961 _ip_filter="${_ip_filter}${_ip_filter:+ || }src [${_ip}]"
963 _port_filter="sport == :${_port}"
965 # Record connections to our public IPs in a temporary file.
966 # This temporary file is in CTDB's private state directory and
967 # $$ is used to avoid a very rare race involving CTDB's script
968 # debugging. No security issue, nothing to see here...
969 _my_connections="${tickledir}/${_port}.connections.$$"
970 # Parentheses are needed around the filters for precedence but
971 # the parentheses can't be empty!
973 # Recent versions of ss print square brackets around IPv6
974 # addresses. While it is desirable to update CTDB's address
975 # parsing and printing code, something needs to be done here
976 # for backward compatibility, so just delete the brackets.
977 ss -tn state established \
978 "${_ip_filter:+( ${_ip_filter} )}" \
979 "${_port_filter:+( ${_port_filter} )}" |
980 awk 'NR > 1 {print $4, $3}' |
982 sort >"$_my_connections"
984 # Record our current tickles in a temporary file
985 _my_tickles="${tickledir}/${_port}.tickles.$$"
987 $CTDB -X gettickles "$_i" "$_port" |
988 awk -F'|' 'NR > 1 { printf "%s:%s %s:%s\n", $2, $3, $4, $5 }'
992 # Add tickles for connections that we haven't already got tickles for
993 comm -23 "$_my_connections" "$_my_tickles" | \
996 # Remove tickles for connections that are no longer there
997 comm -13 "$_my_connections" "$_my_tickles" | \
1000 rm -f "$_my_connections" "$_my_tickles"
1002 # Remove stale files from killed scripts
1003 # Files can't have spaces in name, more portable than -print0/-0
1004 # shellcheck disable=SC2038
1005 (cd "$tickledir" && find . -type f -mmin +10 | xargs -r rm)
1008 ########################################################
1009 # load a site local config file
1010 ########################################################
1012 [ -x "${CTDB_BASE}/rc.local" ] && {
1013 . "${CTDB_BASE}/rc.local"
1016 [ -d "${CTDB_BASE}/rc.local.d" ] && {
1017 for i in "${CTDB_BASE}/rc.local.d"/* ; do
1018 [ -x "$i" ] && . "$i"
1022 script_name="${0##*/}" # basename