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"
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/scripts"
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 ()
39 _opts_defaults="mode=700"
40 # Get any extra options specified after colon
41 if [ "$CTDB_DBDIR" = "tmpfs" ] ; then
44 _opts="${CTDB_DBDIR#tmpfs:}"
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"
54 # shellcheck disable=SC2034
55 CTDB_DBDIR_TMPFS_OPTIONS=""
62 foo="${service_config:-${service_name}}"
63 if [ -n "$foo" ] ; then
69 if [ "$1" != "ctdb" ] ; then
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"
85 if [ "$1" = "ctdb" ] ; then
86 _config="${CTDB_BASE}/ctdbd.conf"
87 if [ -r "$_config" ] ; then
98 ##############################################################
109 # Log given message or stdin to either syslog or a CTDB log file
110 # $1 is the tag passed to logger if syslog is in use.
115 case "$CTDB_LOGGING" in
117 if [ -n "$CTDB_LOGGING" ] ; then
118 _file="${CTDB_LOGGING#file:}"
120 _file="/usr/local/var/log/log.ctdb"
123 if [ -n "$*" ] ; then
131 # Handle all syslog:* variants here too. There's no tool to do
132 # the lossy things, so just use logger.
133 logger -t "ctdbd: ${_tag}" "$@"
138 # When things are run in the background in an eventscript then logging
139 # output might get lost. This is the "solution". :-)
140 background_with_logging ()
143 "$@" 2>&1 </dev/null |
144 script_log "${script_name}&"
150 ##############################################################
151 # check number of args for different events
157 echo "ERROR: must supply interface, IP and maskbits"
163 echo "ERROR: must supply old interface, new interface, IP and maskbits"
170 ##############################################################
171 # determine on what type of system (init style) we are running
174 # only do detection if not already set:
175 if [ -n "$CTDB_INIT_STYLE" ] ; then
179 if [ -x /sbin/startproc ]; then
180 CTDB_INIT_STYLE="suse"
181 elif [ -x /sbin/start-stop-daemon ]; then
182 CTDB_INIT_STYLE="debian"
184 CTDB_INIT_STYLE="redhat"
188 ######################################################
189 # simulate /sbin/service on platforms that don't have it
190 # _service() makes it easier to hook the service() function for
197 # do nothing, when no service was specified
198 [ -z "$_service_name" ] && return
200 if [ -x /sbin/service ]; then
201 $_nice /sbin/service "$_service_name" "$_op"
202 elif [ -x /usr/sbin/service ]; then
203 $_nice /usr/sbin/service "$_service_name" "$_op"
204 elif [ -x /bin/systemctl ]; then
205 $_nice /bin/systemctl "$_op" "$_service_name"
206 elif [ -x "${CTDB_SYS_ETCDIR}/init.d/${_service_name}" ]; then
207 $_nice "${CTDB_SYS_ETCDIR}/init.d/${_service_name}" "$_op"
208 elif [ -x "${CTDB_SYS_ETCDIR}/rc.d/init.d/${_service_name}" ]; then
209 $_nice "${CTDB_SYS_ETCDIR}/rc.d/init.d/${_service_name}" "$_op"
219 ######################################################
220 # simulate /sbin/service (niced) on platforms that don't have it
227 ######################################################
228 # Cached retrieval of PNN from local node. This never changes so why
229 # open a client connection to the server each time this is needed?
232 _pnn_file="${CTDB_SCRIPT_VARDIR}/my-pnn"
233 if [ ! -f "$_pnn_file" ] ; then
234 $CTDB pnn >"$_pnn_file"
240 # Cached retrieval of private IP address from local node. This never
242 ctdb_get_ip_address ()
244 _ip_addr_file="${CTDB_SCRIPT_VARDIR}/my-ip-address"
245 if [ ! -f "$_ip_addr_file" ] ; then
246 $CTDB -X nodestatus |
247 awk -F '|' 'NR == 2 { print $3 }' >"$_ip_addr_file"
250 # ip_address is used by caller
251 # shellcheck disable=SC2034
255 ######################################################
256 # wrapper around /proc/ settings to allow them to be hooked
258 # 1st arg is relative path under /proc/, 2nd arg is value to set
261 echo "$2" >"/proc/$1"
266 if [ -w "/proc/$1" ] ; then
271 ######################################################
272 # wrapper around getting file contents from /proc/ to allow
273 # this to be hooked for testing
274 # 1st arg is relative path under /proc/
280 ######################################################
281 # Print up to $_max kernel stack traces for processes named $_program
282 program_stack_traces ()
288 for _pid in $(pidof "$_prog") ; do
289 [ "$_count" -le "$_max" ] || break
291 # Do this first to avoid racing with process exit
292 _stack=$(get_proc "${_pid}/stack" 2>/dev/null)
293 if [ -n "$_stack" ] ; then
294 echo "Stack trace for ${_prog}[${_pid}]:"
296 _count=$((_count + 1))
301 ######################################################
302 # Ensure $service_name is set
303 assert_service_name ()
305 [ -n "$service_name" ] || die "INTERNAL ERROR: \$service_name not set"
308 ######################################################
309 # check a set of directories is available
310 # return 1 on a missing directory
311 # directories are read from stdin
312 ######################################################
313 ctdb_check_directories_probe()
315 while IFS="" read d ; do
321 [ -d "${d}/." ] || return 1
326 ######################################################
327 # check a set of directories is available
328 # directories are read from stdin
329 ######################################################
330 ctdb_check_directories()
332 ctdb_check_directories_probe || {
333 echo "ERROR: $service_name directory \"$d\" not available"
338 ######################################################
339 # check a set of tcp ports
340 # usage: ctdb_check_tcp_ports <ports...>
341 ######################################################
343 # Check whether something is listening on all of the given TCP ports
344 # using the "ctdb checktcpport" command.
345 ctdb_check_tcp_ports()
347 if [ -z "$1" ] ; then
348 echo "INTERNAL ERROR: ctdb_check_tcp_ports - no ports specified"
352 for _p ; do # process each function argument (port)
353 _cmd="$CTDB checktcpport $_p"
358 echo "$service_name not listening on TCP port $_p"
362 # Couldn't bind, something already listening, next port
366 echo "unexpected error (${_ret}) running \"${_cmd}\""
367 if [ -n "$_out" ] ; then
375 # All ports listening
379 ######################################################
380 # check a unix socket
381 # usage: ctdb_check_unix_socket SOCKPATH
382 ######################################################
383 ctdb_check_unix_socket()
387 if [ -z "$_sockpath" ] ; then
388 echo "ERROR: ctdb_check_unix_socket() requires socket path"
392 _out=$(ss -l -x "src ${_sockpath}" | tail -n +2)
393 if [ -z "$_out" ] ; then
394 echo "ERROR: ${service_name} not listening on ${_sockpath}"
399 ################################################
400 # kill off any TCP connections with the given IP
401 ################################################
402 kill_tcp_connections ()
408 if [ "$3" = "oneway" ] ; then
412 get_tcp_connections_for_ip "$_ip" | {
417 while read _dst _src; do
418 _destport="${_dst##*:}"
421 # we only do one-way killtcp for CIFS
422 139|445) __oneway=true ;;
425 _connections="${_connections}${_nl}${_src} ${_dst}"
426 if ! $__oneway ; then
427 _connections="${_connections}${_nl}${_dst} ${_src}"
430 _killcount=$((_killcount + 1))
433 if [ $_killcount -eq 0 ] ; then
437 echo "$_connections" | \
438 "${CTDB_HELPER_BINDIR}/ctdb_killtcp" "$_iface" || {
439 echo "Failed to kill TCP connections"
443 _connections=$(get_tcp_connections_for_ip "$_ip")
444 if [ -z "$_connections" ] ; then
447 _remaining=$(echo "$_connections" | wc -l)
450 _actually_killed=$((_killcount - _remaining))
452 _t="${_actually_killed}/${_killcount}"
453 echo "Killed ${_t} TCP connections to released IP $_ip"
455 if [ -n "$_connections" ] ; then
456 echo "Remaining connections:"
457 echo "$_connections" | sed -e 's|^| |'
462 ##################################################################
463 # kill off the local end for any TCP connections with the given IP
464 ##################################################################
465 kill_tcp_connections_local_only ()
467 kill_tcp_connections "$@" "oneway"
470 ##################################################################
471 # tickle any TCP connections with the given IP
472 ##################################################################
473 tickle_tcp_connections ()
477 # Get connections, both directions
478 _conns=$(get_tcp_connections_for_ip "$_ip" | \
479 awk '{ print $1, $2 ; print $2, $1 }')
481 echo "$_conns" | awk '{ print "Tickle TCP connection", $1, $2 }'
482 echo "$_conns" | ctdb tickle
485 get_tcp_connections_for_ip ()
489 ss -tn state established "src [$_ip]" | awk 'NR > 1 {print $3, $4}'
492 ########################################################
500 # Ensure interface is up
501 ip link set "$_iface" up || \
502 die "Failed to bringup interface $_iface"
504 # Only need to define broadcast for IPv4
510 # Intentionally unquoted multi-word value here
511 # shellcheck disable=SC2086
512 ip addr add "$_ip/$_maskbits" $_bcast dev "$_iface" || {
513 echo "Failed to add $_ip/$_maskbits on dev $_iface"
517 # Wait 5 seconds for IPv6 addresses to stop being tentative...
518 if [ -z "$_bcast" ] ; then
519 for _x in $(seq 1 10) ; do
520 ip addr show to "${_ip}/128" | grep -q "tentative" || break
524 # If the address was a duplicate then it won't be on the
525 # interface so flag an error.
526 _t=$(ip addr show to "${_ip}/128")
529 echo "Failed to add $_ip/$_maskbits on dev $_iface"
532 *tentative*|*dadfailed*)
533 echo "Failed to add $_ip/$_maskbits on dev $_iface"
534 ip addr del "$_ip/$_maskbits" dev "$_iface"
541 delete_ip_from_iface()
547 # This could be set globally for all interfaces but it is probably
548 # better to avoid surprises, so limit it the interfaces where CTDB
549 # has public IP addresses. There isn't anywhere else convenient
550 # to do this so just set it each time. This is much cheaper than
551 # remembering and re-adding secondaries.
552 set_proc "sys/net/ipv4/conf/${_iface}/promote_secondaries" 1
554 ip addr del "$_ip/$_maskbits" dev "$_iface" || {
555 echo "Failed to del $_ip on dev $_iface"
560 # If the given IP is hosted then print 2 items: maskbits and iface
569 ip addr show to "${_addr}/${_bits}" 2>/dev/null | \
570 awk 'NR == 1 { iface = $2; sub(":$", "", iface) ;
571 sub("@.*", "", iface) }
572 $1 ~ /inet/ { mask = $2; sub(".*/", "", mask);
578 _addr="${1%/*}" # Remove optional maskbits
580 # Intentional word splitting here
581 # shellcheck disable=SC2046
582 set -- $(ip_maskbits_iface "$_addr")
583 if [ -n "$1" ] ; then
586 echo "Removing public address $_addr/$_maskbits from device $_iface"
587 delete_ip_from_iface "$_iface" "$_addr" "$_maskbits" >/dev/null 2>&1
591 drop_all_public_ips ()
593 # _x is intentionally ignored
594 # shellcheck disable=SC2034
595 while read _ip _x ; do
597 done <"${CTDB_BASE}/public_addresses"
602 set_proc_maybe sys/net/ipv4/route/flush 1
603 set_proc_maybe sys/net/ipv6/route/flush 1
606 ########################################################
607 # Interface monitoring
609 # If the interface is a virtual one (e.g. VLAN) then get the
610 # underlying interface
611 interface_get_real ()
613 # Output of "ip link show <iface>"
616 # Extract the full interface description to see if it is a VLAN
617 _t=$(echo "$_iface_info" |
618 awk 'NR == 1 { iface = $2; sub(":$", "", iface) ;
622 # VLAN: use the underlying interface, after the '@'
626 # Not a regular VLAN. For backward compatibility, assume
627 # there is some other sort of VLAN that doesn't have the
628 # '@' in the output and only use what is before a '.'. If
629 # there is no '.' then this will be the whole interface
635 # Check whether an interface is operational
640 _iface_info=$(ip link show "$_iface" 2>&1) || {
641 echo "ERROR: Monitored interface ${_iface} does not exist"
646 # If the interface is a virtual one (e.g. VLAN) then get the
647 # underlying interface.
648 _realiface=$(interface_get_real "$_iface_info")
650 if _bi=$(get_proc "net/bonding/${_realiface}" 2>/dev/null) ; then
651 # This is a bond: various monitoring strategies
652 echo "$_bi" | grep -q 'Currently Active Slave: None' && {
653 echo "ERROR: No active slaves for bond device ${_realiface}"
656 echo "$_bi" | grep -q '^MII Status: up' || {
657 echo "ERROR: public network interface ${_realiface} is down"
660 echo "$_bi" | grep -q '^Bonding Mode: IEEE 802.3ad Dynamic link aggregation' && {
661 # This works around a bug in the driver where the
662 # overall bond status can be up but none of the actual
663 # physical interfaces have a link.
664 echo "$_bi" | grep 'MII Status:' | tail -n +2 | grep -q '^MII Status: up' || {
665 echo "ERROR: No active slaves for 802.ad bond device ${_realiface}"
675 # loopback is always working
679 # we don't know how to test ib links
683 ethtool "$_iface" | grep -q 'Link detected: yes' || {
684 # On some systems, this is not successful when a
685 # cable is plugged but the interface has not been
686 # brought up previously. Bring the interface up
688 ip link set "$_iface" up
689 ethtool "$_iface" | grep -q 'Link detected: yes' || {
690 echo "ERROR: No link on the public network interface ${_iface}"
700 ########################################################
702 _ctdb_counter_common ()
704 [ $# -le 1 ] || die "usage: _ctdb_counter_common [name]"
706 if [ $# -eq 1 ] ; then
707 _counter_name="${1}.failcount"
709 _counter_name="failcount"
712 if [ -z "$script_state_dir" ] ; then
713 die "ctdb_counter_* functions need ctdb_setup_state_dir()"
716 _counter_file="${script_state_dir}/${_counter_name}"
718 # Some code passes an argument
719 # shellcheck disable=SC2120
720 ctdb_counter_init () {
721 _ctdb_counter_common "$1"
725 ctdb_counter_incr () {
726 _ctdb_counter_common "$1"
728 # unary counting using newlines!
729 echo >>"$_counter_file"
731 ctdb_counter_get () {
732 _ctdb_counter_common "$1"
734 stat -c "%s" "$_counter_file" 2>/dev/null || echo 0
737 ########################################################
739 # ctdb_setup_state_dir <type> <name>
740 # Sets/creates script_state_dir)
741 ctdb_setup_state_dir ()
743 [ $# -eq 2 ] || die "usage: ctdb_setup_state_dir <type> <name>"
748 script_state_dir="${CTDB_SCRIPT_VARDIR}/${_type}/${_name}"
750 mkdir -p "$script_state_dir" || \
751 die "Error creating script state dir \"${script_state_dir}\""
754 ##################################################################
755 # Reconfigure a service on demand
757 _ctdb_service_reconfigure_common ()
759 if [ -z "$script_state_dir" ] ; then
760 die "ctdb_service_*_reconfigure() needs ctdb_setup_state_dir()"
763 _ctdb_service_reconfigure_flag="${script_state_dir}/need_reconfigure"
766 ctdb_service_needs_reconfigure ()
768 _ctdb_service_reconfigure_common
769 [ -e "$_ctdb_service_reconfigure_flag" ]
772 ctdb_service_set_reconfigure ()
774 _ctdb_service_reconfigure_common
775 : >"$_ctdb_service_reconfigure_flag"
778 ctdb_service_unset_reconfigure ()
780 _ctdb_service_reconfigure_common
781 rm -f "$_ctdb_service_reconfigure_flag"
784 ctdb_service_reconfigure ()
786 echo "Reconfiguring service \"${service_name}\"..."
787 ctdb_service_unset_reconfigure
788 service_reconfigure || return $?
789 # Intentionally have this use $service_name as default
790 # shellcheck disable=SC2119
794 # Default service_reconfigure() function does nothing.
795 service_reconfigure ()
800 # Default service_start() and service_stop() functions.
802 # These may be overridden in an eventscript.
805 service "$service_name" start
810 service "$service_name" stop
813 ##################################################################
815 # This exists only for backward compatibility with 3rd party scripts
817 ctdb_standard_event_handler ()
825 if [ "$_family" = "inet6" ] ; then
826 _iptables_cmd="ip6tables"
828 _iptables_cmd="iptables"
831 # iptables doesn't like being re-entered, so flock-wrap it.
832 flock -w 30 "${CTDB_SCRIPT_VARDIR}/iptables.flock" "$_iptables_cmd" "$@"
835 # AIX (and perhaps others?) doesn't have mktemp
836 # type is commonly supported and more portable than which(1)
837 # shellcheck disable=SC2039
838 if ! type mktemp >/dev/null 2>&1 ; then
842 if [ "$1" = "-d" ] ; then
847 _hex10=$(dd if=/dev/urandom count=20 2>/dev/null | \
849 sed -e 's@\(..........\).*@\1@')
850 _t="${_d}/tmp.${_hex10}"
863 ######################################################################
864 # NFS callout handling
870 if [ -z "$CTDB_NFS_CALLOUT" ] ; then
871 CTDB_NFS_CALLOUT="${CTDB_BASE}/nfs-linux-kernel-callout"
873 # Always export, for statd callout
874 export CTDB_NFS_CALLOUT
876 # If the callout wants to use this then it must create it
877 export CTDB_NFS_CALLOUT_STATE_DIR="${_state_dir}/callout-state"
879 # Export, if set, for use by clustered NFS callouts
880 if [ -n "$CTDB_NFS_STATE_FS_TYPE" ] ; then
881 export CTDB_NFS_STATE_FS_TYPE
883 if [ -n "$CTDB_NFS_STATE_MNT" ] ; then
884 export CTDB_NFS_STATE_MNT
887 nfs_callout_cache="${_state_dir}/nfs_callout_cache"
888 nfs_callout_cache_callout="${nfs_callout_cache}/CTDB_NFS_CALLOUT"
889 nfs_callout_cache_ops="${nfs_callout_cache}/ops"
892 nfs_callout_register ()
894 mkdir -p "$nfs_callout_cache_ops"
895 rm -f "$nfs_callout_cache_ops"/*
897 echo "$CTDB_NFS_CALLOUT" >"$nfs_callout_cache_callout"
899 _t=$(eval "$CTDB_NFS_CALLOUT" "register")
900 if [ -n "$_t" ] ; then
902 while IFS="" read _op ; do
903 touch "${nfs_callout_cache_ops}/${_op}"
906 touch "${nfs_callout_cache_ops}/ALL"
912 # Re-run registration if $CTDB_NFS_CALLOUT has changed
914 if [ -r "$nfs_callout_cache_callout" ] ; then
915 read _prev <"$nfs_callout_cache_callout"
917 if [ "$CTDB_NFS_CALLOUT" != "$_prev" ] ; then
921 # Run the operation if it is registered...
922 if [ -e "${nfs_callout_cache_ops}/${1}" ] || \
923 [ -e "${nfs_callout_cache_ops}/ALL" ]; then
924 eval "$CTDB_NFS_CALLOUT" "$@"
928 ########################################################
930 ########################################################
936 tickledir="${CTDB_SCRIPT_VARDIR}/tickles"
937 mkdir -p "$tickledir"
939 # What public IPs do I hold?
941 _ips=$($CTDB -X ip | awk -F'|' -v pnn="$_pnn" '$3 == pnn {print $2}')
943 # IPs and port as ss filters
945 for _ip in $_ips ; do
946 _ip_filter="${_ip_filter}${_ip_filter:+ || }src [${_ip}]"
948 _port_filter="sport == :${_port}"
950 # Record connections to our public IPs in a temporary file.
951 # This temporary file is in CTDB's private state directory and
952 # $$ is used to avoid a very rare race involving CTDB's script
953 # debugging. No security issue, nothing to see here...
954 _my_connections="${tickledir}/${_port}.connections.$$"
955 # Parentheses are needed around the filters for precedence but
956 # the parentheses can't be empty!
957 ss -tn state established \
958 "${_ip_filter:+( ${_ip_filter} )}" \
959 "${_port_filter:+( ${_port_filter} )}" |
960 awk 'NR > 1 {print $4, $3}' |
961 sort >"$_my_connections"
963 # Record our current tickles in a temporary file
964 _my_tickles="${tickledir}/${_port}.tickles.$$"
966 $CTDB -X gettickles "$_i" "$_port" |
967 awk -F'|' 'NR > 1 { printf "%s:%s %s:%s\n", $2, $3, $4, $5 }'
971 # Add tickles for connections that we haven't already got tickles for
972 comm -23 "$_my_connections" "$_my_tickles" | \
975 # Remove tickles for connections that are no longer there
976 comm -13 "$_my_connections" "$_my_tickles" | \
979 rm -f "$_my_connections" "$_my_tickles"
981 # Remove stale files from killed scripts
982 # Files can't have spaces in name, more portable than -print0/-0
983 # shellcheck disable=SC2038
984 (cd "$tickledir" && find . -type f -mmin +10 | xargs -r rm)
987 ########################################################
988 # load a site local config file
989 ########################################################
991 [ -n "$CTDB_RC_LOCAL" -a -x "$CTDB_RC_LOCAL" ] && {
995 [ -x "${CTDB_BASE}/rc.local" ] && {
996 . "${CTDB_BASE}/rc.local"
999 [ -d "${CTDB_BASE}/rc.local.d" ] && {
1000 for i in "${CTDB_BASE}/rc.local.d"/* ; do
1001 [ -x "$i" ] && . "$i"
1005 script_name="${0##*/}" # basename