ctdb-scripts: Add optional program name argument to nfs_dump_some_threads()
[Samba.git] / ctdb / config / functions
blob377bc4ddf284bc25181fecc789562e4c7dbffbdd
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     _prog="${1:-nfsd}"
771     _num="${CTDB_NFS_DUMP_STUCK_THREADS:-5}"
772     [ $_num -gt 0 ] || return 0
774     program_stack_traces "$_prog" $_num
777 ########################################################
778 # start/stop the nfs lockmanager service on different platforms
779 ########################################################
780 startstop_nfslock() {
781         PLATFORM="unknown"
782         [ -x $CTDB_ETCDIR/init.d/nfsserver ] && {
783                 PLATFORM="sles"
784         }
785         [ -x $CTDB_ETCDIR/init.d/nfslock -o \
786             -r /usr/lib/systemd/system/nfs-lock.service ] && {
787                 PLATFORM="rhel"
788         }
790         case $PLATFORM in
791         sles)
792                 # for sles there is no service for lockmanager
793                 # so we instead just shutdown/restart nfs
794                 case $1 in
795                 start)
796                         service nfsserver start
797                         ;;
798                 stop)
799                         service nfsserver stop > /dev/null 2>&1
800                         ;;
801                 restart)
802                         service nfsserver stop > /dev/null 2>&1
803                         service nfsserver start
804                         ;;
805                 esac
806                 ;;
807         rhel)
808                 case $1 in
809                 start)
810                         service nfslock start
811                         ;;
812                 stop)
813                         service nfslock stop > /dev/null 2>&1
814                         ;;
815                 restart)
816                         service nfslock stop > /dev/null 2>&1
817                         service nfslock start
818                         ;;
819                 esac
820                 ;;
821         *)
822                 echo "Unknown platform. NFS locking is not supported with ctdb"
823                 exit 1
824                 ;;
825         esac
828 # Periodically update the statd database
829 nfs_statd_update ()
831     _update_period="$1"
833     _statd_update_trigger="$service_state_dir/update-trigger"
834     [ -f "$_statd_update_trigger" ] || touch "$_statd_update_trigger"
836     _last_update=$(stat --printf="%Y" "$_statd_update_trigger")
837     _current_time=$(date +"%s")
838     if [ $(( $_current_time - $_last_update)) -ge $_update_period ] ; then
839         touch "$_statd_update_trigger"
840         $CTDB_BASE/statd-callout updatelocal &
841         $CTDB_BASE/statd-callout updateremote &
842     fi
845 ########################################################
847 add_ip_to_iface ()
849     _iface=$1
850     _ip=$2
851     _maskbits=$3
853     # Ensure interface is up
854     ip link set "$_iface" up || \
855         die "Failed to bringup interface $_iface"
857     ip addr add "$_ip/$_maskbits" brd + dev "$_iface" || {
858         echo "Failed to add $_ip/$_maskbits on dev $_iface"
859         return 1
860     }
863 delete_ip_from_iface()
865     _iface=$1
866     _ip=$2
867     _maskbits=$3
869     # This could be set globally for all interfaces but it is probably
870     # better to avoid surprises, so limit it the interfaces where CTDB
871     # has public IP addresses.  There isn't anywhere else convenient
872     # to do this so just set it each time.  This is much cheaper than
873     # remembering and re-adding secondaries.
874     set_proc "sys/net/ipv4/conf/${_iface}/promote_secondaries" 1
876     ip addr del "$_ip/$_maskbits" dev "$_iface" || {
877         echo "Failed to del $_ip on dev $_iface"
878         return 1
879     }
882 # If the given IP is hosted then print 2 items: maskbits and iface 
883 ip_maskbits_iface ()
885     _addr="$1"
887     ip addr show to "${_addr}/32" 2>/dev/null | \
888         awk '$1 == "inet" { print gensub(".*/", "", 1, $2), $NF }'
891 drop_ip ()
893     _addr="${1%/*}"  # Remove optional maskbits
895     set -- $(ip_maskbits_iface $_addr)
896     if [ -n "$1" ] ; then
897         _maskbits="$1"
898         _iface="$2"
899         echo "Removing public address $_addr/$_maskbits from device $_iface"
900         delete_ip_from_iface $_iface $_addr $_maskbits >/dev/null 2>&1
901     fi
904 drop_all_public_ips ()
906     while read _ip _x ; do
907         drop_ip "$_ip"
908     done <"${CTDB_PUBLIC_ADDRESSES:-/dev/null}"
911 ########################################################
912 # Simple counters
913 _ctdb_counter_common () {
914     _service_name="${1:-${service_name:-${script_name}}}"
915     _counter_file="$ctdb_fail_dir/$_service_name"
916     mkdir -p "${_counter_file%/*}" # dirname
918 ctdb_counter_init () {
919     _ctdb_counter_common "$1"
921     >"$_counter_file"
923 ctdb_counter_incr () {
924     _ctdb_counter_common "$1"
926     # unary counting!
927     echo -n 1 >> "$_counter_file"
929 ctdb_check_counter () {
930     _msg="${1:-error}"  # "error"  - anything else is silent on fail
931     _op="${2:--ge}"  # an integer operator supported by test
932     _limit="${3:-${service_fail_limit}}"
933     shift 3
934     _ctdb_counter_common "$1"
936     # unary counting!
937     _size=$(stat -c "%s" "$_counter_file" 2>/dev/null || echo 0)
938     _hit=false
939     if [ "$_op" != "%" ] ; then
940         if [ $_size $_op $_limit ] ; then
941             _hit=true
942         fi
943     else
944         if [ $(($_size $_op $_limit)) -eq 0 ] ; then
945             _hit=true
946         fi
947     fi
948     if $_hit ; then
949         if [ "$_msg" = "error" ] ; then
950             echo "ERROR: $_size consecutive failures for $_service_name, marking node unhealthy"
951             exit 1              
952         else
953             return 1
954         fi
955     fi
958 ########################################################
960 ctdb_status_dir="$CTDB_VARDIR/state/service_status"
961 ctdb_fail_dir="$CTDB_VARDIR/state/failcount"
963 ctdb_setup_service_state_dir ()
965     service_state_dir="$CTDB_VARDIR/state/service_state/${1:-${service_name}}"
966     mkdir -p "$service_state_dir" || {
967         echo "Error creating state dir \"$service_state_dir\""
968         exit 1
969     }
972 ########################################################
973 # Managed status history, for auto-start/stop
975 ctdb_managed_dir="$CTDB_VARDIR/state/managed_history"
977 _ctdb_managed_common ()
979     _ctdb_managed_file="$ctdb_managed_dir/$service_name"
982 ctdb_service_managed ()
984     _ctdb_managed_common
985     mkdir -p "$ctdb_managed_dir"
986     touch "$_ctdb_managed_file"
989 ctdb_service_unmanaged ()
991     _ctdb_managed_common
992     rm -f "$_ctdb_managed_file"
995 is_ctdb_previously_managed_service ()
997     _ctdb_managed_common
998     [ -f "$_ctdb_managed_file" ]
1001 ########################################################
1002 # Check and set status
1004 log_status_cat ()
1006     echo "node is \"$1\", \"${script_name}\" reports problem: $(cat $2)"
1009 ctdb_checkstatus ()
1011     if [ -r "$ctdb_status_dir/$script_name/unhealthy" ] ; then
1012         log_status_cat "unhealthy" "$ctdb_status_dir/$script_name/unhealthy"
1013         return 1
1014     elif [ -r "$ctdb_status_dir/$script_name/banned" ] ; then
1015         log_status_cat "banned" "$ctdb_status_dir/$script_name/banned"
1016         return 2
1017     else
1018         return 0
1019     fi
1022 ctdb_setstatus ()
1024     d="$ctdb_status_dir/$script_name"
1025     case "$1" in
1026         unhealthy|banned)
1027             mkdir -p "$d"
1028             cat "$2" >"$d/$1"
1029             ;;
1030         *)
1031             for i in "banned" "unhealthy" ; do
1032                 rm -f "$d/$i"
1033             done
1034             ;;
1035     esac
1038 ##################################################################
1039 # Reconfigure a service on demand
1041 _ctdb_service_reconfigure_common ()
1043     _d="$ctdb_status_dir/${service_name}"
1044     mkdir -p "$_d"
1045     _ctdb_service_reconfigure_flag="$_d/reconfigure"
1048 ctdb_service_needs_reconfigure ()
1050     _ctdb_service_reconfigure_common
1051     [ -e "$_ctdb_service_reconfigure_flag" ]
1054 ctdb_service_set_reconfigure ()
1056     _ctdb_service_reconfigure_common
1057     >"$_ctdb_service_reconfigure_flag"
1060 ctdb_service_unset_reconfigure ()
1062     _ctdb_service_reconfigure_common
1063     rm -f "$_ctdb_service_reconfigure_flag"
1066 ctdb_service_reconfigure ()
1068     echo "Reconfiguring service \"${service_name}\"..."
1069     ctdb_service_unset_reconfigure
1070     service_reconfigure || return $?
1071     ctdb_counter_init
1074 # Default service_reconfigure() function does nothing.
1075 service_reconfigure ()
1077     :
1080 ctdb_reconfigure_take_lock ()
1082     _ctdb_service_reconfigure_common
1083     _lock="${_d}/reconfigure_lock"
1084     mkdir -p "${_lock%/*}" # dirname
1085     touch "$_lock"
1087     (
1088         flock 0
1089         # This is overkill but will work if we need to extend this to
1090         # allow certain events to run multiple times in parallel
1091         # (e.g. takeip) and write multiple PIDs to the file.
1092         read _locker_event 
1093         if [ -n "$_locker_event" ] ; then
1094             while read _pid ; do
1095                 if [ -n "$_pid" -a "$_pid" != $$ ] && \
1096                     kill -0 "$_pid" 2>/dev/null ; then
1097                     exit 1
1098                 fi
1099             done
1100         fi
1102         printf "%s\n%s\n" "$event_name" $$ >"$_lock"
1103         exit 0
1104     ) <"$_lock"
1107 ctdb_reconfigure_release_lock ()
1109     _ctdb_service_reconfigure_common
1110     _lock="${_d}/reconfigure_lock"
1112     rm -f "$_lock"
1115 ctdb_replay_monitor_status ()
1117     echo "Replaying previous status for this script due to reconfigure..."
1118     # Leading colon (':') is missing in some versions...
1119     _out=$(ctdb scriptstatus -Y | grep -E "^:?monitor:${script_name}:")
1120     # Output looks like this:
1121     # :monitor:60.nfs:1:ERROR:1314764004.030861:1314764004.035514:foo bar:
1122     # This is the cheapest way of getting fields in the middle.
1123     set -- $(IFS=":" ; echo $_out)
1124     _code="$3"
1125     _status="$4"
1126     # The error output field can include colons so we'll try to
1127     # preserve them.  The weak checking at the beginning tries to make
1128     # this work for both broken (no leading ':') and fixed output.
1129     _out="${_out%:}"
1130     _err_out="${_out#*monitor:${script_name}:*:*:*:*:}"
1131     case "$_status" in
1132         OK) : ;;  # Do nothing special.
1133         TIMEDOUT)
1134             # Recast this as an error, since we can't exit with the
1135             # correct negative number.
1136             _code=1
1137             _err_out="[Replay of TIMEDOUT scriptstatus - note incorrect return code.] ${_err_out}"
1138             ;;
1139         DISABLED)
1140             # Recast this as an OK, since we can't exit with the
1141             # correct negative number.
1142             _code=0
1143             _err_out="[Replay of DISABLED scriptstatus - note incorrect return code.] ${_err_out}"
1144             ;;
1145         *) : ;;  # Must be ERROR, do nothing special.
1146     esac
1147     if [ -n "$_err_out" ] ; then
1148         echo "$_err_out"
1149     fi
1150     exit $_code
1153 ctdb_service_check_reconfigure ()
1155     assert_service_name
1157     # We only care about some events in this function.  For others we
1158     # return now.
1159     case "$event_name" in
1160         monitor|ipreallocated|reconfigure) : ;;
1161         *) return 0 ;;
1162     esac
1164     if ctdb_reconfigure_take_lock ; then
1165         # No events covered by this function are running, so proceed
1166         # with gay abandon.
1167         case "$event_name" in
1168             reconfigure)
1169                 (ctdb_service_reconfigure)
1170                 exit $?
1171                 ;;
1172             ipreallocated)
1173                 if ctdb_service_needs_reconfigure ; then
1174                     ctdb_service_reconfigure
1175                 fi
1176                 ;;
1177         esac
1179         ctdb_reconfigure_release_lock
1180     else
1181         # Somebody else is running an event we don't want to collide
1182         # with.  We proceed with caution.
1183         case "$event_name" in
1184             reconfigure)
1185                 # Tell whoever called us to retry.
1186                 exit 2
1187                 ;;
1188             ipreallocated)
1189                 # Defer any scheduled reconfigure and just run the
1190                 # rest of the ipreallocated event, as per the
1191                 # eventscript.  There's an assumption here that the
1192                 # event doesn't depend on any scheduled reconfigure.
1193                 # This is true in the current code.
1194                 return 0
1195                 ;;
1196             monitor)
1197                 # There is most likely a reconfigure in progress so
1198                 # the service is possibly unstable.  As above, we
1199                 # defer any scheduled reconfigured.  We also replay
1200                 # the previous monitor status since that's the best
1201                 # information we have.
1202                 ctdb_replay_monitor_status
1203                 ;;
1204         esac
1205     fi
1208 ##################################################################
1209 # Does CTDB manage this service? - and associated auto-start/stop
1211 ctdb_compat_managed_service ()
1213     if [ "$1" = "yes" -a "$2" = "$service_name" ] ; then
1214         CTDB_MANAGED_SERVICES="$CTDB_MANAGED_SERVICES $2"
1215     fi
1218 is_ctdb_managed_service ()
1220     assert_service_name
1222     # $t is used just for readability and to allow better accurate
1223     # matching via leading/trailing spaces
1224     t=" $CTDB_MANAGED_SERVICES "
1226     # Return 0 if "<space>$service_name<space>" appears in $t
1227     if [ "${t#* ${service_name} }" != "${t}" ] ; then
1228         return 0
1229     fi
1231     # If above didn't match then update $CTDB_MANAGED_SERVICES for
1232     # backward compatibility and try again.
1233     ctdb_compat_managed_service "$CTDB_MANAGES_VSFTPD"   "vsftpd"
1234     ctdb_compat_managed_service "$CTDB_MANAGES_SAMBA"    "samba"
1235     ctdb_compat_managed_service "$CTDB_MANAGES_WINBIND"  "winbind"
1236     ctdb_compat_managed_service "$CTDB_MANAGES_HTTPD"    "apache2"
1237     ctdb_compat_managed_service "$CTDB_MANAGES_HTTPD"    "httpd"
1238     ctdb_compat_managed_service "$CTDB_MANAGES_ISCSI"    "iscsi"
1239     ctdb_compat_managed_service "$CTDB_MANAGES_CLAMD"    "clamd"
1240     ctdb_compat_managed_service "$CTDB_MANAGES_NFS"      "nfs"
1241     ctdb_compat_managed_service "$CTDB_MANAGES_NFS"      "nfs-ganesha-gpfs"
1243     t=" $CTDB_MANAGED_SERVICES "
1245     # Return 0 if "<space>$service_name<space>" appears in $t
1246     [ "${t#* ${service_name} }" != "${t}" ]
1249 ctdb_start_stop_service ()
1251     assert_service_name
1253     # Allow service-start/service-stop pseudo-events to start/stop
1254     # services when we're not auto-starting/stopping and we're not
1255     # monitoring.
1256     case "$event_name" in
1257         service-start)
1258             if is_ctdb_managed_service ; then
1259                 die 'service-start event not permitted when service is managed'
1260             fi
1261             if [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] ; then
1262                 die 'service-start event not permitted with $CTDB_SERVICE_AUTOSTARTSTOP = yes'
1263             fi
1264             ctdb_service_start
1265             exit $?
1266             ;;
1267         service-stop)
1268             if is_ctdb_managed_service ; then
1269                 die 'service-stop event not permitted when service is managed'
1270             fi
1271             if [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] ; then
1272                 die 'service-stop event not permitted with $CTDB_SERVICE_AUTOSTARTSTOP = yes'
1273             fi
1274             ctdb_service_stop
1275             exit $?
1276             ;;
1277     esac
1279     # Do nothing unless configured to...
1280     [ "$CTDB_SERVICE_AUTOSTARTSTOP" = "yes" ] || return 0
1282     [ "$event_name" = "monitor" ] || return 0
1284     if is_ctdb_managed_service ; then
1285         if ! is_ctdb_previously_managed_service ; then
1286             echo "Starting service \"$service_name\" - now managed"
1287             background_with_logging ctdb_service_start
1288             exit $?
1289         fi
1290     else
1291         if is_ctdb_previously_managed_service ; then
1292             echo "Stopping service \"$service_name\" - no longer managed"
1293             background_with_logging ctdb_service_stop
1294             exit $?
1295         fi
1296     fi
1299 ctdb_service_start ()
1301     # The service is marked managed if we've ever tried to start it.
1302     ctdb_service_managed
1304     service_start || return $?
1306     ctdb_counter_init
1307     ctdb_check_tcp_init
1310 ctdb_service_stop ()
1312     ctdb_service_unmanaged
1313     service_stop
1316 # Default service_start() and service_stop() functions.
1318 # These may be overridden in an eventscript.
1319 service_start ()
1321     service "$service_name" start
1324 service_stop ()
1326     service "$service_name" stop
1329 ##################################################################
1331 ctdb_standard_event_handler ()
1333     case "$1" in
1334         status)
1335             ctdb_checkstatus
1336             exit
1337             ;;
1338         setstatus)
1339             shift
1340             ctdb_setstatus "$@"
1341             exit
1342             ;;
1343     esac
1346 # iptables doesn't like being re-entered, so flock-wrap it.
1347 iptables()
1349         flock -w 30 $CTDB_VARDIR/iptables-ctdb.flock /sbin/iptables "$@"
1352 # AIX (and perhaps others?) doesn't have mktemp
1353 if ! which mktemp >/dev/null 2>&1 ; then
1354     mktemp ()
1355     {
1356         _dir=false
1357         if [ "$1" = "-d" ] ; then
1358             _dir=true
1359             shift
1360         fi
1361         _d="${TMPDIR:-/tmp}"
1362         _hex10=$(dd if=/dev/urandom count=20 2>/dev/null | \
1363             md5sum | \
1364             sed -e 's@\(..........\).*@\1@')
1365         _t="${_d}/tmp.${_hex10}"
1366         (
1367             umask 077
1368             if $_dir ; then
1369                 mkdir "$_t"
1370             else
1371                 >"$_t"
1372             fi
1373         )
1374         echo "$_t"
1375     }
1378 ########################################################
1379 # tickle handling
1380 ########################################################
1382 update_tickles ()
1384         _port="$1"
1386         tickledir="$CTDB_VARDIR/state/tickles"
1387         mkdir -p "$tickledir"
1389         # Who am I?
1390         _pnn=$(ctdb pnn) ; _pnn=${_pnn#PNN:}
1392         # What public IPs do I hold?
1393         _ips=$(ctdb -Y ip | awk -F: -v pnn=$_pnn '$3 == pnn {print $2}')
1395         # IPs as a regexp choice
1396         _ipschoice="($(echo $_ips | sed -e 's/ /|/g' -e 's/\./\\\\./g'))"
1398         # Record connections to our public IPs in a temporary file
1399         _my_connections="${tickledir}/${_port}.connections"
1400         rm -f "$_my_connections"
1401         netstat -tn |
1402         awk -v destpat="^${_ipschoice}:${_port}\$" \
1403           '$1 == "tcp" && $6 == "ESTABLISHED" && $4 ~ destpat {print $5, $4}' |
1404         sort >"$_my_connections"
1406         # Record our current tickles in a temporary file
1407         _my_tickles="${tickledir}/${_port}.tickles"
1408         rm -f "$_my_tickles"
1409         for _i in $_ips ; do
1410                 ctdb -Y gettickles $_i $_port | 
1411                 awk -F: 'NR > 1 { printf "%s:%s %s:%s\n", $2, $3, $4, $5 }'
1412         done |
1413         sort >"$_my_tickles"
1415         # Add tickles for connections that we haven't already got tickles for
1416         comm -23 "$_my_connections" "$_my_tickles" |
1417         while read _src _dst ; do
1418                 ctdb addtickle $_src $_dst
1419         done
1421         # Remove tickles for connections that are no longer there
1422         comm -13 "$_my_connections" "$_my_tickles" |
1423         while read _src _dst ; do
1424                 ctdb deltickle $_src $_dst
1425         done
1427         rm -f "$_my_connections" "$_my_tickles" 
1430 ########################################################
1431 # load a site local config file
1432 ########################################################
1434 [ -n "$CTDB_RC_LOCAL" -a -x "$CTDB_RC_LOCAL" ] && {
1435         . "$CTDB_RC_LOCAL"
1438 [ -x $CTDB_BASE/rc.local ] && {
1439         . $CTDB_BASE/rc.local
1442 [ -d $CTDB_BASE/rc.local.d ] && {
1443         for i in $CTDB_BASE/rc.local.d/* ; do
1444                 [ -x "$i" ] && . "$i"
1445         done
1448 script_name="${0##*/}"       # basename
1449 service_fail_limit=1
1450 event_name="$1"