ctdb-scripts: Compact server-end TCP connection killing output
[samba.git] / ctdb / config / functions
1 # Hey Emacs, this is a -*- shell-script -*- !!!
2
3 # utility functions for ctdb event scripts
4
5 if [ -z "$CTDB_BASE" ] ; then
6     echo 'CTDB_BASE unset in CTDB functions file'
7     exit 1
8 fi
9 export CTDB_BASE
10
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"
15
16 CTDB="${CTDB:-/usr/local/bin/ctdb}"
17
18 # Only (and always) override these variables in test code
19
20 if [ -z "$CTDB_SCRIPT_VARDIR" ] ; then
21     CTDB_SCRIPT_VARDIR="/usr/local/var/lib/ctdb/state"
22 fi
23
24 if [ -z "$CTDB_SYS_ETCDIR" ] ; then
25     CTDB_SYS_ETCDIR="/etc"
26 fi
27
28 if [ -z "$CTDB_HELPER_BINDIR" ] ; then
29     CTDB_HELPER_BINDIR="/usr/local/libexec/ctdb"
30 fi
31
32 #######################################
33 # pull in a system config file, if any
34
35 rewrite_ctdb_options ()
36 {
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}"
50
51             CTDB_DBDIR="${ctdb_rundir}/CTDB_DBDIR"
52             ;;
53         *)
54             # shellcheck disable=SC2034
55             CTDB_DBDIR_TMPFS_OPTIONS=""
56     esac
57 }
58
59 _loadconfig() {
60
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
68
69     if [ "$1" != "ctdb" ] ; then
70         loadconfig "ctdb"
71     fi
72
73     if [ -z "$1" ] ; then
74         return
75     fi
76
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
84
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
92 }
93
94 loadconfig () {
95     _loadconfig "$@"
96 }
97
98 ##############################################################
99
100 die ()
101 {
102     _msg="$1"
103     _rc="${2:-1}"
104
105     echo "$_msg" >&2
106     exit "$_rc"
107 }
108
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.
111 script_log ()
112 {
113     _tag="$1" ; shift
114
115     case "$CTDB_LOGGING" in
116         file:*|"")
117             if [ -n "$CTDB_LOGGING" ] ; then
118                 _file="${CTDB_LOGGING#file:}"
119             else
120                 _file="/usr/local/var/log/log.ctdb"
121             fi
122             {
123                 if [ -n "$*" ] ; then
124                     echo "$*"
125                 else
126                     cat
127                 fi
128             } >>"$_file"
129             ;;
130         *)
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}" "$*"
134             ;;
135     esac
136 }
137
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 ()
141 {
142     (
143         "$@" 2>&1 </dev/null |
144         script_log "${script_name}&"
145     )&
146
147     return 0
148 }
149
150 ##############################################################
151 # check number of args for different events
152 ctdb_check_args ()
153 {
154     case "$1" in
155         takeip|releaseip)
156             if [ $# != 4 ]; then
157                 echo "ERROR: must supply interface, IP and maskbits"
158                 exit 1
159             fi
160             ;;
161         updateip)
162             if [ $# != 5 ]; then
163                 echo "ERROR: must supply old interface, new interface, IP and maskbits"
164                 exit 1
165             fi
166             ;;
167     esac
168 }
169
170 ##############################################################
171 # determine on what type of system (init style) we are running
172 detect_init_style()
173 {
174     # only do detection if not already set:
175     [ -z "$CTDB_INIT_STYLE" ] || return
176
177     if [ -x /sbin/startproc ]; then
178         CTDB_INIT_STYLE="suse"
179     elif [ -x /sbin/start-stop-daemon ]; then
180         CTDB_INIT_STYLE="debian"
181     else
182         CTDB_INIT_STYLE="redhat"
183     fi
184 }
185
186 ######################################################
187 # simulate /sbin/service on platforms that don't have it
188 # _service() makes it easier to hook the service() function for
189 # testing.
190 _service ()
191 {
192   _service_name="$1"
193   _op="$2"
194
195   # do nothing, when no service was specified
196   [ -z "$_service_name" ] && return
197
198   if [ -x /sbin/service ]; then
199       $_nice /sbin/service "$_service_name" "$_op"
200   elif [ -x /usr/sbin/service ]; then
201       $_nice /usr/sbin/service "$_service_name" "$_op"
202   elif [ -x /bin/systemctl ]; then
203       $_nice /bin/systemctl "$_op" "$_service_name"
204   elif [ -x "${CTDB_SYS_ETCDIR}/init.d/${_service_name}" ]; then
205       $_nice "${CTDB_SYS_ETCDIR}/init.d/${_service_name}" "$_op"
206   elif [ -x "${CTDB_SYS_ETCDIR}/rc.d/init.d/${_service_name}" ]; then
207       $_nice "${CTDB_SYS_ETCDIR}/rc.d/init.d/${_service_name}" "$_op"
208   fi
209 }
210
211 service()
212 {
213     _nice=""
214     _service "$@"
215 }
216
217 ######################################################
218 # simulate /sbin/service (niced) on platforms that don't have it
219 nice_service()
220 {
221     _nice="nice"
222     _service "$@"
223 }
224
225 ######################################################
226 # Cached retrieval of PNN from local node.  This never changes so why
227 # open a client connection to the server each time this is needed?
228 ctdb_get_pnn ()
229 {
230     _pnn_file="${CTDB_SCRIPT_VARDIR}/my-pnn"
231     if [ ! -f "$_pnn_file" ] ; then
232         $CTDB pnn >"$_pnn_file"
233     fi
234
235     cat "$_pnn_file"
236 }
237
238 # Cached retrieval of private IP address from local node.  This never
239 # changes.
240 ctdb_get_ip_address ()
241 {
242     _ip_addr_file="${CTDB_SCRIPT_VARDIR}/my-ip-address"
243     if [ ! -f "$_ip_addr_file" ] ; then
244         $CTDB -X nodestatus |
245             awk -F '|' 'NR == 2 { print $3 }' >"$_ip_addr_file"
246     fi
247
248     # ip_address is used by caller
249     # shellcheck disable=SC2034
250     cat "$_ip_addr_file"
251 }
252
253 ######################################################
254 # wrapper around /proc/ settings to allow them to be hooked
255 # for testing
256 # 1st arg is relative path under /proc/, 2nd arg is value to set
257 set_proc ()
258 {
259     echo "$2" >"/proc/$1"
260 }
261
262 set_proc_maybe ()
263 {
264     if [ -w "/proc/$1" ] ; then
265         set_proc "$1" "$2"
266     fi
267 }
268
269 ######################################################
270 # wrapper around getting file contents from /proc/ to allow
271 # this to be hooked for testing
272 # 1st arg is relative path under /proc/
273 get_proc ()
274 {
275     cat "/proc/$1"
276 }
277
278 ######################################################
279 # Print up to $_max kernel stack traces for processes named $_program
280 program_stack_traces ()
281 {
282     _prog="$1"
283     _max="${2:-1}"
284
285     _count=1
286     for _pid in $(pidof "$_prog") ; do
287         [ "$_count" -le "$_max" ] || break
288
289         # Do this first to avoid racing with process exit
290         _stack=$(get_proc "${_pid}/stack" 2>/dev/null)
291         if [ -n "$_stack" ] ; then
292             echo "Stack trace for ${_prog}[${_pid}]:"
293             echo "$_stack"
294             _count=$((_count + 1))
295         fi
296     done
297 }
298
299 ######################################################
300 # Ensure $service_name is set
301 assert_service_name ()
302 {
303     [ -n "$service_name" ] || die "INTERNAL ERROR: \$service_name not set"
304 }
305
306 ######################################################
307 # check a set of directories is available
308 # return 1 on a missing directory
309 # directories are read from stdin
310 ######################################################
311 ctdb_check_directories_probe()
312 {
313     while IFS="" read d ; do
314         case "$d" in
315             *%*)
316                 continue
317                 ;;
318             *)
319                 [ -d "${d}/." ] || return 1
320         esac
321     done
322 }
323
324 ######################################################
325 # check a set of directories is available
326 # directories are read from stdin
327 ######################################################
328 ctdb_check_directories()
329 {
330     ctdb_check_directories_probe || {
331         echo "ERROR: $service_name directory \"$d\" not available"
332         exit 1
333     }
334 }
335
336 ######################################################
337 # check a set of tcp ports
338 # usage: ctdb_check_tcp_ports <ports...>
339 ######################################################
340
341 # Check whether something is listening on all of the given TCP ports
342 # using the "ctdb checktcpport" command.
343 ctdb_check_tcp_ports()
344 {
345         if [ -z "$1" ] ; then
346                 echo "INTERNAL ERROR: ctdb_check_tcp_ports - no ports specified"
347                 exit 1
348         fi
349
350         for _p ; do  # process each function argument (port)
351                 _cmd="$CTDB checktcpport $_p"
352                 _out=$($_cmd 2>&1)
353                 _ret=$?
354                 case "$_ret" in
355                 0)
356                         echo "$service_name not listening on TCP port $_p"
357                         return 1
358                         ;;
359                 98)
360                         # Couldn't bind, something already listening, next port
361                         continue
362                         ;;
363                 *)
364                         echo "unexpected error (${_ret}) running \"${_cmd}\""
365                         if [ -n "$_out" ] ; then
366                                 echo "$_out"
367                         fi
368                         return $_ret
369                         ;;
370                 esac
371         done
372
373         # All ports listening
374         return 0
375 }
376
377 ######################################################
378 # check a unix socket
379 # usage: ctdb_check_unix_socket SERVICE_NAME <socket_path>
380 ######################################################
381 ctdb_check_unix_socket() {
382     socket_path="$1"
383     [ -z "$socket_path" ] && return
384
385     if ! netstat --unix -a -n | grep -q "^unix.*LISTEN.*${socket_path}$"; then
386         echo "ERROR: $service_name socket $socket_path not found"
387         return 1
388     fi
389 }
390
391 ################################################
392 # kill off any TCP connections with the given IP
393 ################################################
394 kill_tcp_connections ()
395 {
396     _iface="$1"
397     _ip="$2"
398
399     _oneway=false
400     if [ "$3" = "oneway" ] ; then
401         _oneway=true
402     fi
403
404     get_tcp_connections_for_ip "$_ip" | {
405         _killcount=0
406         _connections=""
407         _nl="
408 "
409         while read _dst _src; do
410             _destport="${_dst##*:}"
411             __oneway=$_oneway
412             case $_destport in
413                 # we only do one-way killtcp for CIFS
414                 139|445) __oneway=true ;;
415             esac
416
417             _connections="${_connections}${_nl}${_src} ${_dst}"
418             if ! $__oneway ; then
419                 _connections="${_connections}${_nl}${_dst} ${_src}"
420             fi
421
422             _killcount=$((_killcount + 1))
423         done
424
425         if [ $_killcount -eq 0 ] ; then
426             return
427         fi
428
429         echo "$_connections" | \
430                 "${CTDB_HELPER_BINDIR}/ctdb_killtcp" "$_iface" || {
431                 echo "Failed to kill TCP connections"
432                 return
433         }
434
435         _connections=$(get_tcp_connections_for_ip "$_ip")
436         if [ -z "$_connections" ] ; then
437                 _remaining=0
438         else
439                 _remaining=$(echo "$_connections" | wc -l)
440         fi
441
442         _actually_killed=$((_killcount - _remaining))
443
444         _t="${_actually_killed}/${_killcount}"
445         echo "Killed ${_t} TCP connections to released IP $_ip"
446
447         if [ -n "$_connections" ] ; then
448                 echo "Remaining connections:"
449                 echo "$_connections" | sed -e 's|^|  |'
450         fi
451     }
452 }
453
454 ##################################################################
455 # kill off the local end for any TCP connections with the given IP
456 ##################################################################
457 kill_tcp_connections_local_only ()
458 {
459     kill_tcp_connections "$@" "oneway"
460 }
461
462 ##################################################################
463 # tickle any TCP connections with the given IP
464 ##################################################################
465 tickle_tcp_connections ()
466 {
467     _ip="$1"
468
469     # Get connections, both directions
470     _conns=$(get_tcp_connections_for_ip "$_ip" | \
471                     awk '{ print $1, $2 ; print $2, $1 }')
472
473     echo "$_conns" | awk '{ print "Tickle TCP connection", $1, $2 }'
474     echo "$_conns" | ctdb tickle
475 }
476
477 get_tcp_connections_for_ip ()
478 {
479     _ip="$1"
480
481     ss -tn state established "src [$_ip]" | awk 'NR > 1 {print $3, $4}'
482 }
483
484 ########################################################
485
486 add_ip_to_iface ()
487 {
488     _iface=$1
489     _ip=$2
490     _maskbits=$3
491
492     # Ensure interface is up
493     ip link set "$_iface" up || \
494         die "Failed to bringup interface $_iface"
495
496     # Only need to define broadcast for IPv4
497     case "$_ip" in
498         *:*) _bcast=""      ;;
499         *)   _bcast="brd +" ;;
500     esac
501
502     # Intentionally unquoted multi-word value here
503     # shellcheck disable=SC2086
504     ip addr add "$_ip/$_maskbits" $_bcast dev "$_iface" || {
505         echo "Failed to add $_ip/$_maskbits on dev $_iface"
506         return 1
507     }
508
509     # Wait 5 seconds for IPv6 addresses to stop being tentative...
510     if [ -z "$_bcast" ] ; then
511         for _x in $(seq 1 10) ; do
512             ip addr show to "${_ip}/128" | grep -q "tentative" || break
513             sleep 0.5
514         done
515
516         # If the address was a duplicate then it won't be on the
517         # interface so flag an error.
518         _t=$(ip addr show to "${_ip}/128")
519         case "$_t" in
520             "")
521                 echo "Failed to add $_ip/$_maskbits on dev $_iface"
522                 return 1
523                 ;;
524             *tentative*|*dadfailed*)
525                 echo "Failed to add $_ip/$_maskbits on dev $_iface"
526                 ip addr del "$_ip/$_maskbits" dev "$_iface"
527                 return 1
528                 ;;
529         esac
530     fi
531 }
532
533 delete_ip_from_iface()
534 {
535     _iface=$1
536     _ip=$2
537     _maskbits=$3
538
539     # This could be set globally for all interfaces but it is probably
540     # better to avoid surprises, so limit it the interfaces where CTDB
541     # has public IP addresses.  There isn't anywhere else convenient
542     # to do this so just set it each time.  This is much cheaper than
543     # remembering and re-adding secondaries.
544     set_proc "sys/net/ipv4/conf/${_iface}/promote_secondaries" 1
545
546     ip addr del "$_ip/$_maskbits" dev "$_iface" || {
547         echo "Failed to del $_ip on dev $_iface"
548         return 1
549     }
550 }
551
552 # If the given IP is hosted then print 2 items: maskbits and iface
553 ip_maskbits_iface ()
554 {
555     _addr="$1"
556
557     case "$_addr" in
558         *:*) _bits=128 ;;
559         *)   _bits=32  ;;
560     esac
561     ip addr show to "${_addr}/${_bits}" 2>/dev/null | \
562         awk 'NR == 1 { iface = $2; sub(":$", "", iface) ;
563                        sub("@.*", "", iface) }
564              $1 ~ /inet/ { mask = $2; sub(".*/", "", mask);
565                            print mask, iface }'
566 }
567
568 drop_ip ()
569 {
570     _addr="${1%/*}"  # Remove optional maskbits
571
572     # Intentional word splitting here
573     # shellcheck disable=SC2046
574     set -- $(ip_maskbits_iface "$_addr")
575     if [ -n "$1" ] ; then
576         _maskbits="$1"
577         _iface="$2"
578         echo "Removing public address $_addr/$_maskbits from device $_iface"
579         delete_ip_from_iface "$_iface" "$_addr" "$_maskbits" >/dev/null 2>&1
580     fi
581 }
582
583 drop_all_public_ips ()
584 {
585         # _x is intentionally ignored
586         # shellcheck disable=SC2034
587         while read _ip _x ; do
588                 drop_ip "$_ip"
589         done <"${CTDB_PUBLIC_ADDRESSES:-/dev/null}"
590 }
591
592 flush_route_cache ()
593 {
594     set_proc_maybe sys/net/ipv4/route/flush 1
595     set_proc_maybe sys/net/ipv6/route/flush 1
596 }
597
598 ########################################################
599 # Interface monitoring
600
601 # If the interface is a virtual one (e.g. VLAN) then get the
602 # underlying interface
603 interface_get_real ()
604 {
605     # Output of "ip link show <iface>"
606     _iface_info="$1"
607
608     # Extract the full interface description to see if it is a VLAN
609     _t=$(echo "$_iface_info" |
610                 awk 'NR == 1 { iface = $2; sub(":$", "", iface) ;
611                                print iface }')
612     case "$_t" in
613         *@*)
614             # VLAN: use the underlying interface, after the '@'
615             echo "${_t##*@}"
616             ;;
617         *)
618             # Not a regular VLAN.  For backward compatibility, assume
619             # there is some other sort of VLAN that doesn't have the
620             # '@' in the output and only use what is before a '.'.  If
621             # there is no '.' then this will be the whole interface
622             # name.
623             echo "${_t%%.*}"
624     esac
625 }
626
627 # Check whether an interface is operational
628 interface_monitor ()
629 {
630     _iface="$1"
631
632     _iface_info=$(ip link show "$_iface" 2>&1) || {
633         echo "ERROR: Monitored interface ${_iface} does not exist"
634         return 1
635     }
636
637
638     # If the interface is a virtual one (e.g. VLAN) then get the
639     # underlying interface.
640     _realiface=$(interface_get_real "$_iface_info")
641
642     if _bi=$(get_proc "net/bonding/${_realiface}" 2>/dev/null) ; then
643         # This is a bond: various monitoring strategies
644         echo "$_bi" | grep -q 'Currently Active Slave: None' && {
645             echo "ERROR: No active slaves for bond device ${_realiface}"
646             return 1
647         }
648         echo "$_bi" | grep -q '^MII Status: up' || {
649             echo "ERROR: public network interface ${_realiface} is down"
650             return 1
651         }
652         echo "$_bi" | grep -q '^Bonding Mode: IEEE 802.3ad Dynamic link aggregation' && {
653             # This works around a bug in the driver where the
654             # overall bond status can be up but none of the actual
655             # physical interfaces have a link.
656             echo "$_bi" | grep 'MII Status:' | tail -n +2 | grep -q '^MII Status: up' || {
657                 echo "ERROR: No active slaves for 802.ad bond device ${_realiface}"
658                 return 1
659             }
660         }
661
662         return 0
663     else
664         # Not a bond
665         case "$_iface" in
666             lo*)
667                 # loopback is always working
668                 return 0
669                 ;;
670             ib*)
671                 # we don't know how to test ib links
672                 return 0
673                 ;;
674             *)
675                 ethtool "$_iface" | grep -q 'Link detected: yes' || {
676                     # On some systems, this is not successful when a
677                     # cable is plugged but the interface has not been
678                     # brought up previously. Bring the interface up
679                     # and try again...
680                     ip link set "$_iface" up
681                     ethtool "$_iface" | grep -q 'Link detected: yes' || {
682                         echo "ERROR: No link on the public network interface ${_iface}"
683                         return 1
684                     }
685                 }
686                 return 0
687                 ;;
688         esac
689     fi
690 }
691
692 ########################################################
693 # Simple counters
694 _ctdb_counter_common () {
695     _service_name="${1:-${service_name:-${script_name}}}"
696     _counter_file="${CTDB_SCRIPT_VARDIR}/failcount/${_service_name}"
697     mkdir -p "${_counter_file%/*}" # dirname
698 }
699 # Some code passes an argument
700 # shellcheck disable=SC2120
701 ctdb_counter_init () {
702     _ctdb_counter_common "$1"
703
704     >"$_counter_file"
705 }
706 ctdb_counter_incr () {
707     _ctdb_counter_common "$1"
708
709     # unary counting using newlines!
710     echo >>"$_counter_file"
711 }
712 ctdb_counter_get () {
713     _ctdb_counter_common "$1"
714     # unary counting!
715     stat -c "%s" "$_counter_file" 2>/dev/null || echo 0
716 }
717
718 ########################################################
719
720 ctdb_setup_service_state_dir ()
721 {
722         _s="${1:-${service_name}}"
723
724         _service_state_dir="${CTDB_SCRIPT_VARDIR}/service_state/${_s}"
725         mkdir -p "$_service_state_dir" ||
726                 die "Error creating state dir \"${_service_state_dir}\""
727
728         echo "$_service_state_dir"
729 }
730
731 ##################################################################
732 # Reconfigure a service on demand
733
734 _ctdb_service_reconfigure_common ()
735 {
736     _d="${CTDB_SCRIPT_VARDIR}/service_status/${service_name}"
737     mkdir -p "$_d"
738     _ctdb_service_reconfigure_flag="$_d/reconfigure"
739 }
740
741 ctdb_service_needs_reconfigure ()
742 {
743     _ctdb_service_reconfigure_common
744     [ -e "$_ctdb_service_reconfigure_flag" ]
745 }
746
747 ctdb_service_set_reconfigure ()
748 {
749     _ctdb_service_reconfigure_common
750     >"$_ctdb_service_reconfigure_flag"
751 }
752
753 ctdb_service_unset_reconfigure ()
754 {
755     _ctdb_service_reconfigure_common
756     rm -f "$_ctdb_service_reconfigure_flag"
757 }
758
759 ctdb_service_reconfigure ()
760 {
761     echo "Reconfiguring service \"${service_name}\"..."
762     ctdb_service_unset_reconfigure
763     service_reconfigure || return $?
764     # Intentionally have this use $service_name as default
765     # shellcheck disable=SC2119
766     ctdb_counter_init
767 }
768
769 # Default service_reconfigure() function does nothing.
770 service_reconfigure ()
771 {
772     :
773 }
774
775 ##################################################################
776 # Does CTDB manage this service?
777
778 ctdb_compat_managed_service ()
779 {
780     if [ "$1" = "yes" -a "$2" = "$service_name" ] ; then
781         CTDB_MANAGED_SERVICES="$CTDB_MANAGED_SERVICES $2"
782     fi
783 }
784
785 is_ctdb_managed_service ()
786 {
787     assert_service_name
788
789     # $t is used just for readability and to allow better accurate
790     # matching via leading/trailing spaces
791     t=" $CTDB_MANAGED_SERVICES "
792
793     # Return 0 if "<space>$service_name<space>" appears in $t
794     if [ "${t#* ${service_name} }" != "${t}" ] ; then
795         return 0
796     fi
797
798     # If above didn't match then update $CTDB_MANAGED_SERVICES for
799     # backward compatibility and try again.
800     ctdb_compat_managed_service "$CTDB_MANAGES_VSFTPD"   "vsftpd"
801     ctdb_compat_managed_service "$CTDB_MANAGES_SAMBA"    "samba"
802     ctdb_compat_managed_service "$CTDB_MANAGES_WINBIND"  "winbind"
803     ctdb_compat_managed_service "$CTDB_MANAGES_HTTPD"    "apache2"
804     ctdb_compat_managed_service "$CTDB_MANAGES_HTTPD"    "httpd"
805     ctdb_compat_managed_service "$CTDB_MANAGES_ISCSI"    "iscsi"
806     ctdb_compat_managed_service "$CTDB_MANAGES_CLAMD"    "clamd"
807     ctdb_compat_managed_service "$CTDB_MANAGES_NFS"      "nfs"
808
809     t=" $CTDB_MANAGED_SERVICES "
810
811     # Return 0 if "<space>$service_name<space>" appears in $t
812     [ "${t#* ${service_name} }" != "${t}" ]
813 }
814
815 # Default service_start() and service_stop() functions.
816  
817 # These may be overridden in an eventscript.
818 service_start ()
819 {
820     service "$service_name" start
821 }
822
823 service_stop ()
824 {
825     service "$service_name" stop
826 }
827
828 ##################################################################
829
830 # This exists only for backward compatibility with 3rd party scripts
831 # that call it
832 ctdb_standard_event_handler ()
833 {
834     :
835 }
836
837 iptables_wrapper ()
838 {
839     _family="$1" ; shift
840     if [ "$_family" = "inet6" ] ; then
841         _iptables_cmd="ip6tables"
842     else
843         _iptables_cmd="iptables"
844     fi
845
846     # iptables doesn't like being re-entered, so flock-wrap it.
847     flock -w 30 "${CTDB_SCRIPT_VARDIR}/iptables.flock" "$_iptables_cmd" "$@"
848 }
849
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
854     mktemp ()
855     {
856         _dir=false
857         if [ "$1" = "-d" ] ; then
858             _dir=true
859             shift
860         fi
861         _d="${TMPDIR:-/tmp}"
862         _hex10=$(dd if=/dev/urandom count=20 2>/dev/null | \
863             md5sum | \
864             sed -e 's@\(..........\).*@\1@')
865         _t="${_d}/tmp.${_hex10}"
866         (
867             umask 077
868             if $_dir ; then
869                 mkdir "$_t"
870             else
871                 >"$_t"
872             fi
873         )
874         echo "$_t"
875     }
876 fi
877
878 ######################################################################
879 # NFS callout handling
880
881 nfs_callout_init ()
882 {
883         _state_dir="$1"
884
885         if [ -z "$CTDB_NFS_CALLOUT" ] ; then
886                 CTDB_NFS_CALLOUT="${CTDB_BASE}/nfs-linux-kernel-callout"
887         fi
888         # Always export, for statd callout
889         export CTDB_NFS_CALLOUT
890
891         # If the callout wants to use this then it must create it
892         export CTDB_NFS_CALLOUT_STATE_DIR="${_state_dir}/callout-state"
893
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
897         fi
898         if [ -n "$CTDB_NFS_STATE_MNT" ] ; then
899                 export CTDB_NFS_STATE_MNT
900         fi
901
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"
905 }
906
907 nfs_callout_register ()
908 {
909     mkdir -p "$nfs_callout_cache_ops"
910     rm -f "$nfs_callout_cache_ops"/*
911
912     echo "$CTDB_NFS_CALLOUT" >"$nfs_callout_cache_callout"
913
914     _t=$(eval "$CTDB_NFS_CALLOUT" "register")
915     if [ -n "$_t" ] ; then
916         echo "$_t" |
917             while IFS="" read _op ; do
918                 touch "${nfs_callout_cache_ops}/${_op}"
919             done
920     else
921         touch "${nfs_callout_cache_ops}/ALL"
922     fi
923 }
924
925 nfs_callout ()
926 {
927     # Re-run registration if $CTDB_NFS_CALLOUT has changed
928     _prev=""
929     if [ -r "$nfs_callout_cache_callout" ] ; then
930         read _prev <"$nfs_callout_cache_callout"
931     fi
932     if [ "$CTDB_NFS_CALLOUT" != "$_prev" ] ; then
933         nfs_callout_register
934     fi
935
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         eval "$CTDB_NFS_CALLOUT" "$@"
940     fi
941 }
942
943 ########################################################
944 # tickle handling
945 ########################################################
946
947 update_tickles ()
948 {
949         _port="$1"
950
951         tickledir="${CTDB_SCRIPT_VARDIR}/tickles"
952         mkdir -p "$tickledir"
953
954         # What public IPs do I hold?
955         _pnn=$(ctdb_get_pnn)
956         _ips=$($CTDB -X ip | awk -F'|' -v pnn="$_pnn" '$3 == pnn {print $2}')
957
958         # IPs and port as ss filters
959         _ip_filter=""
960         for _ip in $_ips ; do
961             _ip_filter="${_ip_filter}${_ip_filter:+ || }src [${_ip}]"
962         done
963         _port_filter="sport == :${_port}"
964
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!
972         ss -tn state established \
973            "${_ip_filter:+( ${_ip_filter} )}" \
974            "${_port_filter:+( ${_port_filter} )}" |
975         awk 'NR > 1 {print $4, $3}' |
976         sort >"$_my_connections"
977
978         # Record our current tickles in a temporary file
979         _my_tickles="${tickledir}/${_port}.tickles.$$"
980         for _i in $_ips ; do
981                 $CTDB -X gettickles "$_i" "$_port" |
982                 awk -F'|' 'NR > 1 { printf "%s:%s %s:%s\n", $2, $3, $4, $5 }'
983         done |
984         sort >"$_my_tickles"
985
986         # Add tickles for connections that we haven't already got tickles for
987         comm -23 "$_my_connections" "$_my_tickles" | \
988                 $CTDB addtickle
989
990         # Remove tickles for connections that are no longer there
991         comm -13 "$_my_connections" "$_my_tickles" | \
992                 $CTDB deltickle
993
994         rm -f "$_my_connections" "$_my_tickles"
995
996         # Remove stale files from killed scripts
997         # Files can't have spaces in name, more portable than -print0/-0
998         # shellcheck disable=SC2038
999         (cd "$tickledir" && find . -type f -mmin +10 | xargs -r rm)
1000 }
1001
1002 ########################################################
1003 # load a site local config file
1004 ########################################################
1005
1006 [ -n "$CTDB_RC_LOCAL" -a -x "$CTDB_RC_LOCAL" ] && {
1007         . "$CTDB_RC_LOCAL"
1008 }
1009
1010 [ -x "${CTDB_BASE}/rc.local" ] && {
1011         . "${CTDB_BASE}/rc.local"
1012 }
1013
1014 [ -d "${CTDB_BASE}/rc.local.d" ] && {
1015         for i in "${CTDB_BASE}/rc.local.d"/* ; do
1016                 [ -x "$i" ] && . "$i"
1017         done
1018 }
1019
1020 script_name="${0##*/}"       # basename