ctdb-scripts: Support systemctl directly
[obnox/samba/samba-obnox.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
10 CTDB_VARDIR="/usr/local/var/lib/ctdb"
11 ctdb_rundir="/usr/local/var/run/ctdb"
12
13 # Only (and always) override these variables in test code
14
15 if [ -z "$CTDB_SCRIPT_VARDIR" ] ; then
16     CTDB_SCRIPT_VARDIR="/usr/local/var/lib/ctdb/state"
17 fi
18
19 if [ -z "$CTDB_SYS_ETCDIR" ] ; then
20     CTDB_SYS_ETCDIR="/etc"
21 fi
22
23 if [ -z "$CTDB_HELPER_BINDIR" ] ; then
24     CTDB_HELPER_BINDIR="/usr/local/libexec/ctdb"
25 fi
26
27 #######################################
28 # pull in a system config file, if any
29
30 rewrite_ctdb_options ()
31 {
32     case "$CTDB_DBDIR" in
33         tmpfs|tmpfs:*)
34             _opts_defaults="mode=700"
35             # Get any extra options specified after colon
36             if [ "$CTDB_DBDIR" = "tmpfs" ] ; then
37                 _opts=""
38             else
39                 _opts="${CTDB_DBDIR#tmpfs:}"
40             fi
41             # This is an internal variable, only used by ctdbd_wrapper.
42             # It is OK to repeat mount options - last value wins
43             CTDB_DBDIR_TMPFS_OPTIONS="${_opts_defaults}${_opts:+,}${_opts}"
44
45             CTDB_DBDIR="${ctdb_rundir}/CTDB_DBDIR"
46             ;;
47         *)
48             CTDB_DBDIR_TMPFS_OPTIONS=""
49     esac
50 }
51
52 _loadconfig() {
53
54     if [ -z "$1" ] ; then
55         foo="${service_config:-${service_name}}"
56         if [ -n "$foo" ] ; then
57             loadconfig "$foo"
58             return
59         fi
60     fi
61
62     if [ "$1" != "ctdb" ] ; then
63         loadconfig "ctdb"
64     fi
65
66     if [ -z "$1" ] ; then
67         return
68     fi
69
70     if [ -f $CTDB_SYS_ETCDIR/sysconfig/$1 ]; then
71         . $CTDB_SYS_ETCDIR/sysconfig/$1
72     elif [ -f $CTDB_SYS_ETCDIR/default/$1 ]; then
73         . $CTDB_SYS_ETCDIR/default/$1
74     elif [ -f $CTDB_BASE/sysconfig/$1 ]; then
75         . $CTDB_BASE/sysconfig/$1
76     fi
77
78     if [ "$1" = "ctdb" ] ; then
79         _config="${CTDBD_CONF:-${CTDB_BASE}/ctdbd.conf}"
80         if [ -r "$_config" ] ; then
81             . "$_config"
82         fi
83         rewrite_ctdb_options
84     fi
85 }
86
87 loadconfig () {
88     _loadconfig "$@"
89 }
90
91 ##############################################################
92
93 # CTDB_SCRIPT_DEBUGLEVEL can be overwritten by setting it in a
94 # configuration file.
95 debug ()
96 {
97     if [ ${CTDB_SCRIPT_DEBUGLEVEL:-2} -ge 4 ] ; then
98         # If there are arguments then echo them.  Otherwise expect to
99         # use stdin, which allows us to pass lots of debug using a
100         # here document.
101         if [ -n "$1" ] ; then
102             echo "DEBUG: $*"
103         else
104             sed -e 's@^@DEBUG: @'
105         fi
106     else
107         if [ -z "$1" ] ; then
108             cat >/dev/null
109         fi
110     fi
111 }
112
113 die ()
114 {
115     _msg="$1"
116     _rc="${2:-1}"
117
118     echo "$_msg" >&2
119     exit $_rc
120 }
121
122 # Log given message or stdin to either syslog or a CTDB log file
123 # $1 is the tag passed to logger if syslog is in use.
124 script_log ()
125 {
126     _tag="$1" ; shift
127
128     case "$CTDB_LOGGING" in
129         file:*|"")
130             if [ -n "$CTDB_LOGGING" ] ; then
131                 _file="${CTDB_LOGGING#file:}"
132             else
133                 _file="/usr/local/var/log/log.ctdb"
134             fi
135             {
136                 if [ -n "$*" ] ; then
137                     echo "$*"
138                 else
139                     cat
140                 fi
141             } >>"$_file"
142             ;;
143         *)
144             # Handle all syslog:* variants here too.  There's no tool to do
145             # the lossy things, so just use logger.
146             logger -t "ctdbd: ${_tag}" $*
147             ;;
148     esac
149 }
150
151 # When things are run in the background in an eventscript then logging
152 # output might get lost.  This is the "solution".  :-)
153 background_with_logging ()
154 {
155     (
156         "$@" 2>&1 </dev/null |
157         script_log "${script_name}&"
158     )&
159
160     return 0
161 }
162
163 ##############################################################
164 # check number of args for different events
165 ctdb_check_args ()
166 {
167     case "$1" in
168         takeip|releaseip)
169             if [ $# != 4 ]; then
170                 echo "ERROR: must supply interface, IP and maskbits"
171                 exit 1
172             fi
173             ;;
174         updateip)
175             if [ $# != 5 ]; then
176                 echo "ERROR: must supply old interface, new interface, IP and maskbits"
177                 exit 1
178             fi
179             ;;
180     esac
181 }
182
183 ##############################################################
184 # determine on what type of system (init style) we are running
185 detect_init_style()
186 {
187     # only do detection if not already set:
188     [ -z "$CTDB_INIT_STYLE" ] || return
189
190     if [ -x /sbin/startproc ]; then
191         CTDB_INIT_STYLE="suse"
192     elif [ -x /sbin/start-stop-daemon ]; then
193         CTDB_INIT_STYLE="debian"
194     else
195         CTDB_INIT_STYLE="redhat"
196     fi
197 }
198
199 ######################################################
200 # simulate /sbin/service on platforms that don't have it
201 # _service() makes it easier to hook the service() function for
202 # testing.
203 _service ()
204 {
205   _service_name="$1"
206   _op="$2"
207
208   # do nothing, when no service was specified
209   [ -z "$_service_name" ] && return
210
211   if [ -x /sbin/service ]; then
212       $_nice /sbin/service "$_service_name" "$_op"
213   elif [ -x /usr/sbin/service ]; then
214       $_nice /usr/sbin/service "$_service_name" "$_op"
215   elif [ -x /bin/systemctl ]; then
216       $_nice /bin/systemctl "$_op" "$_service_name"
217   elif [ -x $CTDB_SYS_ETCDIR/init.d/$_service_name ]; then
218       $_nice $CTDB_SYS_ETCDIR/init.d/$_service_name "$_op"
219   elif [ -x $CTDB_SYS_ETCDIR/rc.d/init.d/$_service_name ]; then
220       $_nice $CTDB_SYS_ETCDIR/rc.d/init.d/$_service_name "$_op"
221   fi
222 }
223
224 service()
225 {
226     _nice=""
227     _service "$@"
228 }
229
230 ######################################################
231 # simulate /sbin/service (niced) on platforms that don't have it
232 nice_service()
233 {
234     _nice="nice"
235     _service "$@"
236 }
237
238 ######################################################
239 # Cached retrieval of PNN from local node.  This never changes so why
240 # open a client connection to the server each time this is needed?
241 # This sets $pnn - this avoid an unnecessary subprocess.
242 ctdb_get_pnn ()
243 {
244     _pnn_file="${CTDB_SCRIPT_VARDIR}/my-pnn"
245     if [ ! -f "$_pnn_file" ] ; then
246         ctdb pnn | sed -e 's@.*:@@' >"$_pnn_file"
247     fi
248
249     read pnn <"$_pnn_file"
250 }
251
252 # Cached retrieval of private IP address from local node.  This never
253 # changes.  Sets $ip_address to avoid an unnecessary subprocess.
254 ctdb_get_ip_address ()
255 {
256     _ip_addr_file="${CTDB_SCRIPT_VARDIR}/my-ip-address"
257     if [ ! -f "$_ip_addr_file" ] ; then
258         ctdb -X nodestatus |
259             awk -F '|' 'NR == 2 { print $3 }' >"$_ip_addr_file"
260     fi
261
262     read ip_address <"$_ip_addr_file"
263 }
264
265 ######################################################
266 # wrapper around /proc/ settings to allow them to be hooked
267 # for testing
268 # 1st arg is relative path under /proc/, 2nd arg is value to set
269 set_proc ()
270 {
271     echo "$2" >"/proc/$1"
272 }
273
274 set_proc_maybe ()
275 {
276     if [ -w "/proc/$1" ] ; then
277         set_proc "$1" "$2"
278     fi
279 }
280
281 ######################################################
282 # wrapper around getting file contents from /proc/ to allow
283 # this to be hooked for testing
284 # 1st arg is relative path under /proc/
285 get_proc ()
286 {
287     cat "/proc/$1"
288 }
289
290 ######################################################
291 # Print up to $_max kernel stack traces for processes named $_program
292 program_stack_traces ()
293 {
294     _prog="$1"
295     _max="${2:-1}"
296
297     _count=1
298     for _pid in $(pidof "$_prog") ; do
299         [ $_count -le $_max ] || break
300
301         # Do this first to avoid racing with process exit
302         _stack=$(get_proc "${_pid}/stack" 2>/dev/null)
303         if [ -n "$_stack" ] ; then
304             echo "Stack trace for ${_prog}[${_pid}]:"
305             echo "$_stack"
306             _count=$(($_count + 1))
307         fi
308     done
309 }
310
311 ######################################################
312 # Ensure $service_name is set
313 assert_service_name ()
314 {
315     [ -n "$service_name" ] || die "INTERNAL ERROR: \$service_name not set"
316 }
317
318 ######################################################
319 # check a set of directories is available
320 # return 1 on a missing directory
321 # directories are read from stdin
322 ######################################################
323 ctdb_check_directories_probe()
324 {
325     while IFS="" read d ; do
326         case "$d" in
327             *%*)
328                 continue
329                 ;;
330             *)
331                 [ -d "${d}/." ] || return 1
332         esac
333     done
334 }
335
336 ######################################################
337 # check a set of directories is available
338 # directories are read from stdin
339 ######################################################
340 ctdb_check_directories()
341 {
342     ctdb_check_directories_probe || {
343         echo "ERROR: $service_name directory \"$d\" not available"
344         exit 1
345     }
346 }
347
348 ######################################################
349 # check a set of tcp ports
350 # usage: ctdb_check_tcp_ports <ports...>
351 ######################################################
352
353 # This flag file is created when a service is initially started.  It
354 # is deleted the first time TCP port checks for that service succeed.
355 # Until then ctdb_check_tcp_ports() prints a more subtle "error"
356 # message if a port check fails.
357 _ctdb_check_tcp_common ()
358 {
359     assert_service_name
360     _d="${CTDB_SCRIPT_VARDIR}/failcount"
361     _ctdb_service_started_file="${_d}/${service_name}.started"
362 }
363
364 ctdb_check_tcp_init ()
365 {
366     _ctdb_check_tcp_common
367     mkdir -p "${_ctdb_service_started_file%/*}" # dirname
368     touch "$_ctdb_service_started_file"
369 }
370
371 # Check whether something is listening on all of the given TCP ports
372 # using the "ctdb checktcpport" command.
373 ctdb_check_tcp_ports()
374 {
375     if [ -z "$1" ] ; then
376         echo "INTERNAL ERROR: ctdb_check_tcp_ports - no ports specified"
377         exit 1
378     fi
379
380     for _p ; do  # process each function argument (port)
381         _cmd="ctdb checktcpport $_p"
382         _out=$($_cmd 2>&1)
383         _ret=$?
384         case "$_ret" in
385             0)
386                 _ctdb_check_tcp_common
387                 if [ ! -f "$_ctdb_service_started_file" ] ; then
388                     echo "ERROR: $service_name tcp port $_p is not responding"
389                     debug "\"ctdb checktcpport $_p\" was able to bind to port"
390                 else
391                     echo "INFO: $service_name tcp port $_p is not responding"
392                 fi
393
394                 return 1
395                 ;;
396             98)
397                 # Couldn't bind, something already listening, next port...
398                 continue
399                 ;;
400             *)
401                 echo "ERROR: unexpected error running \"ctdb checktcpport\""
402                 debug <<EOF
403 ctdb checktcpport (exited with $_ret) with output:
404 $_out"
405 EOF
406                 return $_ret
407         esac
408     done
409
410     # All ports listening
411     _ctdb_check_tcp_common
412     rm -f "$_ctdb_service_started_file"
413     return 0
414 }
415
416 ######################################################
417 # check a unix socket
418 # usage: ctdb_check_unix_socket SERVICE_NAME <socket_path>
419 ######################################################
420 ctdb_check_unix_socket() {
421     socket_path="$1"
422     [ -z "$socket_path" ] && return
423
424     if ! netstat --unix -a -n | grep -q "^unix.*LISTEN.*${socket_path}$"; then
425         echo "ERROR: $service_name socket $socket_path not found"
426         return 1
427     fi
428 }
429
430 ######################################################
431 # check a command returns zero status
432 # usage: ctdb_check_command <command>
433 ######################################################
434 ctdb_check_command ()
435 {
436     _out=$("$@" 2>&1) || {
437         echo "ERROR: $* returned error"
438         echo "$_out" | debug
439         exit 1
440     }
441 }
442
443 ################################################
444 # kill off any TCP connections with the given IP
445 ################################################
446 kill_tcp_connections ()
447 {
448     _iface="$1"
449     _ip="$2"
450
451     _oneway=false
452     if [ "$3" = "oneway" ] ; then
453         _oneway=true
454     fi
455
456     get_tcp_connections_for_ip "$_ip" | {
457         _killcount=0
458         _connections=""
459         _nl="
460 "
461         while read _dst _src; do
462             _destport="${_dst##*:}"
463             __oneway=$_oneway
464             case $_destport in
465                 # we only do one-way killtcp for CIFS
466                 139|445) __oneway=true ;;
467             esac
468
469             echo "Killing TCP connection $_src $_dst"
470             _connections="${_connections}${_nl}${_src} ${_dst}"
471             if ! $__oneway ; then
472                 _connections="${_connections}${_nl}${_dst} ${_src}"
473             fi
474
475             _killcount=$(($_killcount + 1))
476         done
477
478         if [ $_killcount -eq 0 ] ; then
479             return
480         fi
481
482         echo "$_connections" | \
483                 "${CTDB_HELPER_BINDIR}/ctdb_killtcp" "$_iface" || {
484                 echo "Failed to kill TCP connections"
485                 return
486         }
487
488         _remaining=$(get_tcp_connections_for_ip $_ip | wc -l)
489
490         if [ $_remaining -eq 0 ] ; then
491                 echo "Killed $_killcount TCP connections to released IP $_ip"
492                 return
493         fi
494
495         _t="${_remaining}/${_killcount}"
496         echo "Failed to kill TCP connections for IP $_ip (${_t} remaining)"
497     }
498 }
499
500 ##################################################################
501 # kill off the local end for any TCP connections with the given IP
502 ##################################################################
503 kill_tcp_connections_local_only ()
504 {
505     kill_tcp_connections "$@" "oneway"
506 }
507
508 ##################################################################
509 # tickle any TCP connections with the given IP
510 ##################################################################
511 tickle_tcp_connections ()
512 {
513     _ip="$1"
514
515     get_tcp_connections_for_ip "$_ip" |
516     {
517         _failed=false
518
519         while read dest src; do
520             echo "Tickle TCP connection $src $dest"
521             ctdb tickle $src $dest >/dev/null 2>&1 || _failed=true
522             echo "Tickle TCP connection $dest $src"
523             ctdb tickle $dest $src >/dev/null 2>&1 || _failed=true
524         done
525
526         if $_failed ; then
527             echo "Failed to send tickle control"
528         fi
529     }
530 }
531
532 get_tcp_connections_for_ip ()
533 {
534     _ip="$1"
535
536     ss -tn state established "src [$_ip]" | awk 'NR > 1 {print $3, $4}'
537 }
538
539 ########################################################
540
541 add_ip_to_iface ()
542 {
543     _iface=$1
544     _ip=$2
545     _maskbits=$3
546
547     # Ensure interface is up
548     ip link set "$_iface" up || \
549         die "Failed to bringup interface $_iface"
550
551     # Only need to define broadcast for IPv4
552     case "$ip" in
553         *:*) _bcast=""      ;;
554         *)   _bcast="brd +" ;;
555     esac
556
557     ip addr add "$_ip/$_maskbits" $_bcast dev "$_iface" || {
558         echo "Failed to add $_ip/$_maskbits on dev $_iface"
559         return 1
560     }
561
562     # Wait 5 seconds for IPv6 addresses to stop being tentative...
563     if [ -z "$_bcast" ] ; then
564         for _x in $(seq 1 10) ; do
565             ip addr show to "${_ip}/128" | grep -q "tentative" || break
566             sleep 0.5
567         done
568
569         # If the address was a duplicate then it won't be on the
570         # interface so flag an error.
571         _t=$(ip addr show to "${_ip}/128")
572         case "$_t" in
573             "")
574                 echo "Failed to add $_ip/$_maskbits on dev $_iface"
575                 return 1
576                 ;;
577             *tentative*|*dadfailed*)
578                 echo "Failed to add $_ip/$_maskbits on dev $_iface"
579                 ip addr del "$_ip/$_maskbits" dev "$_iface"
580                 return 1
581                 ;;
582         esac
583     fi
584 }
585
586 delete_ip_from_iface()
587 {
588     _iface=$1
589     _ip=$2
590     _maskbits=$3
591
592     # This could be set globally for all interfaces but it is probably
593     # better to avoid surprises, so limit it the interfaces where CTDB
594     # has public IP addresses.  There isn't anywhere else convenient
595     # to do this so just set it each time.  This is much cheaper than
596     # remembering and re-adding secondaries.
597     set_proc "sys/net/ipv4/conf/${_iface}/promote_secondaries" 1
598
599     ip addr del "$_ip/$_maskbits" dev "$_iface" || {
600         echo "Failed to del $_ip on dev $_iface"
601         return 1
602     }
603 }
604
605 # If the given IP is hosted then print 2 items: maskbits and iface
606 ip_maskbits_iface ()
607 {
608     _addr="$1"
609
610     case "$_addr" in
611         *:*) _family="inet6" ; _bits=128 ;;
612         *)   _family="inet"  ; _bits=32  ;;
613     esac
614
615     ip addr show to "${_addr}/${_bits}" 2>/dev/null | \
616         awk -v family="${_family}" \
617             'NR == 1 { iface = $2; sub(":$", "", iface) ; \
618                        sub("@.*", "", iface) } \
619              $1 ~ /inet/ { mask = $2; sub(".*/", "", mask); \
620                            print mask, iface, family }'
621 }
622
623 drop_ip ()
624 {
625     _addr="${1%/*}"  # Remove optional maskbits
626
627     set -- $(ip_maskbits_iface $_addr)
628     if [ -n "$1" ] ; then
629         _maskbits="$1"
630         _iface="$2"
631         echo "Removing public address $_addr/$_maskbits from device $_iface"
632         delete_ip_from_iface $_iface $_addr $_maskbits >/dev/null 2>&1
633     fi
634 }
635
636 drop_all_public_ips ()
637 {
638     while read _ip _x ; do
639         drop_ip "$_ip"
640     done <"${CTDB_PUBLIC_ADDRESSES:-/dev/null}"
641 }
642
643 flush_route_cache ()
644 {
645     set_proc_maybe sys/net/ipv4/route/flush 1
646     set_proc_maybe sys/net/ipv6/route/flush 1
647 }
648
649 ########################################################
650 # Interface monitoring
651
652 # If the interface is a virtual one (e.g. VLAN) then get the
653 # underlying interface
654 interface_get_real ()
655 {
656     # Output of "ip link show <iface>"
657     _iface_info="$1"
658
659     # Extract the full interface description to see if it is a VLAN
660     _t=$(echo "$_iface_info" |
661                 awk 'NR == 1 { iface = $2; sub(":$", "", iface) ; \
662                                print iface }')
663     case "$_t" in
664         *@*)
665             # VLAN: use the underlying interface, after the '@'
666             echo "${_t##*@}"
667             ;;
668         *)
669             # Not a regular VLAN.  For backward compatibility, assume
670             # there is some other sort of VLAN that doesn't have the
671             # '@' in the output and only use what is before a '.'.  If
672             # there is no '.' then this will be the whole interface
673             # name.
674             echo "${_t%%.*}"
675     esac
676 }
677
678 # Check whether an interface is operational
679 interface_monitor ()
680 {
681     _iface="$1"
682
683     _iface_info=$(ip link show "$_iface" 2>&1) || {
684         echo "ERROR: Monitored interface ${_iface} does not exist"
685         return 1
686     }
687
688
689     # If the interface is a virtual one (e.g. VLAN) then get the
690     # underlying interface.
691     _realiface=$(interface_get_real "$_iface_info")
692
693     if _bi=$(get_proc "net/bonding/${_realiface}" 2>/dev/null) ; then
694         # This is a bond: various monitoring strategies
695         echo "$_bi" | grep -q 'Currently Active Slave: None' && {
696             echo "ERROR: No active slaves for bond device ${_realiface}"
697             return 1
698         }
699         echo "$_bi" | grep -q '^MII Status: up' || {
700             echo "ERROR: public network interface ${_realiface} is down"
701             return 1
702         }
703         echo "$_bi" | grep -q '^Bonding Mode: IEEE 802.3ad Dynamic link aggregation' && {
704             # This works around a bug in the driver where the
705             # overall bond status can be up but none of the actual
706             # physical interfaces have a link.
707             echo "$_bi" | grep 'MII Status:' | tail -n +2 | grep -q '^MII Status: up' || {
708                 echo "ERROR: No active slaves for 802.ad bond device ${_realiface}"
709                 return 1
710             }
711         }
712
713         return 0
714     else
715         # Not a bond
716         case "$_iface" in
717             lo*)
718                 # loopback is always working
719                 return 0
720                 ;;
721             ib*)
722                 # we don't know how to test ib links
723                 return 0
724                 ;;
725             *)
726                 ethtool "$_iface" | grep -q 'Link detected: yes' || {
727                     # On some systems, this is not successful when a
728                     # cable is plugged but the interface has not been
729                     # brought up previously. Bring the interface up
730                     # and try again...
731                     ip link set "$_iface" up
732                     ethtool "$_iface" | grep -q 'Link detected: yes' || {
733                         echo "ERROR: No link on the public network interface ${_iface}"
734                         return 1
735                     }
736                 }
737                 return 0
738                 ;;
739         esac
740     fi
741 }
742
743 ########################################################
744 # Simple counters
745 _ctdb_counter_common () {
746     _service_name="${1:-${service_name:-${script_name}}}"
747     _counter_file="${CTDB_SCRIPT_VARDIR}/failcount/${_service_name}"
748     mkdir -p "${_counter_file%/*}" # dirname
749 }
750 ctdb_counter_init () {
751     _ctdb_counter_common "$1"
752
753     >"$_counter_file"
754 }
755 ctdb_counter_incr () {
756     _ctdb_counter_common "$1"
757
758     # unary counting!
759     echo -n 1 >> "$_counter_file"
760 }
761 ctdb_counter_get () {
762     _ctdb_counter_common "$1"
763     # unary counting!
764     stat -c "%s" "$_counter_file" 2>/dev/null || echo 0
765 }
766 ctdb_check_counter () {
767     _msg="${1:-error}"  # "error"  - anything else is silent on fail
768     _op="${2:--ge}"  # an integer operator supported by test
769     _limit="${3:-${service_fail_limit}}"
770     shift 3
771
772     _size=$(ctdb_counter_get "$1")
773
774     _hit=false
775     if [ "$_op" != "%" ] ; then
776         if [ $_size $_op $_limit ] ; then
777             _hit=true
778         fi
779     else
780         if [ $(($_size $_op $_limit)) -eq 0 ] ; then
781             _hit=true
782         fi
783     fi
784     if $_hit ; then
785         if [ "$_msg" = "error" ] ; then
786             echo "ERROR: $_size consecutive failures for $_service_name, marking node unhealthy"
787             exit 1              
788         else
789             return 1
790         fi
791     fi
792 }
793
794 ########################################################
795
796 ctdb_setup_service_state_dir ()
797 {
798     service_state_dir="${CTDB_SCRIPT_VARDIR}/service_state/${1:-${service_name}}"
799     mkdir -p "$service_state_dir" || {
800         echo "Error creating state dir \"$service_state_dir\""
801         exit 1
802     }
803 }
804
805 ########################################################
806 # Managed status history, for auto-start/stop
807
808 _ctdb_managed_common ()
809 {
810     _ctdb_managed_file="${CTDB_SCRIPT_VARDIR}/managed_history/${service_name}"
811 }
812
813 ctdb_service_managed ()
814 {
815     _ctdb_managed_common
816     mkdir -p "${_ctdb_managed_file%/*}" # dirname
817     touch "$_ctdb_managed_file"
818 }
819
820 ctdb_service_unmanaged ()
821 {
822     _ctdb_managed_common
823     rm -f "$_ctdb_managed_file"
824 }
825
826 is_ctdb_previously_managed_service ()
827 {
828     _ctdb_managed_common
829     [ -f "$_ctdb_managed_file" ]
830 }
831
832 ##################################################################
833 # Reconfigure a service on demand
834
835 _ctdb_service_reconfigure_common ()
836 {
837     _d="${CTDB_SCRIPT_VARDIR}/service_status/${service_name}"
838     mkdir -p "$_d"
839     _ctdb_service_reconfigure_flag="$_d/reconfigure"
840 }
841
842 ctdb_service_needs_reconfigure ()
843 {
844     _ctdb_service_reconfigure_common
845     [ -e "$_ctdb_service_reconfigure_flag" ]
846 }
847
848 ctdb_service_set_reconfigure ()
849 {
850     _ctdb_service_reconfigure_common
851     >"$_ctdb_service_reconfigure_flag"
852 }
853
854 ctdb_service_unset_reconfigure ()
855 {
856     _ctdb_service_reconfigure_common
857     rm -f "$_ctdb_service_reconfigure_flag"
858 }
859
860 ctdb_service_reconfigure ()
861 {
862     echo "Reconfiguring service \"${service_name}\"..."
863     ctdb_service_unset_reconfigure
864     service_reconfigure || return $?
865     ctdb_counter_init
866 }
867
868 # Default service_reconfigure() function does nothing.
869 service_reconfigure ()
870 {
871     :
872 }
873
874 ctdb_reconfigure_take_lock ()
875 {
876     _ctdb_service_reconfigure_common
877     _lock="${_d}/reconfigure_lock"
878     mkdir -p "${_lock%/*}" # dirname
879     touch "$_lock"
880
881     (
882         flock 0
883         # This is overkill but will work if we need to extend this to
884         # allow certain events to run multiple times in parallel
885         # (e.g. takeip) and write multiple PIDs to the file.
886         read _locker_event 
887         if [ -n "$_locker_event" ] ; then
888             while read _pid ; do
889                 if [ -n "$_pid" -a "$_pid" != $$ ] && \
890                     kill -0 "$_pid" 2>/dev/null ; then
891                     exit 1
892                 fi
893             done
894         fi
895
896         printf "%s\n%s\n" "$event_name" $$ >"$_lock"
897         exit 0
898     ) <"$_lock"
899 }
900
901 ctdb_reconfigure_release_lock ()
902 {
903     _ctdb_service_reconfigure_common
904     _lock="${_d}/reconfigure_lock"
905
906     rm -f "$_lock"
907 }
908
909 ctdb_replay_monitor_status ()
910 {
911     echo "Replaying previous status for this script due to reconfigure..."
912     # Leading separator ('|') is missing in some versions...
913     _out=$(ctdb scriptstatus -X | grep -E "^\|?monitor\|${script_name}\|")
914     # Output looks like this:
915     # |monitor|60.nfs|1|ERROR|1314764004.030861|1314764004.035514|foo bar|
916     # This is the cheapest way of getting fields in the middle.
917     set -- $(IFS="|" ; echo $_out)
918     _code="$3"
919     _status="$4"
920     # The error output field can include colons so we'll try to
921     # preserve them.  The weak checking at the beginning tries to make
922     # this work for both broken (no leading '|') and fixed output.
923     _out="${_out%|}"
924     _err_out="${_out#*monitor|${script_name}|*|*|*|*|}"
925     case "$_status" in
926         OK) : ;;  # Do nothing special.
927         TIMEDOUT)
928             # Recast this as an error, since we can't exit with the
929             # correct negative number.
930             _code=1
931             _err_out="[Replay of TIMEDOUT scriptstatus - note incorrect return code.] ${_err_out}"
932             ;;
933         DISABLED)
934             # Recast this as an OK, since we can't exit with the
935             # correct negative number.
936             _code=0
937             _err_out="[Replay of DISABLED scriptstatus - note incorrect return code.] ${_err_out}"
938             ;;
939         *) : ;;  # Must be ERROR, do nothing special.
940     esac
941     if [ -n "$_err_out" ] ; then
942         echo "$_err_out"
943     fi
944     exit $_code
945 }
946
947 ctdb_service_check_reconfigure ()
948 {
949     assert_service_name
950
951     # We only care about some events in this function.  For others we
952     # return now.
953     case "$event_name" in
954         monitor|ipreallocated|reconfigure) : ;;
955         *) return 0 ;;
956     esac
957
958     if ctdb_reconfigure_take_lock ; then
959         # No events covered by this function are running, so proceed
960         # with gay abandon.
961         case "$event_name" in
962             reconfigure)
963                 (ctdb_service_reconfigure)
964                 exit $?
965                 ;;
966             ipreallocated)
967                 if ctdb_service_needs_reconfigure ; then
968                     ctdb_service_reconfigure
969                 fi
970                 ;;
971         esac
972
973         ctdb_reconfigure_release_lock
974     else
975         # Somebody else is running an event we don't want to collide
976         # with.  We proceed with caution.
977         case "$event_name" in
978             reconfigure)
979                 # Tell whoever called us to retry.
980                 exit 2
981                 ;;
982             ipreallocated)
983                 # Defer any scheduled reconfigure and just run the
984                 # rest of the ipreallocated event, as per the
985                 # eventscript.  There's an assumption here that the
986                 # event doesn't depend on any scheduled reconfigure.
987                 # This is true in the current code.
988                 return 0
989                 ;;
990             monitor)
991                 # There is most likely a reconfigure in progress so
992                 # the service is possibly unstable.  As above, we
993                 # defer any scheduled reconfigured.  We also replay
994                 # the previous monitor status since that's the best
995                 # information we have.
996                 ctdb_replay_monitor_status
997                 ;;
998         esac
999     fi
1000 }
1001
1002 ##################################################################
1003 # Does CTDB manage this service? - and associated auto-start/stop
1004
1005 ctdb_compat_managed_service ()
1006 {
1007     if [ "$1" = "yes" -a "$2" = "$service_name" ] ; then
1008         CTDB_MANAGED_SERVICES="$CTDB_MANAGED_SERVICES $2"
1009     fi
1010 }
1011
1012 is_ctdb_managed_service ()
1013 {
1014     assert_service_name
1015
1016     # $t is used just for readability and to allow better accurate
1017     # matching via leading/trailing spaces
1018     t=" $CTDB_MANAGED_SERVICES "
1019
1020     # Return 0 if "<space>$service_name<space>" appears in $t
1021     if [ "${t#* ${service_name} }" != "${t}" ] ; then
1022         return 0
1023     fi
1024
1025     # If above didn't match then update $CTDB_MANAGED_SERVICES for
1026     # backward compatibility and try again.
1027     ctdb_compat_managed_service "$CTDB_MANAGES_VSFTPD"   "vsftpd"
1028     ctdb_compat_managed_service "$CTDB_MANAGES_SAMBA"    "samba"
1029     ctdb_compat_managed_service "$CTDB_MANAGES_WINBIND"  "winbind"
1030     ctdb_compat_managed_service "$CTDB_MANAGES_HTTPD"    "apache2"
1031     ctdb_compat_managed_service "$CTDB_MANAGES_HTTPD"    "httpd"
1032     ctdb_compat_managed_service "$CTDB_MANAGES_ISCSI"    "iscsi"
1033     ctdb_compat_managed_service "$CTDB_MANAGES_CLAMD"    "clamd"
1034     ctdb_compat_managed_service "$CTDB_MANAGES_NFS"      "nfs"
1035
1036     t=" $CTDB_MANAGED_SERVICES "
1037
1038     # Return 0 if "<space>$service_name<space>" appears in $t
1039     [ "${t#* ${service_name} }" != "${t}" ]
1040 }
1041
1042 ctdb_start_stop_service ()
1043 {
1044     assert_service_name
1045
1046     # Allow service-start/service-stop pseudo-events to start/stop
1047     # services when we're not auto-starting/stopping and we're not
1048     # monitoring.
1049     case "$event_name" in
1050         service-start)
1051             if is_ctdb_managed_service ; then
1052                 die 'service-start event not permitted when service is managed'
1053             fi
1054             if [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] ; then
1055                 die 'service-start event not permitted with $CTDB_SERVICE_AUTOSTARTSTOP = yes'
1056             fi
1057             ctdb_service_start
1058             exit $?
1059             ;;
1060         service-stop)
1061             if is_ctdb_managed_service ; then
1062                 die 'service-stop event not permitted when service is managed'
1063             fi
1064             if [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] ; then
1065                 die 'service-stop event not permitted with $CTDB_SERVICE_AUTOSTARTSTOP = yes'
1066             fi
1067             ctdb_service_stop
1068             exit $?
1069             ;;
1070     esac
1071
1072     # Do nothing unless configured to...
1073     [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] || return 0
1074
1075     [ "$event_name" = "monitor" ] || return 0
1076
1077     if is_ctdb_managed_service ; then
1078         if ! is_ctdb_previously_managed_service ; then
1079             echo "Starting service \"$service_name\" - now managed"
1080             background_with_logging ctdb_service_start
1081             exit $?
1082         fi
1083     else
1084         if is_ctdb_previously_managed_service ; then
1085             echo "Stopping service \"$service_name\" - no longer managed"
1086             background_with_logging ctdb_service_stop
1087             exit $?
1088         fi
1089     fi
1090 }
1091
1092 ctdb_service_start ()
1093 {
1094     # The service is marked managed if we've ever tried to start it.
1095     ctdb_service_managed
1096
1097     service_start || return $?
1098
1099     ctdb_counter_init
1100     ctdb_check_tcp_init
1101 }
1102
1103 ctdb_service_stop ()
1104 {
1105     ctdb_service_unmanaged
1106     service_stop
1107 }
1108
1109 # Default service_start() and service_stop() functions.
1110  
1111 # These may be overridden in an eventscript.
1112 service_start ()
1113 {
1114     service "$service_name" start
1115 }
1116
1117 service_stop ()
1118 {
1119     service "$service_name" stop
1120 }
1121
1122 ##################################################################
1123
1124 ctdb_standard_event_handler ()
1125 {
1126     :
1127 }
1128
1129 iptables_wrapper ()
1130 {
1131     _family="$1" ; shift
1132     if [ "$_family" = "inet6" ] ; then
1133         _iptables_cmd="ip6tables"
1134     else
1135         _iptables_cmd="iptables"
1136     fi
1137
1138     # iptables doesn't like being re-entered, so flock-wrap it.
1139     flock -w 30 "${CTDB_SCRIPT_VARDIR}/iptables.flock" "$_iptables_cmd" "$@"
1140 }
1141
1142 # AIX (and perhaps others?) doesn't have mktemp
1143 if ! type mktemp >/dev/null 2>&1 ; then
1144     mktemp ()
1145     {
1146         _dir=false
1147         if [ "$1" = "-d" ] ; then
1148             _dir=true
1149             shift
1150         fi
1151         _d="${TMPDIR:-/tmp}"
1152         _hex10=$(dd if=/dev/urandom count=20 2>/dev/null | \
1153             md5sum | \
1154             sed -e 's@\(..........\).*@\1@')
1155         _t="${_d}/tmp.${_hex10}"
1156         (
1157             umask 077
1158             if $_dir ; then
1159                 mkdir "$_t"
1160             else
1161                 >"$_t"
1162             fi
1163         )
1164         echo "$_t"
1165     }
1166 fi
1167
1168 ########################################################
1169 # tickle handling
1170 ########################################################
1171
1172 update_tickles ()
1173 {
1174         _port="$1"
1175
1176         tickledir="${CTDB_SCRIPT_VARDIR}/tickles"
1177         mkdir -p "$tickledir"
1178
1179         ctdb_get_pnn
1180
1181         # What public IPs do I hold?
1182         _ips=$(ctdb -X ip | awk -F'|' -v pnn=$pnn '$3 == pnn {print $2}')
1183
1184         # IPs and port as ss filters
1185         _ip_filter=""
1186         for _ip in $_ips ; do
1187             _ip_filter="${_ip_filter}${_ip_filter:+ || }src [${_ip}]"
1188         done
1189         _port_filter="sport == :${_port}"
1190
1191         # Record connections to our public IPs in a temporary file.
1192         # This temporary file is in CTDB's private state directory and
1193         # $$ is used to avoid a very rare race involving CTDB's script
1194         # debugging.  No security issue, nothing to see here...
1195         _my_connections="${tickledir}/${_port}.connections.$$"
1196         # Parentheses are needed around the filters for precedence but
1197         # the parentheses can't be empty!
1198         ss -tn state established \
1199            "${_ip_filter:+( ${_ip_filter} )}" \
1200            "${_port_filter:+( ${_port_filter} )}" |
1201         awk 'NR > 1 {print $4, $3}' |
1202         sort >"$_my_connections"
1203
1204         # Record our current tickles in a temporary file
1205         _my_tickles="${tickledir}/${_port}.tickles.$$"
1206         for _i in $_ips ; do
1207                 ctdb -X gettickles $_i $_port |
1208                 awk -F'|' 'NR > 1 { printf "%s:%s %s:%s\n", $2, $3, $4, $5 }'
1209         done |
1210         sort >"$_my_tickles"
1211
1212         # Add tickles for connections that we haven't already got tickles for
1213         comm -23 "$_my_connections" "$_my_tickles" |
1214         while read _src _dst ; do
1215                 ctdb addtickle $_src $_dst
1216         done
1217
1218         # Remove tickles for connections that are no longer there
1219         comm -13 "$_my_connections" "$_my_tickles" |
1220         while read _src _dst ; do
1221                 ctdb deltickle $_src $_dst
1222         done
1223
1224         rm -f "$_my_connections" "$_my_tickles"
1225
1226         # Remove stale files from killed scripts
1227         find "$tickledir" -type f -mmin +10 | xargs -r rm
1228 }
1229
1230 ########################################################
1231 # load a site local config file
1232 ########################################################
1233
1234 [ -n "$CTDB_RC_LOCAL" -a -x "$CTDB_RC_LOCAL" ] && {
1235         . "$CTDB_RC_LOCAL"
1236 }
1237
1238 [ -x $CTDB_BASE/rc.local ] && {
1239         . $CTDB_BASE/rc.local
1240 }
1241
1242 [ -d $CTDB_BASE/rc.local.d ] && {
1243         for i in $CTDB_BASE/rc.local.d/* ; do
1244                 [ -x "$i" ] && . "$i"
1245         done
1246 }
1247
1248 script_name="${0##*/}"       # basename
1249 service_fail_limit=1
1250 event_name="$1"