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
40 if [ -f "${CTDB_SYS_ETCDIR}/sysconfig/$1" ]; then
41 . "${CTDB_SYS_ETCDIR}/sysconfig/$1"
42 elif [ -f "${CTDB_SYS_ETCDIR}/default/$1" ]; then
43 . "${CTDB_SYS_ETCDIR}/default/$1"
49 load_system_config "ctdb"
51 _config="${CTDB_BASE}/ctdbd.conf"
52 if [ -r "$_config" ] ; then
57 # load_script_options [ component script ]
58 # script is an event script name relative to a component
59 # component is currently ignored
60 load_script_options ()
62 if [ $# -eq 2 ] ; then
64 elif [ $# -eq 0 ] ; then
67 die "usage: load_script_options [ component script ]"
72 _options="${CTDB_BASE}/script.options"
74 if [ -r "$_options" ] ; then
78 if [ -n "$_script" ] ; then
79 _s="${CTDB_BASE}/events.d/${_script}"
83 _options="${_s}.options"
85 if [ -r "$_options" ] ; then
90 ##############################################################
101 # Log given message or stdin to either syslog or a CTDB log file
102 # $1 is the tag passed to logger if syslog is in use.
107 case "$CTDB_LOGGING" in
109 if [ -n "$CTDB_LOGGING" ] ; then
110 _file="${CTDB_LOGGING#file:}"
112 _file="/usr/local/var/log/log.ctdb"
115 if [ -n "$*" ] ; then
123 # Handle all syslog:* variants here too. There's no tool to do
124 # the lossy things, so just use logger.
125 logger -t "ctdbd: ${_tag}" "$@"
130 # When things are run in the background in an eventscript then logging
131 # output might get lost. This is the "solution". :-)
132 background_with_logging ()
135 "$@" 2>&1 </dev/null |
136 script_log "${script_name}&"
142 ##############################################################
143 # check number of args for different events
149 echo "ERROR: must supply interface, IP and maskbits"
155 echo "ERROR: must supply old interface, new interface, IP and maskbits"
162 ##############################################################
163 # determine on what type of system (init style) we are running
166 # only do detection if not already set:
167 if [ -n "$CTDB_INIT_STYLE" ] ; then
171 if [ -x /sbin/startproc ]; then
172 CTDB_INIT_STYLE="suse"
173 elif [ -x /sbin/start-stop-daemon ]; then
174 CTDB_INIT_STYLE="debian"
176 CTDB_INIT_STYLE="redhat"
180 ######################################################
181 # simulate /sbin/service on platforms that don't have it
182 # _service() makes it easier to hook the service() function for
189 # do nothing, when no service was specified
190 [ -z "$_service_name" ] && return
192 if [ -x /sbin/service ]; then
193 $_nice /sbin/service "$_service_name" "$_op"
194 elif [ -x /usr/sbin/service ]; then
195 $_nice /usr/sbin/service "$_service_name" "$_op"
196 elif [ -x /bin/systemctl ]; then
197 $_nice /bin/systemctl "$_op" "$_service_name"
198 elif [ -x "${CTDB_SYS_ETCDIR}/init.d/${_service_name}" ]; then
199 $_nice "${CTDB_SYS_ETCDIR}/init.d/${_service_name}" "$_op"
200 elif [ -x "${CTDB_SYS_ETCDIR}/rc.d/init.d/${_service_name}" ]; then
201 $_nice "${CTDB_SYS_ETCDIR}/rc.d/init.d/${_service_name}" "$_op"
211 ######################################################
212 # simulate /sbin/service (niced) on platforms that don't have it
219 ######################################################
220 # Cached retrieval of PNN from local node. This never changes so why
221 # open a client connection to the server each time this is needed?
224 _pnn_file="${CTDB_SCRIPT_VARDIR}/my-pnn"
225 if [ ! -f "$_pnn_file" ] ; then
226 $CTDB pnn >"$_pnn_file"
232 # Cached retrieval of private IP address from local node. This never
234 ctdb_get_ip_address ()
236 _ip_addr_file="${CTDB_SCRIPT_VARDIR}/my-ip-address"
237 if [ ! -f "$_ip_addr_file" ] ; then
238 $CTDB -X nodestatus |
239 awk -F '|' 'NR == 2 { print $3 }' >"$_ip_addr_file"
242 # ip_address is used by caller
243 # shellcheck disable=SC2034
247 # Cached retrieval of database options for use by event scripts.
249 # If the variables are already set then they should not be overwritten
250 # - this should only happen during event script testing.
251 ctdb_get_db_options ()
253 _db_opts_file="${CTDB_SCRIPT_VARDIR}/db_options.cache"
255 if [ ! -f "$_db_opts_file" ] ; then
257 ctdb_translate_option "database" \
258 "volatile database directory" \
260 ctdb_translate_option "database" \
261 "persistent database directory" \
262 "CTDB_DBDIR_PERSISTENT"
263 ctdb_translate_option "database" \
264 "state database directory" \
272 ctdb_translate_option ()
278 # ctdb-config already prints an error if something goes wrong
279 _t=$("${CTDB_HELPER_BINDIR}/ctdb-config" get "$_section" "$_opt") || \
281 echo "${_variable}=\"${_t}\""
284 ######################################################
285 # wrapper around /proc/ settings to allow them to be hooked
287 # 1st arg is relative path under /proc/, 2nd arg is value to set
290 echo "$2" >"/proc/$1"
295 if [ -w "/proc/$1" ] ; then
300 ######################################################
301 # wrapper around getting file contents from /proc/ to allow
302 # this to be hooked for testing
303 # 1st arg is relative path under /proc/
309 ######################################################
310 # Print up to $_max kernel stack traces for processes named $_program
311 program_stack_traces ()
317 for _pid in $(pidof "$_prog") ; do
318 [ "$_count" -le "$_max" ] || break
320 # Do this first to avoid racing with process exit
321 _stack=$(get_proc "${_pid}/stack" 2>/dev/null)
322 if [ -n "$_stack" ] ; then
323 echo "Stack trace for ${_prog}[${_pid}]:"
325 _count=$((_count + 1))
330 ######################################################
331 # Ensure $service_name is set
332 assert_service_name ()
334 # service_name is set by the event script
335 # shellcheck disable=SC2154
336 [ -n "$service_name" ] || die "INTERNAL ERROR: \$service_name not set"
339 ######################################################
340 # check a set of directories is available
341 # return 1 on a missing directory
342 # directories are read from stdin
343 ######################################################
344 ctdb_check_directories_probe()
346 while IFS="" read d ; do
352 [ -d "${d}/." ] || return 1
357 ######################################################
358 # check a set of directories is available
359 # directories are read from stdin
360 ######################################################
361 ctdb_check_directories()
363 ctdb_check_directories_probe || {
364 echo "ERROR: $service_name directory \"$d\" not available"
369 ######################################################
370 # check a set of tcp ports
371 # usage: ctdb_check_tcp_ports <ports...>
372 ######################################################
374 # Check whether something is listening on all of the given TCP ports
375 # using the "ctdb checktcpport" command.
376 ctdb_check_tcp_ports()
378 if [ -z "$1" ] ; then
379 echo "INTERNAL ERROR: ctdb_check_tcp_ports - no ports specified"
383 for _p ; do # process each function argument (port)
384 _cmd="$CTDB checktcpport $_p"
389 echo "$service_name not listening on TCP port $_p"
393 # Couldn't bind, something already listening, next port
397 echo "unexpected error (${_ret}) running \"${_cmd}\""
398 if [ -n "$_out" ] ; then
406 # All ports listening
410 ######################################################
411 # check a unix socket
412 # usage: ctdb_check_unix_socket SOCKPATH
413 ######################################################
414 ctdb_check_unix_socket()
418 if [ -z "$_sockpath" ] ; then
419 echo "ERROR: ctdb_check_unix_socket() requires socket path"
423 _out=$(ss -l -x "src ${_sockpath}" | tail -n +2)
424 if [ -z "$_out" ] ; then
425 echo "ERROR: ${service_name} not listening on ${_sockpath}"
430 ################################################
431 # kill off any TCP connections with the given IP
432 ################################################
433 kill_tcp_connections ()
439 if [ "$3" = "oneway" ] ; then
443 get_tcp_connections_for_ip "$_ip" | {
448 while read _dst _src; do
449 _destport="${_dst##*:}"
452 # we only do one-way killtcp for CIFS
453 139|445) __oneway=true ;;
456 _connections="${_connections}${_nl}${_src} ${_dst}"
457 if ! $__oneway ; then
458 _connections="${_connections}${_nl}${_dst} ${_src}"
461 _killcount=$((_killcount + 1))
464 if [ $_killcount -eq 0 ] ; then
468 echo "$_connections" | \
469 "${CTDB_HELPER_BINDIR}/ctdb_killtcp" "$_iface" || {
470 echo "Failed to kill TCP connections"
474 _connections=$(get_tcp_connections_for_ip "$_ip")
475 if [ -z "$_connections" ] ; then
478 _remaining=$(echo "$_connections" | wc -l)
481 _actually_killed=$((_killcount - _remaining))
483 _t="${_actually_killed}/${_killcount}"
484 echo "Killed ${_t} TCP connections to released IP $_ip"
486 if [ -n "$_connections" ] ; then
487 echo "Remaining connections:"
488 echo "$_connections" | sed -e 's|^| |'
493 ##################################################################
494 # kill off the local end for any TCP connections with the given IP
495 ##################################################################
496 kill_tcp_connections_local_only ()
498 kill_tcp_connections "$@" "oneway"
501 ##################################################################
502 # tickle any TCP connections with the given IP
503 ##################################################################
504 tickle_tcp_connections ()
508 # Get connections, both directions
509 _conns=$(get_tcp_connections_for_ip "$_ip" | \
510 awk '{ print $1, $2 ; print $2, $1 }')
512 echo "$_conns" | awk '{ print "Tickle TCP connection", $1, $2 }'
513 echo "$_conns" | ctdb tickle
516 get_tcp_connections_for_ip ()
520 ss -tn state established "src [$_ip]" | awk 'NR > 1 {print $3, $4}'
523 ########################################################
531 # Ensure interface is up
532 ip link set "$_iface" up || \
533 die "Failed to bringup interface $_iface"
535 # Only need to define broadcast for IPv4
541 # Intentionally unquoted multi-word value here
542 # shellcheck disable=SC2086
543 ip addr add "$_ip/$_maskbits" $_bcast dev "$_iface" || {
544 echo "Failed to add $_ip/$_maskbits on dev $_iface"
548 # Wait 5 seconds for IPv6 addresses to stop being tentative...
549 if [ -z "$_bcast" ] ; then
550 for _x in $(seq 1 10) ; do
551 ip addr show to "${_ip}/128" | grep -q "tentative" || break
555 # If the address was a duplicate then it won't be on the
556 # interface so flag an error.
557 _t=$(ip addr show to "${_ip}/128")
560 echo "Failed to add $_ip/$_maskbits on dev $_iface"
563 *tentative*|*dadfailed*)
564 echo "Failed to add $_ip/$_maskbits on dev $_iface"
565 ip addr del "$_ip/$_maskbits" dev "$_iface"
572 delete_ip_from_iface()
578 # This could be set globally for all interfaces but it is probably
579 # better to avoid surprises, so limit it the interfaces where CTDB
580 # has public IP addresses. There isn't anywhere else convenient
581 # to do this so just set it each time. This is much cheaper than
582 # remembering and re-adding secondaries.
583 set_proc "sys/net/ipv4/conf/${_iface}/promote_secondaries" 1
585 ip addr del "$_ip/$_maskbits" dev "$_iface" || {
586 echo "Failed to del $_ip on dev $_iface"
591 # If the given IP is hosted then print 2 items: maskbits and iface
600 ip addr show to "${_addr}/${_bits}" 2>/dev/null | \
601 awk 'NR == 1 { iface = $2; sub(":$", "", iface) ;
602 sub("@.*", "", iface) }
603 $1 ~ /inet/ { mask = $2; sub(".*/", "", mask);
609 _addr="${1%/*}" # Remove optional maskbits
611 # Intentional word splitting here
612 # shellcheck disable=SC2046
613 set -- $(ip_maskbits_iface "$_addr")
614 if [ -n "$1" ] ; then
617 echo "Removing public address $_addr/$_maskbits from device $_iface"
618 delete_ip_from_iface "$_iface" "$_addr" "$_maskbits" >/dev/null 2>&1
622 drop_all_public_ips ()
624 # _x is intentionally ignored
625 # shellcheck disable=SC2034
626 while read _ip _x ; do
628 done <"${CTDB_BASE}/public_addresses"
633 set_proc_maybe sys/net/ipv4/route/flush 1
634 set_proc_maybe sys/net/ipv6/route/flush 1
637 ########################################################
638 # Interface monitoring
640 # If the interface is a virtual one (e.g. VLAN) then get the
641 # underlying interface
642 interface_get_real ()
644 # Output of "ip link show <iface>"
647 # Extract the full interface description to see if it is a VLAN
648 _t=$(echo "$_iface_info" |
649 awk 'NR == 1 { iface = $2; sub(":$", "", iface) ;
653 # VLAN: use the underlying interface, after the '@'
657 # Not a regular VLAN. For backward compatibility, assume
658 # there is some other sort of VLAN that doesn't have the
659 # '@' in the output and only use what is before a '.'. If
660 # there is no '.' then this will be the whole interface
666 # Check whether an interface is operational
671 _iface_info=$(ip link show "$_iface" 2>&1) || {
672 echo "ERROR: Monitored interface ${_iface} does not exist"
677 # If the interface is a virtual one (e.g. VLAN) then get the
678 # underlying interface.
679 _realiface=$(interface_get_real "$_iface_info")
681 if _bi=$(get_proc "net/bonding/${_realiface}" 2>/dev/null) ; then
682 # This is a bond: various monitoring strategies
683 echo "$_bi" | grep -q 'Currently Active Slave: None' && {
684 echo "ERROR: No active slaves for bond device ${_realiface}"
687 echo "$_bi" | grep -q '^MII Status: up' || {
688 echo "ERROR: public network interface ${_realiface} is down"
691 echo "$_bi" | grep -q '^Bonding Mode: IEEE 802.3ad Dynamic link aggregation' && {
692 # This works around a bug in the driver where the
693 # overall bond status can be up but none of the actual
694 # physical interfaces have a link.
695 echo "$_bi" | grep 'MII Status:' | tail -n +2 | grep -q '^MII Status: up' || {
696 echo "ERROR: No active slaves for 802.ad bond device ${_realiface}"
706 # loopback is always working
710 # we don't know how to test ib links
714 ethtool "$_iface" | grep -q 'Link detected: yes' || {
715 # On some systems, this is not successful when a
716 # cable is plugged but the interface has not been
717 # brought up previously. Bring the interface up
719 ip link set "$_iface" up
720 ethtool "$_iface" | grep -q 'Link detected: yes' || {
721 echo "ERROR: No link on the public network interface ${_iface}"
731 ########################################################
733 _ctdb_counter_common ()
735 [ $# -le 1 ] || die "usage: _ctdb_counter_common [name]"
737 if [ $# -eq 1 ] ; then
738 _counter_name="${1}.failcount"
740 _counter_name="failcount"
743 if [ -z "$script_state_dir" ] ; then
744 die "ctdb_counter_* functions need ctdb_setup_state_dir()"
747 _counter_file="${script_state_dir}/${_counter_name}"
749 # Some code passes an argument
750 # shellcheck disable=SC2120
751 ctdb_counter_init () {
752 _ctdb_counter_common "$1"
756 ctdb_counter_incr () {
757 _ctdb_counter_common "$1"
759 # unary counting using newlines!
760 echo >>"$_counter_file"
762 ctdb_counter_get () {
763 _ctdb_counter_common "$1"
765 stat -c "%s" "$_counter_file" 2>/dev/null || echo 0
768 ########################################################
770 # ctdb_setup_state_dir <type> <name>
771 # Sets/creates script_state_dir)
772 ctdb_setup_state_dir ()
774 [ $# -eq 2 ] || die "usage: ctdb_setup_state_dir <type> <name>"
779 script_state_dir="${CTDB_SCRIPT_VARDIR}/${_type}/${_name}"
781 mkdir -p "$script_state_dir" || \
782 die "Error creating script state dir \"${script_state_dir}\""
785 ##################################################################
786 # Reconfigure a service on demand
788 _ctdb_service_reconfigure_common ()
790 if [ -z "$script_state_dir" ] ; then
791 die "ctdb_service_*_reconfigure() needs ctdb_setup_state_dir()"
794 _ctdb_service_reconfigure_flag="${script_state_dir}/need_reconfigure"
797 ctdb_service_needs_reconfigure ()
799 _ctdb_service_reconfigure_common
800 [ -e "$_ctdb_service_reconfigure_flag" ]
803 ctdb_service_set_reconfigure ()
805 _ctdb_service_reconfigure_common
806 : >"$_ctdb_service_reconfigure_flag"
809 ctdb_service_unset_reconfigure ()
811 _ctdb_service_reconfigure_common
812 rm -f "$_ctdb_service_reconfigure_flag"
815 ctdb_service_reconfigure ()
817 echo "Reconfiguring service \"${service_name}\"..."
818 ctdb_service_unset_reconfigure
819 service_reconfigure || return $?
820 # Intentionally have this use $service_name as default
821 # shellcheck disable=SC2119
825 # Default service_reconfigure() function does nothing.
826 service_reconfigure ()
831 # Default service_start() and service_stop() functions.
833 # These may be overridden in an eventscript.
836 service "$service_name" start
841 service "$service_name" stop
844 ##################################################################
846 # This exists only for backward compatibility with 3rd party scripts
848 ctdb_standard_event_handler ()
856 if [ "$_family" = "inet6" ] ; then
857 _iptables_cmd="ip6tables"
859 _iptables_cmd="iptables"
862 # iptables doesn't like being re-entered, so flock-wrap it.
863 flock -w 30 "${CTDB_SCRIPT_VARDIR}/iptables.flock" "$_iptables_cmd" "$@"
866 # AIX (and perhaps others?) doesn't have mktemp
867 # type is commonly supported and more portable than which(1)
868 # shellcheck disable=SC2039
869 if ! type mktemp >/dev/null 2>&1 ; then
873 if [ "$1" = "-d" ] ; then
878 _hex10=$(dd if=/dev/urandom count=20 2>/dev/null | \
880 sed -e 's@\(..........\).*@\1@')
881 _t="${_d}/tmp.${_hex10}"
894 ######################################################################
895 # NFS callout handling
901 if [ -z "$CTDB_NFS_CALLOUT" ] ; then
902 CTDB_NFS_CALLOUT="${CTDB_BASE}/nfs-linux-kernel-callout"
904 # Always export, for statd callout
905 export CTDB_NFS_CALLOUT
907 # If the callout wants to use this then it must create it
908 export CTDB_NFS_CALLOUT_STATE_DIR="${_state_dir}/callout-state"
910 # Export, if set, for use by clustered NFS callouts
911 if [ -n "$CTDB_NFS_STATE_FS_TYPE" ] ; then
912 export CTDB_NFS_STATE_FS_TYPE
914 if [ -n "$CTDB_NFS_STATE_MNT" ] ; then
915 export CTDB_NFS_STATE_MNT
918 nfs_callout_cache="${_state_dir}/nfs_callout_cache"
919 nfs_callout_cache_callout="${nfs_callout_cache}/CTDB_NFS_CALLOUT"
920 nfs_callout_cache_ops="${nfs_callout_cache}/ops"
923 nfs_callout_register ()
925 mkdir -p "$nfs_callout_cache_ops"
926 rm -f "$nfs_callout_cache_ops"/*
928 echo "$CTDB_NFS_CALLOUT" >"$nfs_callout_cache_callout"
930 _t=$(eval "$CTDB_NFS_CALLOUT" "register")
931 if [ -n "$_t" ] ; then
933 while IFS="" read _op ; do
934 touch "${nfs_callout_cache_ops}/${_op}"
937 touch "${nfs_callout_cache_ops}/ALL"
943 # Re-run registration if $CTDB_NFS_CALLOUT has changed
945 if [ -r "$nfs_callout_cache_callout" ] ; then
946 read _prev <"$nfs_callout_cache_callout"
948 if [ "$CTDB_NFS_CALLOUT" != "$_prev" ] ; then
952 # Run the operation if it is registered...
953 if [ -e "${nfs_callout_cache_ops}/${1}" ] || \
954 [ -e "${nfs_callout_cache_ops}/ALL" ]; then
955 eval "$CTDB_NFS_CALLOUT" "$@"
959 ########################################################
961 ########################################################
967 tickledir="${CTDB_SCRIPT_VARDIR}/tickles"
968 mkdir -p "$tickledir"
970 # What public IPs do I hold?
972 _ips=$($CTDB -X ip | awk -F'|' -v pnn="$_pnn" '$3 == pnn {print $2}')
974 # IPs and port as ss filters
976 for _ip in $_ips ; do
977 _ip_filter="${_ip_filter}${_ip_filter:+ || }src [${_ip}]"
979 _port_filter="sport == :${_port}"
981 # Record connections to our public IPs in a temporary file.
982 # This temporary file is in CTDB's private state directory and
983 # $$ is used to avoid a very rare race involving CTDB's script
984 # debugging. No security issue, nothing to see here...
985 _my_connections="${tickledir}/${_port}.connections.$$"
986 # Parentheses are needed around the filters for precedence but
987 # the parentheses can't be empty!
988 ss -tn state established \
989 "${_ip_filter:+( ${_ip_filter} )}" \
990 "${_port_filter:+( ${_port_filter} )}" |
991 awk 'NR > 1 {print $4, $3}' |
992 sort >"$_my_connections"
994 # Record our current tickles in a temporary file
995 _my_tickles="${tickledir}/${_port}.tickles.$$"
997 $CTDB -X gettickles "$_i" "$_port" |
998 awk -F'|' 'NR > 1 { printf "%s:%s %s:%s\n", $2, $3, $4, $5 }'
1000 sort >"$_my_tickles"
1002 # Add tickles for connections that we haven't already got tickles for
1003 comm -23 "$_my_connections" "$_my_tickles" | \
1006 # Remove tickles for connections that are no longer there
1007 comm -13 "$_my_connections" "$_my_tickles" | \
1010 rm -f "$_my_connections" "$_my_tickles"
1012 # Remove stale files from killed scripts
1013 # Files can't have spaces in name, more portable than -print0/-0
1014 # shellcheck disable=SC2038
1015 (cd "$tickledir" && find . -type f -mmin +10 | xargs -r rm)
1018 ########################################################
1019 # load a site local config file
1020 ########################################################
1022 [ -x "${CTDB_BASE}/rc.local" ] && {
1023 . "${CTDB_BASE}/rc.local"
1026 [ -d "${CTDB_BASE}/rc.local.d" ] && {
1027 for i in "${CTDB_BASE}/rc.local.d"/* ; do
1028 [ -x "$i" ] && . "$i"
1032 script_name="${0##*/}" # basename