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"
47 # load_script_options [ component script ]
48 # script is an event script name relative to a component
49 # component is currently ignored
50 load_script_options ()
52 if [ $# -eq 2 ] ; then
54 elif [ $# -eq 0 ] ; then
57 die "usage: load_script_options [ component script ]"
60 _options="${CTDB_BASE}/script.options"
62 if [ -r "$_options" ] ; then
66 if [ -n "$_script" ] ; then
67 _s="${CTDB_BASE}/events/legacy/${_script}"
71 _options="${_s}.options"
73 if [ -r "$_options" ] ; then
78 ##############################################################
89 # Log given message or stdin to either syslog or a CTDB log file
90 # $1 is the tag passed to logger if syslog is in use.
95 case "$CTDB_LOGGING" in
97 if [ -n "$CTDB_LOGGING" ] ; then
98 _file="${CTDB_LOGGING#file:}"
100 _file="/usr/local/var/log/log.ctdb"
103 if [ -n "$*" ] ; then
111 # Handle all syslog:* variants here too. There's no tool to do
112 # the lossy things, so just use logger.
113 logger -t "ctdbd: ${_tag}" "$@"
118 # When things are run in the background in an eventscript then logging
119 # output might get lost. This is the "solution". :-)
120 background_with_logging ()
123 "$@" 2>&1 </dev/null |
124 script_log "${script_name}&"
130 ##############################################################
131 # check number of args for different events
137 echo "ERROR: must supply interface, IP and maskbits"
143 echo "ERROR: must supply old interface, new interface, IP and maskbits"
150 ##############################################################
151 # determine on what type of system (init style) we are running
154 # only do detection if not already set:
155 if [ -n "$CTDB_INIT_STYLE" ] ; then
159 if [ -x /sbin/startproc ]; then
160 CTDB_INIT_STYLE="suse"
161 elif [ -x /sbin/start-stop-daemon ]; then
162 CTDB_INIT_STYLE="debian"
164 CTDB_INIT_STYLE="redhat"
168 ######################################################
169 # simulate /sbin/service on platforms that don't have it
170 # _service() makes it easier to hook the service() function for
177 # do nothing, when no service was specified
178 [ -z "$_service_name" ] && return
180 if [ -x /sbin/service ]; then
181 $_nice /sbin/service "$_service_name" "$_op"
182 elif [ -x /usr/sbin/service ]; then
183 $_nice /usr/sbin/service "$_service_name" "$_op"
184 elif [ -x /bin/systemctl ]; then
185 $_nice /bin/systemctl "$_op" "$_service_name"
186 elif [ -x "${CTDB_SYS_ETCDIR}/init.d/${_service_name}" ]; then
187 $_nice "${CTDB_SYS_ETCDIR}/init.d/${_service_name}" "$_op"
188 elif [ -x "${CTDB_SYS_ETCDIR}/rc.d/init.d/${_service_name}" ]; then
189 $_nice "${CTDB_SYS_ETCDIR}/rc.d/init.d/${_service_name}" "$_op"
199 ######################################################
200 # simulate /sbin/service (niced) on platforms that don't have it
207 ######################################################
208 # Cached retrieval of PNN from local node. This never changes so why
209 # open a client connection to the server each time this is needed?
212 _pnn_file="${CTDB_SCRIPT_VARDIR}/my-pnn"
213 if [ ! -f "$_pnn_file" ] ; then
214 $CTDB pnn >"$_pnn_file"
220 # Cached retrieval of private IP address from local node. This never
222 ctdb_get_ip_address ()
224 _ip_addr_file="${CTDB_SCRIPT_VARDIR}/my-ip-address"
225 if [ ! -f "$_ip_addr_file" ] ; then
226 $CTDB -X nodestatus |
227 awk -F '|' 'NR == 2 { print $3 }' >"$_ip_addr_file"
230 # ip_address is used by caller
231 # shellcheck disable=SC2034
235 # Cached retrieval of database options for use by event scripts.
237 # If the variables are already set then they should not be overwritten
238 # - this should only happen during event script testing.
239 ctdb_get_db_options ()
241 _db_opts_file="${CTDB_SCRIPT_VARDIR}/db_options.cache"
243 if [ ! -f "$_db_opts_file" ] ; then
245 ctdb_translate_option "database" \
246 "volatile database directory" \
248 ctdb_translate_option "database" \
249 "persistent database directory" \
250 "CTDB_DBDIR_PERSISTENT"
251 ctdb_translate_option "database" \
252 "state database directory" \
260 ctdb_translate_option ()
266 # ctdb-config already prints an error if something goes wrong
267 _t=$("${CTDB_HELPER_BINDIR}/ctdb-config" get "$_section" "$_opt") || \
269 echo "${_variable}=\"${_t}\""
272 ######################################################
273 # wrapper around /proc/ settings to allow them to be hooked
275 # 1st arg is relative path under /proc/, 2nd arg is value to set
278 echo "$2" >"/proc/$1"
283 if [ -w "/proc/$1" ] ; then
288 ######################################################
289 # wrapper around getting file contents from /proc/ to allow
290 # this to be hooked for testing
291 # 1st arg is relative path under /proc/
297 ######################################################
298 # Print up to $_max kernel stack traces for processes named $_program
299 program_stack_traces ()
305 for _pid in $(pidof "$_prog") ; do
306 [ "$_count" -le "$_max" ] || break
308 # Do this first to avoid racing with process exit
309 _stack=$(get_proc "${_pid}/stack" 2>/dev/null)
310 if [ -n "$_stack" ] ; then
311 echo "Stack trace for ${_prog}[${_pid}]:"
313 _count=$((_count + 1))
318 ######################################################
319 # Ensure $service_name is set
320 assert_service_name ()
322 # service_name is set by the event script
323 # shellcheck disable=SC2154
324 [ -n "$service_name" ] || die "INTERNAL ERROR: \$service_name not set"
327 ######################################################
328 # check a set of directories is available
329 # return 1 on a missing directory
330 # directories are read from stdin
331 ######################################################
332 ctdb_check_directories_probe()
334 while IFS="" read d ; do
340 [ -d "${d}/." ] || return 1
345 ######################################################
346 # check a set of directories is available
347 # directories are read from stdin
348 ######################################################
349 ctdb_check_directories()
351 ctdb_check_directories_probe || {
352 echo "ERROR: $service_name directory \"$d\" not available"
357 ######################################################
358 # check a set of tcp ports
359 # usage: ctdb_check_tcp_ports <ports...>
360 ######################################################
362 # Check whether something is listening on all of the given TCP ports
363 # using the "ctdb checktcpport" command.
364 ctdb_check_tcp_ports()
366 if [ -z "$1" ] ; then
367 echo "INTERNAL ERROR: ctdb_check_tcp_ports - no ports specified"
371 for _p ; do # process each function argument (port)
372 _cmd="$CTDB checktcpport $_p"
377 echo "$service_name not listening on TCP port $_p"
381 # Couldn't bind, something already listening, next port
385 echo "unexpected error (${_ret}) running \"${_cmd}\""
386 if [ -n "$_out" ] ; then
394 # All ports listening
398 ######################################################
399 # check a unix socket
400 # usage: ctdb_check_unix_socket SOCKPATH
401 ######################################################
402 ctdb_check_unix_socket()
406 if [ -z "$_sockpath" ] ; then
407 echo "ERROR: ctdb_check_unix_socket() requires socket path"
411 _out=$(ss -l -x "src ${_sockpath}" | tail -n +2)
412 if [ -z "$_out" ] ; then
413 echo "ERROR: ${service_name} not listening on ${_sockpath}"
418 ################################################
419 # kill off any TCP connections with the given IP
420 ################################################
421 kill_tcp_connections ()
427 if [ "$3" = "oneway" ] ; then
431 get_tcp_connections_for_ip "$_ip" | {
436 while read _dst _src; do
437 _destport="${_dst##*:}"
440 # we only do one-way killtcp for CIFS
441 139|445) __oneway=true ;;
444 _connections="${_connections}${_nl}${_src} ${_dst}"
445 if ! $__oneway ; then
446 _connections="${_connections}${_nl}${_dst} ${_src}"
449 _killcount=$((_killcount + 1))
452 if [ $_killcount -eq 0 ] ; then
456 echo "$_connections" | \
457 "${CTDB_HELPER_BINDIR}/ctdb_killtcp" "$_iface" || {
458 echo "Failed to kill TCP connections"
462 _connections=$(get_tcp_connections_for_ip "$_ip")
463 if [ -z "$_connections" ] ; then
466 _remaining=$(echo "$_connections" | wc -l)
469 _actually_killed=$((_killcount - _remaining))
471 _t="${_actually_killed}/${_killcount}"
472 echo "Killed ${_t} TCP connections to released IP $_ip"
474 if [ -n "$_connections" ] ; then
475 echo "Remaining connections:"
476 echo "$_connections" | sed -e 's|^| |'
481 ##################################################################
482 # kill off the local end for any TCP connections with the given IP
483 ##################################################################
484 kill_tcp_connections_local_only ()
486 kill_tcp_connections "$@" "oneway"
489 ##################################################################
490 # tickle any TCP connections with the given IP
491 ##################################################################
492 tickle_tcp_connections ()
496 # Get connections, both directions
497 _conns=$(get_tcp_connections_for_ip "$_ip" | \
498 awk '{ print $1, $2 ; print $2, $1 }')
500 echo "$_conns" | awk '{ print "Tickle TCP connection", $1, $2 }'
501 echo "$_conns" | ctdb tickle
504 get_tcp_connections_for_ip ()
508 ss -tn state established "src [$_ip]" | awk 'NR > 1 {print $3, $4}'
511 ########################################################
519 # Ensure interface is up
520 ip link set "$_iface" up || \
521 die "Failed to bringup interface $_iface"
523 # Only need to define broadcast for IPv4
529 # Intentionally unquoted multi-word value here
530 # shellcheck disable=SC2086
531 ip addr add "$_ip/$_maskbits" $_bcast dev "$_iface" || {
532 echo "Failed to add $_ip/$_maskbits on dev $_iface"
536 # Wait 5 seconds for IPv6 addresses to stop being tentative...
537 if [ -z "$_bcast" ] ; then
538 for _x in $(seq 1 10) ; do
539 ip addr show to "${_ip}/128" | grep -q "tentative" || break
543 # If the address was a duplicate then it won't be on the
544 # interface so flag an error.
545 _t=$(ip addr show to "${_ip}/128")
548 echo "Failed to add $_ip/$_maskbits on dev $_iface"
551 *tentative*|*dadfailed*)
552 echo "Failed to add $_ip/$_maskbits on dev $_iface"
553 ip addr del "$_ip/$_maskbits" dev "$_iface"
560 delete_ip_from_iface()
566 # This could be set globally for all interfaces but it is probably
567 # better to avoid surprises, so limit it the interfaces where CTDB
568 # has public IP addresses. There isn't anywhere else convenient
569 # to do this so just set it each time. This is much cheaper than
570 # remembering and re-adding secondaries.
571 set_proc "sys/net/ipv4/conf/${_iface}/promote_secondaries" 1
573 ip addr del "$_ip/$_maskbits" dev "$_iface" || {
574 echo "Failed to del $_ip on dev $_iface"
579 # If the given IP is hosted then print 2 items: maskbits and iface
588 ip addr show to "${_addr}/${_bits}" 2>/dev/null | \
589 awk 'NR == 1 { iface = $2; sub(":$", "", iface) ;
590 sub("@.*", "", iface) }
591 $1 ~ /inet/ { mask = $2; sub(".*/", "", mask);
597 _addr="${1%/*}" # Remove optional maskbits
599 # Intentional word splitting here
600 # shellcheck disable=SC2046
601 set -- $(ip_maskbits_iface "$_addr")
602 if [ -n "$1" ] ; then
605 echo "Removing public address $_addr/$_maskbits from device $_iface"
606 delete_ip_from_iface "$_iface" "$_addr" "$_maskbits" >/dev/null 2>&1
610 drop_all_public_ips ()
612 # _x is intentionally ignored
613 # shellcheck disable=SC2034
614 while read _ip _x ; do
616 done <"${CTDB_BASE}/public_addresses"
621 set_proc_maybe sys/net/ipv4/route/flush 1
622 set_proc_maybe sys/net/ipv6/route/flush 1
625 ########################################################
626 # Interface monitoring
628 # If the interface is a virtual one (e.g. VLAN) then get the
629 # underlying interface
630 interface_get_real ()
632 # Output of "ip link show <iface>"
635 # Extract the full interface description to see if it is a VLAN
636 _t=$(echo "$_iface_info" |
637 awk 'NR == 1 { iface = $2; sub(":$", "", iface) ;
641 # VLAN: use the underlying interface, after the '@'
645 # Not a regular VLAN. For backward compatibility, assume
646 # there is some other sort of VLAN that doesn't have the
647 # '@' in the output and only use what is before a '.'. If
648 # there is no '.' then this will be the whole interface
654 # Check whether an interface is operational
659 _iface_info=$(ip link show "$_iface" 2>&1) || {
660 echo "ERROR: Monitored interface ${_iface} does not exist"
665 # If the interface is a virtual one (e.g. VLAN) then get the
666 # underlying interface.
667 _realiface=$(interface_get_real "$_iface_info")
669 if _bi=$(get_proc "net/bonding/${_realiface}" 2>/dev/null) ; then
670 # This is a bond: various monitoring strategies
671 echo "$_bi" | grep -q 'Currently Active Slave: None' && {
672 echo "ERROR: No active slaves for bond device ${_realiface}"
675 echo "$_bi" | grep -q '^MII Status: up' || {
676 echo "ERROR: public network interface ${_realiface} is down"
679 echo "$_bi" | grep -q '^Bonding Mode: IEEE 802.3ad Dynamic link aggregation' && {
680 # This works around a bug in the driver where the
681 # overall bond status can be up but none of the actual
682 # physical interfaces have a link.
683 echo "$_bi" | grep 'MII Status:' | tail -n +2 | grep -q '^MII Status: up' || {
684 echo "ERROR: No active slaves for 802.ad bond device ${_realiface}"
694 # loopback is always working
698 # we don't know how to test ib links
702 ethtool "$_iface" | grep -q 'Link detected: yes' || {
703 # On some systems, this is not successful when a
704 # cable is plugged but the interface has not been
705 # brought up previously. Bring the interface up
707 ip link set "$_iface" up
708 ethtool "$_iface" | grep -q 'Link detected: yes' || {
709 echo "ERROR: No link on the public network interface ${_iface}"
719 ########################################################
721 _ctdb_counter_common ()
723 [ $# -le 1 ] || die "usage: _ctdb_counter_common [name]"
725 if [ $# -eq 1 ] ; then
726 _counter_name="${1}.failcount"
728 _counter_name="failcount"
731 if [ -z "$script_state_dir" ] ; then
732 die "ctdb_counter_* functions need ctdb_setup_state_dir()"
735 _counter_file="${script_state_dir}/${_counter_name}"
737 # Some code passes an argument
738 # shellcheck disable=SC2120
739 ctdb_counter_init () {
740 _ctdb_counter_common "$1"
744 ctdb_counter_incr () {
745 _ctdb_counter_common "$1"
747 # unary counting using newlines!
748 echo >>"$_counter_file"
750 ctdb_counter_get () {
751 _ctdb_counter_common "$1"
753 _val=$(wc -c < "$_counter_file" 2>/dev/null || echo 0)
754 # Strip leading spaces from ouput of wc (on freebsd)
755 # shellcheck disable=SC2086
759 ########################################################
761 # ctdb_setup_state_dir <type> <name>
762 # Sets/creates script_state_dir)
763 ctdb_setup_state_dir ()
765 [ $# -eq 2 ] || die "usage: ctdb_setup_state_dir <type> <name>"
770 script_state_dir="${CTDB_SCRIPT_VARDIR}/${_type}/${_name}"
772 mkdir -p "$script_state_dir" || \
773 die "Error creating script state dir \"${script_state_dir}\""
776 ##################################################################
777 # Reconfigure a service on demand
779 _ctdb_service_reconfigure_common ()
781 if [ -z "$script_state_dir" ] ; then
782 die "ctdb_service_*_reconfigure() needs ctdb_setup_state_dir()"
785 _ctdb_service_reconfigure_flag="${script_state_dir}/need_reconfigure"
788 ctdb_service_needs_reconfigure ()
790 _ctdb_service_reconfigure_common
791 [ -e "$_ctdb_service_reconfigure_flag" ]
794 ctdb_service_set_reconfigure ()
796 _ctdb_service_reconfigure_common
797 : >"$_ctdb_service_reconfigure_flag"
800 ctdb_service_unset_reconfigure ()
802 _ctdb_service_reconfigure_common
803 rm -f "$_ctdb_service_reconfigure_flag"
806 ctdb_service_reconfigure ()
808 echo "Reconfiguring service \"${service_name}\"..."
809 ctdb_service_unset_reconfigure
810 service_reconfigure || return $?
811 # Intentionally have this use $service_name as default
812 # shellcheck disable=SC2119
816 # Default service_reconfigure() function does nothing.
817 service_reconfigure ()
822 # Default service_start() and service_stop() functions.
824 # These may be overridden in an eventscript.
827 service "$service_name" start
832 service "$service_name" stop
835 ##################################################################
837 # This exists only for backward compatibility with 3rd party scripts
839 ctdb_standard_event_handler ()
847 if [ "$_family" = "inet6" ] ; then
848 _iptables_cmd="ip6tables"
850 _iptables_cmd="iptables"
853 # iptables doesn't like being re-entered, so flock-wrap it.
854 flock -w 30 "${CTDB_SCRIPT_VARDIR}/iptables.flock" "$_iptables_cmd" "$@"
857 # AIX (and perhaps others?) doesn't have mktemp
858 # type is commonly supported and more portable than which(1)
859 # shellcheck disable=SC2039
860 if ! type mktemp >/dev/null 2>&1 ; then
864 if [ "$1" = "-d" ] ; then
869 _hex10=$(dd if=/dev/urandom count=20 2>/dev/null | \
872 _t="${_d}/tmp.${_hex10}"
885 ######################################################################
886 # NFS callout handling
892 if [ -z "$CTDB_NFS_CALLOUT" ] ; then
893 CTDB_NFS_CALLOUT="${CTDB_BASE}/nfs-linux-kernel-callout"
895 # Always export, for statd callout
896 export CTDB_NFS_CALLOUT
898 # If the callout wants to use this then it must create it
899 export CTDB_NFS_CALLOUT_STATE_DIR="${_state_dir}/callout-state"
901 # Export, if set, for use by clustered NFS callouts
902 if [ -n "$CTDB_NFS_STATE_FS_TYPE" ] ; then
903 export CTDB_NFS_STATE_FS_TYPE
905 if [ -n "$CTDB_NFS_STATE_MNT" ] ; then
906 export CTDB_NFS_STATE_MNT
909 nfs_callout_cache="${_state_dir}/nfs_callout_cache"
910 nfs_callout_cache_callout="${nfs_callout_cache}/CTDB_NFS_CALLOUT"
911 nfs_callout_cache_ops="${nfs_callout_cache}/ops"
914 nfs_callout_register ()
916 mkdir -p "$nfs_callout_cache_ops"
917 rm -f "$nfs_callout_cache_ops"/*
919 echo "$CTDB_NFS_CALLOUT" >"$nfs_callout_cache_callout"
921 _t=$(eval "$CTDB_NFS_CALLOUT" "register")
922 if [ -n "$_t" ] ; then
924 while IFS="" read _op ; do
925 touch "${nfs_callout_cache_ops}/${_op}"
928 touch "${nfs_callout_cache_ops}/ALL"
934 # Re-run registration if $CTDB_NFS_CALLOUT has changed
936 if [ -r "$nfs_callout_cache_callout" ] ; then
937 read _prev <"$nfs_callout_cache_callout"
939 if [ "$CTDB_NFS_CALLOUT" != "$_prev" ] ; then
943 # Run the operation if it is registered...
944 if [ -e "${nfs_callout_cache_ops}/${1}" ] || \
945 [ -e "${nfs_callout_cache_ops}/ALL" ]; then
946 eval "$CTDB_NFS_CALLOUT" "$@"
950 ########################################################
952 ########################################################
958 tickledir="${CTDB_SCRIPT_VARDIR}/tickles"
959 mkdir -p "$tickledir"
961 # What public IPs do I hold?
963 _ips=$($CTDB -X ip | awk -F'|' -v pnn="$_pnn" '$3 == pnn {print $2}')
965 # IPs and port as ss filters
967 for _ip in $_ips ; do
968 _ip_filter="${_ip_filter}${_ip_filter:+ || }src [${_ip}]"
970 _port_filter="sport == :${_port}"
972 # Record connections to our public IPs in a temporary file.
973 # This temporary file is in CTDB's private state directory and
974 # $$ is used to avoid a very rare race involving CTDB's script
975 # debugging. No security issue, nothing to see here...
976 _my_connections="${tickledir}/${_port}.connections.$$"
977 # Parentheses are needed around the filters for precedence but
978 # the parentheses can't be empty!
979 ss -tn state established \
980 "${_ip_filter:+( ${_ip_filter} )}" \
981 "${_port_filter:+( ${_port_filter} )}" |
982 awk 'NR > 1 {print $4, $3}' |
983 sort >"$_my_connections"
985 # Record our current tickles in a temporary file
986 _my_tickles="${tickledir}/${_port}.tickles.$$"
988 $CTDB -X gettickles "$_i" "$_port" |
989 awk -F'|' 'NR > 1 { printf "%s:%s %s:%s\n", $2, $3, $4, $5 }'
993 # Add tickles for connections that we haven't already got tickles for
994 comm -23 "$_my_connections" "$_my_tickles" | \
997 # Remove tickles for connections that are no longer there
998 comm -13 "$_my_connections" "$_my_tickles" | \
1001 rm -f "$_my_connections" "$_my_tickles"
1003 # Remove stale files from killed scripts
1004 # Files can't have spaces in name, more portable than -print0/-0
1005 # shellcheck disable=SC2038
1006 (cd "$tickledir" && find . -type f -mmin +10 | xargs -r rm)
1009 ########################################################
1010 # load a site local config file
1011 ########################################################
1013 [ -x "${CTDB_BASE}/rc.local" ] && {
1014 . "${CTDB_BASE}/rc.local"
1017 [ -d "${CTDB_BASE}/rc.local.d" ] && {
1018 for i in "${CTDB_BASE}/rc.local.d"/* ; do
1019 [ -x "$i" ] && . "$i"
1023 script_name="${0##*/}" # basename