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