ctdb-scripts: Factor out new function program_stack_traces()
[Samba.git] / ctdb / config / functions
blob49553c73559dc8bfc4c6218ca52d0b7ed43492db
1 # Hey Emacs, this is a -*- shell-script -*- !!!
3 # utility functions for ctdb event scripts
5 [ -z "$CTDB_VARDIR" ] && {
6     if [ -d "/var/lib/ctdb" ] ; then
7         export CTDB_VARDIR="/var/lib/ctdb"
8     else
9         export CTDB_VARDIR="/var/ctdb"
10     fi
12 [ -z "$CTDB_ETCDIR" ] && {
13     export CTDB_ETCDIR="/etc"
16 #######################################
17 # pull in a system config file, if any
18 _loadconfig() {
20     if [ -z "$1" ] ; then
21         foo="${service_config:-${service_name}}"
22         if [ -n "$foo" ] ; then
23             loadconfig "$foo"
24             return
25         fi
26     fi
28     if [ "$1" != "ctdb" ] ; then
29         loadconfig "ctdb"
30     fi
32     if [ -z "$1" ] ; then
33         return
34     fi
36     if [ -f $CTDB_ETCDIR/sysconfig/$1 ]; then
37         . $CTDB_ETCDIR/sysconfig/$1
38     elif [ -f $CTDB_ETCDIR/default/$1 ]; then
39         . $CTDB_ETCDIR/default/$1
40     elif [ -f $CTDB_BASE/sysconfig/$1 ]; then
41         . $CTDB_BASE/sysconfig/$1
42     fi
44     if [ "$1" = "ctdb" ] ; then
45         _config="${CTDB_BASE}/ctdbd.conf"
46         if [ -r "$_config" ] ; then
47             . "$_config"
48         fi
49     fi
52 loadconfig () {
53     _loadconfig "$@"
56 ##############################################################
58 # CTDB_SCRIPT_DEBUGLEVEL can be overwritten by setting it in a
59 # configuration file.
60 debug ()
62     if [ ${CTDB_SCRIPT_DEBUGLEVEL:-2} -ge 4 ] ; then
63         # If there are arguments then echo them.  Otherwise expect to
64         # use stdin, which allows us to pass lots of debug using a
65         # here document.
66         if [ -n "$1" ] ; then
67             echo "DEBUG: $*"
68         elif ! tty -s ; then
69             sed -e 's@^@DEBUG: @'
70         fi
71     fi
74 die ()
76     _msg="$1"
77     _rc="${2:-1}"
79     echo "$_msg"
80     exit $_rc
83 # Log given message or stdin to either syslog or a CTDB log file
84 # $1 is the tag passed to logger if syslog is in use.
85 script_log ()
87     _tag="$1" ; shift
89     case "$CTDB_LOGGING" in
90         file:*|"")
91             if [ -n "$CTDB_LOGGING" ] ; then
92                 _file="${CTDB_LOGGING#file:}"
93             else
94                 _file="/var/log/log.ctdb"
95             fi
96             {
97                 if [ -n "$*" ] ; then
98                     echo "$*"
99                 else
100                     cat
101                 fi
102             } >>"$_file"
103             ;;
104         *)
105             # Handle all syslog:* variants here too.  There's no tool to do
106             # the lossy things, so just use logger.
107             logger -t "ctdbd: ${_tag}" $*
108             ;;
109     esac
112 # When things are run in the background in an eventscript then logging
113 # output might get lost.  This is the "solution".  :-)
114 background_with_logging ()
116     (
117         "$@" 2>&1 </dev/null |
118         script_log "${script_name}&"
119     )&
121     return 0
124 ##############################################################
125 # check number of args for different events
126 ctdb_check_args ()
128     case "$1" in
129         takeip|releaseip)
130             if [ $# != 4 ]; then
131                 echo "ERROR: must supply interface, IP and maskbits"
132                 exit 1
133             fi
134             ;;
135         updateip)
136             if [ $# != 5 ]; then
137                 echo "ERROR: must supply old interface, new interface, IP and maskbits"
138                 exit 1
139             fi
140             ;;
141     esac
144 ##############################################################
145 # determine on what type of system (init style) we are running
146 detect_init_style()
148     # only do detection if not already set:
149     [ -z "$CTDB_INIT_STYLE" ] || return
151     if [ -x /sbin/startproc ]; then
152         CTDB_INIT_STYLE="suse"
153     elif [ -x /sbin/start-stop-daemon ]; then
154         CTDB_INIT_STYLE="debian"
155     else
156         CTDB_INIT_STYLE="redhat"
157     fi
160 ######################################################
161 # simulate /sbin/service on platforms that don't have it
162 # _service() makes it easier to hook the service() function for
163 # testing.
164 _service ()
166   _service_name="$1"
167   _op="$2"
169   # do nothing, when no service was specified
170   [ -z "$_service_name" ] && return
172   if [ -x /sbin/service ]; then
173       $_nice /sbin/service "$_service_name" "$_op"
174   elif [ -x $CTDB_ETCDIR/init.d/$_service_name ]; then
175       $_nice $CTDB_ETCDIR/init.d/$_service_name "$_op"
176   elif [ -x $CTDB_ETCDIR/rc.d/init.d/$_service_name ]; then
177       $_nice $CTDB_ETCDIR/rc.d/init.d/$_service_name "$_op"
178   fi
181 service()
183     _nice=""
184     _service "$@"
187 ######################################################
188 # simulate /sbin/service (niced) on platforms that don't have it
189 nice_service()
191     _nice="nice"
192     _service "$@"
195 ######################################################
196 # wrapper around /proc/ settings to allow them to be hooked
197 # for testing
198 # 1st arg is relative path under /proc/, 2nd arg is value to set
199 set_proc ()
201     echo "$2" >"/proc/$1"
204 ######################################################
205 # wrapper around getting file contents from /proc/ to allow
206 # this to be hooked for testing
207 # 1st arg is relative path under /proc/
208 get_proc ()
210     cat "/proc/$1"
213 ######################################################
214 # Print up to $_max kernel stack traces for processes named $_program
215 program_stack_traces ()
217     _prog="$1"
218     _max="${2:-1}"
220     _count=1
221     for _pid in $(pidof "$_prog") ; do
222         [ $_count -le $_max ] || break
224         # Do this first to avoid racing with process exit
225         _stack=$(get_proc "${_pid}/stack" 2>/dev/null)
226         if [ -n "$_stack" ] ; then
227             echo "Stack trace for ${_prog}[${_pid}]:"
228             echo "$_stack"
229             _count=$(($_count + 1))
230         fi
231     done
234 ######################################################
235 # Check that an RPC service is healthy -
236 # this includes allowing a certain number of failures
237 # before marking the NFS service unhealthy.
239 # usage: nfs_check_rpc_service SERVICE_NAME [ triple ...]
241 # each triple is a set of 3 arguments: an operator, a 
242 # fail count limit and an action string.
244 # For example:
246 #       nfs_check_rpc_service "lockd" \
247 #           -ge 15 "verbose restart unhealthy" \
248 #           -eq 10 "restart:bs"
250 # says that if lockd is down for 15 iterations then do
251 # a verbose restart of lockd and mark the node unhealthy.
252 # Before this, after 10 iterations of failure, the
253 # service is restarted silently in the background.
254 # Order is important: the number of failures need to be
255 # specified in reverse order because processing stops
256 # after the first condition that is true.
257 ######################################################
258 nfs_check_rpc_service ()
260     _prog_name="$1" ; shift
262     if _nfs_check_rpc_common "$_prog_name" ; then
263         return
264     fi
266     while [ -n "$3" ] ; do
267         if _nfs_check_rpc_action "$1" "$2" "$3" ; then
268             break
269         fi
270         shift 3
271     done
274 # The new way of doing things...
275 nfs_check_rpc_services ()
277     # Files must end with .check - avoids editor backups, RPM fu, ...
278     for _f in "${CTDB_BASE}/nfs-rpc-checks.d/"[0-9][0-9].*.check ; do
279         _t="${_f%.check}"
280         _prog_name="${_t##*/[0-9][0-9].}"
282         if _nfs_check_rpc_common "$_prog_name" ; then
283             # This RPC service is up, check next service...
284             continue
285         fi
287         # Check each line in the file in turn until one of the limit
288         # checks is hit...
289         while read _cmp _lim _rest ; do
290             # Skip comments
291             case "$_cmp" in
292                 \#*) continue ;;
293             esac
295             if _nfs_check_rpc_action "$_cmp" "$_lim" "$_rest" ; then
296                 # Limit was hit on this line, no further checking...
297                 break
298             fi
299         done <"$_f"
300     done
303 _nfs_check_rpc_common ()
305     _prog_name="$1"
307     # Some platforms don't have separate programs for all services.
308     case "$_prog_name" in
309         statd)
310             which "rpc.${_prog_name}" >/dev/null 2>&1 || return 0
311     esac
313     case "$_prog_name" in
314         nfsd)
315             _rpc_prog=nfs
316             _version=3
317             ;;
318         mountd)
319             _rpc_prog=mountd
320             _version=1
321             ;;
322         rquotad)
323             _rpc_prog=rquotad
324             _version=1
325             ;;
326         lockd)
327             _rpc_prog=nlockmgr
328             _version=4
329             ;;
330         statd)
331             _rpc_prog=status
332             _version=1
333             ;;
334         *)
335             echo "Internal error: unknown RPC program \"$_prog_name\"."
336             exit 1
337     esac
339     _service_name="nfs_${_prog_name}"
341     if ctdb_check_rpc "$_rpc_prog" $_version >/dev/null ; then
342         ctdb_counter_init "$_service_name"
343         return 0
344     fi
346     ctdb_counter_incr "$_service_name"
348     return 1
351 _nfs_check_rpc_action ()
353     _cmp="$1"
354     _limit="$2"
355     _actions="$3"
357     if ctdb_check_counter "quiet" "$_cmp" "$_limit" "$_service_name" ; then
358         return 1
359     fi
361     for _action in $_actions ; do
362         case "$_action" in
363             verbose)
364                 echo "$ctdb_check_rpc_out"
365                 ;;
366             restart)
367                 _nfs_restart_rpc_service "$_prog_name"
368                 ;;
369             restart:b)
370                 _nfs_restart_rpc_service "$_prog_name" true
371                 ;;
372             unhealthy)
373                 exit 1
374                 ;;
375             *)
376                 echo "Internal error: unknown action \"$_action\"."
377                 exit 1
378         esac
379     done
381     return 0
384 _nfs_restart_rpc_service ()
386     _prog_name="$1"
387     _background="${2:-false}"
389     if $_background ; then
390         _maybe_background="background_with_logging"
391     else
392         _maybe_background=""
393     fi
395     _p="rpc.${_prog_name}"
397     case "$_prog_name" in
398         nfsd)
399             echo "Trying to restart NFS service"
400             $_maybe_background startstop_nfs restart
401             ;;
402         mountd)
403             echo "Trying to restart $_prog_name [${_p}]"
404             killall -q -9 "$_p"
405             $_maybe_background $_p ${MOUNTD_PORT:+-p} $MOUNTD_PORT
406             ;;
407         rquotad)
408             echo "Trying to restart $_prog_name [${_p}]"
409             killall -q -9 "$_p"
410             $_maybe_background $_p ${RQUOTAD_PORT:+-p} $RQUOTAD_PORT
411             ;;
412         lockd)
413             echo "Trying to restart lock manager service"
414             $_maybe_background startstop_nfslock restart
415             ;;
416         statd)
417             echo "Trying to restart $_prog_name [${_p}]"
418             killall -q -9 "$_p"
419             $_maybe_background $_p \
420                 ${STATD_HOSTNAME:+-n} $STATD_HOSTNAME \
421                 ${STATD_PORT:+-p} $STATD_PORT \
422                 ${STATD_OUTGOING_PORT:+-o} $STATD_OUTGOING_PORT
423             ;;
424         *)
425             echo "Internal error: unknown RPC program \"$_prog_name\"."
426             exit 1
427     esac
430 ######################################################
431 # check that a rpc server is registered with portmap
432 # and responding to requests
433 # usage: ctdb_check_rpc SERVICE_NAME VERSION
434 ######################################################
435 ctdb_check_rpc ()
437     progname="$1"
438     version="$2"
440     _localhost="${CTDB_RPCINFO_LOCALHOST:-127.0.0.1}"
442     if ! ctdb_check_rpc_out=$(rpcinfo -u $_localhost $progname $version 2>&1) ; then
443         ctdb_check_rpc_out="ERROR: $progname failed RPC check:
444 $ctdb_check_rpc_out"
445         echo "$ctdb_check_rpc_out"
446         return 1
447     fi
450 ######################################################
451 # Ensure $service_name is set
452 assert_service_name ()
454     [ -n "$service_name" ] || die "INTERNAL ERROR: \$service_name not set"
457 ######################################################
458 # check a set of directories is available
459 # return 1 on a missing directory
460 # directories are read from stdin
461 ######################################################
462 ctdb_check_directories_probe()
464     while IFS="" read d ; do
465         case "$d" in
466             *%*)
467                 continue
468                 ;;
469             *)
470                 [ -d "${d}/." ] || return 1
471         esac
472     done
475 ######################################################
476 # check a set of directories is available
477 # directories are read from stdin
478 ######################################################
479 ctdb_check_directories()
481     ctdb_check_directories_probe || {
482         echo "ERROR: $service_name directory \"$d\" not available"
483         exit 1
484     }
487 ######################################################
488 # check a set of tcp ports
489 # usage: ctdb_check_tcp_ports <ports...>
490 ######################################################
492 # This flag file is created when a service is initially started.  It
493 # is deleted the first time TCP port checks for that service succeed.
494 # Until then ctdb_check_tcp_ports() prints a more subtle "error"
495 # message if a port check fails.
496 _ctdb_check_tcp_common ()
498     assert_service_name
499     _ctdb_service_started_file="$ctdb_fail_dir/$service_name.started"
502 ctdb_check_tcp_init ()
504     _ctdb_check_tcp_common
505     mkdir -p "${_ctdb_service_started_file%/*}" # dirname
506     touch "$_ctdb_service_started_file"
509 # Check whether something is listening on all of the given TCP ports
510 # using the "ctdb checktcpport" command.
511 ctdb_check_tcp_ports()
513     if [ -z "$1" ] ; then
514         echo "INTERNAL ERROR: ctdb_check_tcp_ports - no ports specified"
515         exit 1
516     fi
518     for _p ; do  # process each function argument (port)
519         _cmd="ctdb checktcpport $_p"
520         _out=$($_cmd 2>&1)
521         _ret=$?
522         case "$_ret" in
523             0)
524                 _ctdb_check_tcp_common
525                 if [ ! -f "$_ctdb_service_started_file" ] ; then
526                     echo "ERROR: $service_name tcp port $_p is not responding"
527                     debug "\"ctdb checktcpport $_p\" was able to bind to port"
528                 else
529                     echo "INFO: $service_name tcp port $_p is not responding"
530                 fi
532                 return 1
533                 ;;
534             98)
535                 # Couldn't bind, something already listening, next port...
536                 continue
537                 ;;
538             *)
539                 echo "ERROR: unexpected error running \"ctdb checktcpport\""
540                 debug <<EOF
541 ctdb checktcpport (exited with $_ret) with output:
542 $_out"
544                 return $_ret
545         esac
546     done
548     # All ports listening
549     _ctdb_check_tcp_common
550     rm -f "$_ctdb_service_started_file"
551     return 0
554 ######################################################
555 # check a unix socket
556 # usage: ctdb_check_unix_socket SERVICE_NAME <socket_path>
557 ######################################################
558 ctdb_check_unix_socket() {
559     socket_path="$1"
560     [ -z "$socket_path" ] && return
562     if ! netstat --unix -a -n | grep -q "^unix.*LISTEN.*${socket_path}$"; then
563         echo "ERROR: $service_name socket $socket_path not found"
564         return 1
565     fi
568 ######################################################
569 # check a command returns zero status
570 # usage: ctdb_check_command <command>
571 ######################################################
572 ctdb_check_command ()
574     _out=$("$@" 2>&1) || {
575         echo "ERROR: $* returned error"
576         echo "$_out" | debug
577         exit 1
578     }
581 ################################################
582 # kill off any TCP connections with the given IP
583 ################################################
584 kill_tcp_connections ()
586     _ip="$1"
588     _oneway=false
589     if [ "$2" = "oneway" ] ; then
590         _oneway=true
591     fi
593     get_tcp_connections_for_ip "$_ip" | {
594         _killcount=0
595         _connections=""
596         _nl="
598         while read _dst _src; do
599             _destport="${_dst##*:}"
600             __oneway=$_oneway
601             case $_destport in
602                 # we only do one-way killtcp for CIFS
603                 139|445) __oneway=true ;;
604             esac
606             echo "Killing TCP connection $_src $_dst"
607             _connections="${_connections}${_nl}${_src} ${_dst}"
608             if ! $__oneway ; then
609                 _connections="${_connections}${_nl}${_dst} ${_src}"
610             fi
612             _killcount=$(($_killcount + 1))
613         done
615         if [ $_killcount -eq 0 ] ; then
616             return
617         fi
619         echo "$_connections" | ctdb killtcp || {
620             echo "Failed to send killtcp control"
621             return
622         }
624         _count=0
625         while : ; do
626             _remaining=$(get_tcp_connections_for_ip $_ip | wc -l)
628             if [ $_remaining -eq 0 ] ; then
629                 echo "Killed $_killcount TCP connections to released IP $_ip"
630                 return
631             fi
633             _count=$(($_count + 1))
634             if [ $_count -gt 3 ] ; then
635                 echo "Timed out killing tcp connections for IP $_ip ($_remaining remaining)"
636                 return
637             fi
639             echo "Waiting for $_remaining connections to be killed for IP $_ip"
640             sleep 1
641         done
642     }
645 ##################################################################
646 # kill off the local end for any TCP connections with the given IP
647 ##################################################################
648 kill_tcp_connections_local_only ()
650     kill_tcp_connections "$1" "oneway"
653 ##################################################################
654 # tickle any TCP connections with the given IP
655 ##################################################################
656 tickle_tcp_connections ()
658     _ip="$1"
660     get_tcp_connections_for_ip "$_ip" |
661     {
662         _failed=false
664         while read dest src; do
665             echo "Tickle TCP connection $src $dest"
666             ctdb tickle $src $dest >/dev/null 2>&1 || _failed=true
667             echo "Tickle TCP connection $dest $src"
668             ctdb tickle $dest $src >/dev/null 2>&1 || _failed=true
669         done
671         if $_failed ; then
672             echo "Failed to send tickle control"
673         fi
674     }
677 get_tcp_connections_for_ip ()
679     _ip="$1"
681     netstat -tn | awk -v ip=$_ip \
682         'index($1, "tcp") == 1 && \
683          (index($4, ip ":") == 1 || index($4, "::ffff:" ip ":") == 1) \
684          && $6 == "ESTABLISHED" \
685          {print $4" "$5}'
688 ########################################################
689 # start/stop the Ganesha nfs service
690 ########################################################
691 startstop_ganesha()
693     _service_name="nfs-ganesha-$CTDB_CLUSTER_FILESYSTEM_TYPE"
694     case "$1" in
695         start)
696             service "$_service_name" start
697             ;;
698         stop)
699             service "$_service_name" stop
700             ;;
701         restart)
702             service "$_service_name" restart
703             ;;
704     esac
707 ########################################################
708 # start/stop the nfs service on different platforms
709 ########################################################
710 startstop_nfs() {
711         PLATFORM="unknown"
712         [ -x $CTDB_ETCDIR/init.d/nfsserver ] && {
713                 PLATFORM="sles"
714         }
715         [ -x $CTDB_ETCDIR/init.d/nfslock -o \
716             -r /usr/lib/systemd/system/nfs-lock.service ] && {
717                 PLATFORM="rhel"
718         }
720         case $PLATFORM in
721         sles)
722                 case $1 in
723                 start)
724                         service nfsserver start
725                         ;;
726                 stop)
727                         service nfsserver stop > /dev/null 2>&1
728                         ;;
729                 restart)
730                         set_proc "fs/nfsd/threads" 0
731                         service nfsserver stop > /dev/null 2>&1
732                         pkill -9 nfsd
733                         nfs_dump_some_threads
734                         service nfsserver start
735                         ;;
736                 esac
737                 ;;
738         rhel)
739                 case $1 in
740                 start)
741                         service nfslock start
742                         service nfs start
743                         ;;
744                 stop)
745                         service nfs stop
746                         service nfslock stop
747                         ;;
748                 restart)
749                         set_proc "fs/nfsd/threads" 0
750                         service nfs stop > /dev/null 2>&1
751                         service nfslock stop > /dev/null 2>&1
752                         pkill -9 nfsd
753                         nfs_dump_some_threads
754                         service nfslock start
755                         service nfs start
756                         ;;
757                 esac
758                 ;;
759         *)
760                 echo "Unknown platform. NFS is not supported with ctdb"
761                 exit 1
762                 ;;
763         esac
766 # Dump up to the configured number of nfsd thread backtraces.
767 nfs_dump_some_threads ()
769     _num="${CTDB_NFS_DUMP_STUCK_THREADS:-5}"
770     [ $_num -gt 0 ] || return 0
772     program_stack_traces "nfsd" $_num
775 ########################################################
776 # start/stop the nfs lockmanager service on different platforms
777 ########################################################
778 startstop_nfslock() {
779         PLATFORM="unknown"
780         [ -x $CTDB_ETCDIR/init.d/nfsserver ] && {
781                 PLATFORM="sles"
782         }
783         [ -x $CTDB_ETCDIR/init.d/nfslock -o \
784             -r /usr/lib/systemd/system/nfs-lock.service ] && {
785                 PLATFORM="rhel"
786         }
788         case $PLATFORM in
789         sles)
790                 # for sles there is no service for lockmanager
791                 # so we instead just shutdown/restart nfs
792                 case $1 in
793                 start)
794                         service nfsserver start
795                         ;;
796                 stop)
797                         service nfsserver stop > /dev/null 2>&1
798                         ;;
799                 restart)
800                         service nfsserver stop > /dev/null 2>&1
801                         service nfsserver start
802                         ;;
803                 esac
804                 ;;
805         rhel)
806                 case $1 in
807                 start)
808                         service nfslock start
809                         ;;
810                 stop)
811                         service nfslock stop > /dev/null 2>&1
812                         ;;
813                 restart)
814                         service nfslock stop > /dev/null 2>&1
815                         service nfslock start
816                         ;;
817                 esac
818                 ;;
819         *)
820                 echo "Unknown platform. NFS locking is not supported with ctdb"
821                 exit 1
822                 ;;
823         esac
826 # Periodically update the statd database
827 nfs_statd_update ()
829     _update_period="$1"
831     _statd_update_trigger="$service_state_dir/update-trigger"
832     [ -f "$_statd_update_trigger" ] || touch "$_statd_update_trigger"
834     _last_update=$(stat --printf="%Y" "$_statd_update_trigger")
835     _current_time=$(date +"%s")
836     if [ $(( $_current_time - $_last_update)) -ge $_update_period ] ; then
837         touch "$_statd_update_trigger"
838         $CTDB_BASE/statd-callout updatelocal &
839         $CTDB_BASE/statd-callout updateremote &
840     fi
843 ########################################################
845 add_ip_to_iface ()
847     _iface=$1
848     _ip=$2
849     _maskbits=$3
851     # Ensure interface is up
852     ip link set "$_iface" up || \
853         die "Failed to bringup interface $_iface"
855     ip addr add "$_ip/$_maskbits" brd + dev "$_iface" || {
856         echo "Failed to add $_ip/$_maskbits on dev $_iface"
857         return 1
858     }
861 delete_ip_from_iface()
863     _iface=$1
864     _ip=$2
865     _maskbits=$3
867     # This could be set globally for all interfaces but it is probably
868     # better to avoid surprises, so limit it the interfaces where CTDB
869     # has public IP addresses.  There isn't anywhere else convenient
870     # to do this so just set it each time.  This is much cheaper than
871     # remembering and re-adding secondaries.
872     set_proc "sys/net/ipv4/conf/${_iface}/promote_secondaries" 1
874     ip addr del "$_ip/$_maskbits" dev "$_iface" || {
875         echo "Failed to del $_ip on dev $_iface"
876         return 1
877     }
880 # If the given IP is hosted then print 2 items: maskbits and iface 
881 ip_maskbits_iface ()
883     _addr="$1"
885     ip addr show to "${_addr}/32" 2>/dev/null | \
886         awk '$1 == "inet" { print gensub(".*/", "", 1, $2), $NF }'
889 drop_ip ()
891     _addr="${1%/*}"  # Remove optional maskbits
893     set -- $(ip_maskbits_iface $_addr)
894     if [ -n "$1" ] ; then
895         _maskbits="$1"
896         _iface="$2"
897         echo "Removing public address $_addr/$_maskbits from device $_iface"
898         delete_ip_from_iface $_iface $_addr $_maskbits >/dev/null 2>&1
899     fi
902 drop_all_public_ips ()
904     while read _ip _x ; do
905         drop_ip "$_ip"
906     done <"${CTDB_PUBLIC_ADDRESSES:-/dev/null}"
909 ########################################################
910 # Simple counters
911 _ctdb_counter_common () {
912     _service_name="${1:-${service_name:-${script_name}}}"
913     _counter_file="$ctdb_fail_dir/$_service_name"
914     mkdir -p "${_counter_file%/*}" # dirname
916 ctdb_counter_init () {
917     _ctdb_counter_common "$1"
919     >"$_counter_file"
921 ctdb_counter_incr () {
922     _ctdb_counter_common "$1"
924     # unary counting!
925     echo -n 1 >> "$_counter_file"
927 ctdb_check_counter () {
928     _msg="${1:-error}"  # "error"  - anything else is silent on fail
929     _op="${2:--ge}"  # an integer operator supported by test
930     _limit="${3:-${service_fail_limit}}"
931     shift 3
932     _ctdb_counter_common "$1"
934     # unary counting!
935     _size=$(stat -c "%s" "$_counter_file" 2>/dev/null || echo 0)
936     _hit=false
937     if [ "$_op" != "%" ] ; then
938         if [ $_size $_op $_limit ] ; then
939             _hit=true
940         fi
941     else
942         if [ $(($_size $_op $_limit)) -eq 0 ] ; then
943             _hit=true
944         fi
945     fi
946     if $_hit ; then
947         if [ "$_msg" = "error" ] ; then
948             echo "ERROR: $_size consecutive failures for $_service_name, marking node unhealthy"
949             exit 1              
950         else
951             return 1
952         fi
953     fi
956 ########################################################
958 ctdb_status_dir="$CTDB_VARDIR/state/service_status"
959 ctdb_fail_dir="$CTDB_VARDIR/state/failcount"
961 ctdb_setup_service_state_dir ()
963     service_state_dir="$CTDB_VARDIR/state/service_state/${1:-${service_name}}"
964     mkdir -p "$service_state_dir" || {
965         echo "Error creating state dir \"$service_state_dir\""
966         exit 1
967     }
970 ########################################################
971 # Managed status history, for auto-start/stop
973 ctdb_managed_dir="$CTDB_VARDIR/state/managed_history"
975 _ctdb_managed_common ()
977     _ctdb_managed_file="$ctdb_managed_dir/$service_name"
980 ctdb_service_managed ()
982     _ctdb_managed_common
983     mkdir -p "$ctdb_managed_dir"
984     touch "$_ctdb_managed_file"
987 ctdb_service_unmanaged ()
989     _ctdb_managed_common
990     rm -f "$_ctdb_managed_file"
993 is_ctdb_previously_managed_service ()
995     _ctdb_managed_common
996     [ -f "$_ctdb_managed_file" ]
999 ########################################################
1000 # Check and set status
1002 log_status_cat ()
1004     echo "node is \"$1\", \"${script_name}\" reports problem: $(cat $2)"
1007 ctdb_checkstatus ()
1009     if [ -r "$ctdb_status_dir/$script_name/unhealthy" ] ; then
1010         log_status_cat "unhealthy" "$ctdb_status_dir/$script_name/unhealthy"
1011         return 1
1012     elif [ -r "$ctdb_status_dir/$script_name/banned" ] ; then
1013         log_status_cat "banned" "$ctdb_status_dir/$script_name/banned"
1014         return 2
1015     else
1016         return 0
1017     fi
1020 ctdb_setstatus ()
1022     d="$ctdb_status_dir/$script_name"
1023     case "$1" in
1024         unhealthy|banned)
1025             mkdir -p "$d"
1026             cat "$2" >"$d/$1"
1027             ;;
1028         *)
1029             for i in "banned" "unhealthy" ; do
1030                 rm -f "$d/$i"
1031             done
1032             ;;
1033     esac
1036 ##################################################################
1037 # Reconfigure a service on demand
1039 _ctdb_service_reconfigure_common ()
1041     _d="$ctdb_status_dir/${service_name}"
1042     mkdir -p "$_d"
1043     _ctdb_service_reconfigure_flag="$_d/reconfigure"
1046 ctdb_service_needs_reconfigure ()
1048     _ctdb_service_reconfigure_common
1049     [ -e "$_ctdb_service_reconfigure_flag" ]
1052 ctdb_service_set_reconfigure ()
1054     _ctdb_service_reconfigure_common
1055     >"$_ctdb_service_reconfigure_flag"
1058 ctdb_service_unset_reconfigure ()
1060     _ctdb_service_reconfigure_common
1061     rm -f "$_ctdb_service_reconfigure_flag"
1064 ctdb_service_reconfigure ()
1066     echo "Reconfiguring service \"${service_name}\"..."
1067     ctdb_service_unset_reconfigure
1068     service_reconfigure || return $?
1069     ctdb_counter_init
1072 # Default service_reconfigure() function does nothing.
1073 service_reconfigure ()
1075     :
1078 ctdb_reconfigure_take_lock ()
1080     _ctdb_service_reconfigure_common
1081     _lock="${_d}/reconfigure_lock"
1082     mkdir -p "${_lock%/*}" # dirname
1083     touch "$_lock"
1085     (
1086         flock 0
1087         # This is overkill but will work if we need to extend this to
1088         # allow certain events to run multiple times in parallel
1089         # (e.g. takeip) and write multiple PIDs to the file.
1090         read _locker_event 
1091         if [ -n "$_locker_event" ] ; then
1092             while read _pid ; do
1093                 if [ -n "$_pid" -a "$_pid" != $$ ] && \
1094                     kill -0 "$_pid" 2>/dev/null ; then
1095                     exit 1
1096                 fi
1097             done
1098         fi
1100         printf "%s\n%s\n" "$event_name" $$ >"$_lock"
1101         exit 0
1102     ) <"$_lock"
1105 ctdb_reconfigure_release_lock ()
1107     _ctdb_service_reconfigure_common
1108     _lock="${_d}/reconfigure_lock"
1110     rm -f "$_lock"
1113 ctdb_replay_monitor_status ()
1115     echo "Replaying previous status for this script due to reconfigure..."
1116     # Leading colon (':') is missing in some versions...
1117     _out=$(ctdb scriptstatus -Y | grep -E "^:?monitor:${script_name}:")
1118     # Output looks like this:
1119     # :monitor:60.nfs:1:ERROR:1314764004.030861:1314764004.035514:foo bar:
1120     # This is the cheapest way of getting fields in the middle.
1121     set -- $(IFS=":" ; echo $_out)
1122     _code="$3"
1123     _status="$4"
1124     # The error output field can include colons so we'll try to
1125     # preserve them.  The weak checking at the beginning tries to make
1126     # this work for both broken (no leading ':') and fixed output.
1127     _out="${_out%:}"
1128     _err_out="${_out#*monitor:${script_name}:*:*:*:*:}"
1129     case "$_status" in
1130         OK) : ;;  # Do nothing special.
1131         TIMEDOUT)
1132             # Recast this as an error, since we can't exit with the
1133             # correct negative number.
1134             _code=1
1135             _err_out="[Replay of TIMEDOUT scriptstatus - note incorrect return code.] ${_err_out}"
1136             ;;
1137         DISABLED)
1138             # Recast this as an OK, since we can't exit with the
1139             # correct negative number.
1140             _code=0
1141             _err_out="[Replay of DISABLED scriptstatus - note incorrect return code.] ${_err_out}"
1142             ;;
1143         *) : ;;  # Must be ERROR, do nothing special.
1144     esac
1145     if [ -n "$_err_out" ] ; then
1146         echo "$_err_out"
1147     fi
1148     exit $_code
1151 ctdb_service_check_reconfigure ()
1153     assert_service_name
1155     # We only care about some events in this function.  For others we
1156     # return now.
1157     case "$event_name" in
1158         monitor|ipreallocated|reconfigure) : ;;
1159         *) return 0 ;;
1160     esac
1162     if ctdb_reconfigure_take_lock ; then
1163         # No events covered by this function are running, so proceed
1164         # with gay abandon.
1165         case "$event_name" in
1166             reconfigure)
1167                 (ctdb_service_reconfigure)
1168                 exit $?
1169                 ;;
1170             ipreallocated)
1171                 if ctdb_service_needs_reconfigure ; then
1172                     ctdb_service_reconfigure
1173                 fi
1174                 ;;
1175         esac
1177         ctdb_reconfigure_release_lock
1178     else
1179         # Somebody else is running an event we don't want to collide
1180         # with.  We proceed with caution.
1181         case "$event_name" in
1182             reconfigure)
1183                 # Tell whoever called us to retry.
1184                 exit 2
1185                 ;;
1186             ipreallocated)
1187                 # Defer any scheduled reconfigure and just run the
1188                 # rest of the ipreallocated event, as per the
1189                 # eventscript.  There's an assumption here that the
1190                 # event doesn't depend on any scheduled reconfigure.
1191                 # This is true in the current code.
1192                 return 0
1193                 ;;
1194             monitor)
1195                 # There is most likely a reconfigure in progress so
1196                 # the service is possibly unstable.  As above, we
1197                 # defer any scheduled reconfigured.  We also replay
1198                 # the previous monitor status since that's the best
1199                 # information we have.
1200                 ctdb_replay_monitor_status
1201                 ;;
1202         esac
1203     fi
1206 ##################################################################
1207 # Does CTDB manage this service? - and associated auto-start/stop
1209 ctdb_compat_managed_service ()
1211     if [ "$1" = "yes" -a "$2" = "$service_name" ] ; then
1212         CTDB_MANAGED_SERVICES="$CTDB_MANAGED_SERVICES $2"
1213     fi
1216 is_ctdb_managed_service ()
1218     assert_service_name
1220     # $t is used just for readability and to allow better accurate
1221     # matching via leading/trailing spaces
1222     t=" $CTDB_MANAGED_SERVICES "
1224     # Return 0 if "<space>$service_name<space>" appears in $t
1225     if [ "${t#* ${service_name} }" != "${t}" ] ; then
1226         return 0
1227     fi
1229     # If above didn't match then update $CTDB_MANAGED_SERVICES for
1230     # backward compatibility and try again.
1231     ctdb_compat_managed_service "$CTDB_MANAGES_VSFTPD"   "vsftpd"
1232     ctdb_compat_managed_service "$CTDB_MANAGES_SAMBA"    "samba"
1233     ctdb_compat_managed_service "$CTDB_MANAGES_WINBIND"  "winbind"
1234     ctdb_compat_managed_service "$CTDB_MANAGES_HTTPD"    "apache2"
1235     ctdb_compat_managed_service "$CTDB_MANAGES_HTTPD"    "httpd"
1236     ctdb_compat_managed_service "$CTDB_MANAGES_ISCSI"    "iscsi"
1237     ctdb_compat_managed_service "$CTDB_MANAGES_CLAMD"    "clamd"
1238     ctdb_compat_managed_service "$CTDB_MANAGES_NFS"      "nfs"
1239     ctdb_compat_managed_service "$CTDB_MANAGES_NFS"      "nfs-ganesha-gpfs"
1241     t=" $CTDB_MANAGED_SERVICES "
1243     # Return 0 if "<space>$service_name<space>" appears in $t
1244     [ "${t#* ${service_name} }" != "${t}" ]
1247 ctdb_start_stop_service ()
1249     assert_service_name
1251     # Allow service-start/service-stop pseudo-events to start/stop
1252     # services when we're not auto-starting/stopping and we're not
1253     # monitoring.
1254     case "$event_name" in
1255         service-start)
1256             if is_ctdb_managed_service ; then
1257                 die 'service-start event not permitted when service is managed'
1258             fi
1259             if [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] ; then
1260                 die 'service-start event not permitted with $CTDB_SERVICE_AUTOSTARTSTOP = yes'
1261             fi
1262             ctdb_service_start
1263             exit $?
1264             ;;
1265         service-stop)
1266             if is_ctdb_managed_service ; then
1267                 die 'service-stop event not permitted when service is managed'
1268             fi
1269             if [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] ; then
1270                 die 'service-stop event not permitted with $CTDB_SERVICE_AUTOSTARTSTOP = yes'
1271             fi
1272             ctdb_service_stop
1273             exit $?
1274             ;;
1275     esac
1277     # Do nothing unless configured to...
1278     [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] || return 0
1280     [ "$event_name" = "monitor" ] || return 0
1282     if is_ctdb_managed_service ; then
1283         if ! is_ctdb_previously_managed_service ; then
1284             echo "Starting service \"$service_name\" - now managed"
1285             background_with_logging ctdb_service_start
1286             exit $?
1287         fi
1288     else
1289         if is_ctdb_previously_managed_service ; then
1290             echo "Stopping service \"$service_name\" - no longer managed"
1291             background_with_logging ctdb_service_stop
1292             exit $?
1293         fi
1294     fi
1297 ctdb_service_start ()
1299     # The service is marked managed if we've ever tried to start it.
1300     ctdb_service_managed
1302     service_start || return $?
1304     ctdb_counter_init
1305     ctdb_check_tcp_init
1308 ctdb_service_stop ()
1310     ctdb_service_unmanaged
1311     service_stop
1314 # Default service_start() and service_stop() functions.
1316 # These may be overridden in an eventscript.
1317 service_start ()
1319     service "$service_name" start
1322 service_stop ()
1324     service "$service_name" stop
1327 ##################################################################
1329 ctdb_standard_event_handler ()
1331     case "$1" in
1332         status)
1333             ctdb_checkstatus
1334             exit
1335             ;;
1336         setstatus)
1337             shift
1338             ctdb_setstatus "$@"
1339             exit
1340             ;;
1341     esac
1344 # iptables doesn't like being re-entered, so flock-wrap it.
1345 iptables()
1347         flock -w 30 $CTDB_VARDIR/iptables-ctdb.flock /sbin/iptables "$@"
1350 # AIX (and perhaps others?) doesn't have mktemp
1351 if ! which mktemp >/dev/null 2>&1 ; then
1352     mktemp ()
1353     {
1354         _dir=false
1355         if [ "$1" = "-d" ] ; then
1356             _dir=true
1357             shift
1358         fi
1359         _d="${TMPDIR:-/tmp}"
1360         _hex10=$(dd if=/dev/urandom count=20 2>/dev/null | \
1361             md5sum | \
1362             sed -e 's@\(..........\).*@\1@')
1363         _t="${_d}/tmp.${_hex10}"
1364         (
1365             umask 077
1366             if $_dir ; then
1367                 mkdir "$_t"
1368             else
1369                 >"$_t"
1370             fi
1371         )
1372         echo "$_t"
1373     }
1376 ########################################################
1377 # tickle handling
1378 ########################################################
1380 update_tickles ()
1382         _port="$1"
1384         tickledir="$CTDB_VARDIR/state/tickles"
1385         mkdir -p "$tickledir"
1387         # Who am I?
1388         _pnn=$(ctdb pnn) ; _pnn=${_pnn#PNN:}
1390         # What public IPs do I hold?
1391         _ips=$(ctdb -Y ip | awk -F: -v pnn=$_pnn '$3 == pnn {print $2}')
1393         # IPs as a regexp choice
1394         _ipschoice="($(echo $_ips | sed -e 's/ /|/g' -e 's/\./\\\\./g'))"
1396         # Record connections to our public IPs in a temporary file
1397         _my_connections="${tickledir}/${_port}.connections"
1398         rm -f "$_my_connections"
1399         netstat -tn |
1400         awk -v destpat="^${_ipschoice}:${_port}\$" \
1401           '$1 == "tcp" && $6 == "ESTABLISHED" && $4 ~ destpat {print $5, $4}' |
1402         sort >"$_my_connections"
1404         # Record our current tickles in a temporary file
1405         _my_tickles="${tickledir}/${_port}.tickles"
1406         rm -f "$_my_tickles"
1407         for _i in $_ips ; do
1408                 ctdb -Y gettickles $_i $_port | 
1409                 awk -F: 'NR > 1 { printf "%s:%s %s:%s\n", $2, $3, $4, $5 }'
1410         done |
1411         sort >"$_my_tickles"
1413         # Add tickles for connections that we haven't already got tickles for
1414         comm -23 "$_my_connections" "$_my_tickles" |
1415         while read _src _dst ; do
1416                 ctdb addtickle $_src $_dst
1417         done
1419         # Remove tickles for connections that are no longer there
1420         comm -13 "$_my_connections" "$_my_tickles" |
1421         while read _src _dst ; do
1422                 ctdb deltickle $_src $_dst
1423         done
1425         rm -f "$_my_connections" "$_my_tickles" 
1428 ########################################################
1429 # load a site local config file
1430 ########################################################
1432 [ -n "$CTDB_RC_LOCAL" -a -x "$CTDB_RC_LOCAL" ] && {
1433         . "$CTDB_RC_LOCAL"
1436 [ -x $CTDB_BASE/rc.local ] && {
1437         . $CTDB_BASE/rc.local
1440 [ -d $CTDB_BASE/rc.local.d ] && {
1441         for i in $CTDB_BASE/rc.local.d/* ; do
1442                 [ -x "$i" ] && . "$i"
1443         done
1446 script_name="${0##*/}"       # basename
1447 service_fail_limit=1
1448 event_name="$1"