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