Skip to content

Instantly share code, notes, and snippets.

@TvL2386
Created October 27, 2011 05:25
Show Gist options
  • Save TvL2386/1318848 to your computer and use it in GitHub Desktop.
Save TvL2386/1318848 to your computer and use it in GitHub Desktop.
A Keepalived script
#!/usr/bin/ruby
# This is in my keepalived.conf
# ...
# notify_master "/usr/tools/keepalived/notify.sh primary"
# notify_backup "/usr/tools/keepalived/notify.sh backup"
# notify_fault "/usr/tools/keepalived/notify.sh fault"
# ...
require 'socket'
require 'logger'
require 'thread'
include Socket::Constants
pid = fork do
SCRIPTS = %w[radvd.sh conntrack.sh dhcp.sh routes.sh]
$workdir = '/usr/tools/keepalived'
LOG = Logger.new("/var/log/keepalived-notifier.log", 2, 1024*1024) # rotate after 1MB and keep 2 copies
LOG.level = Logger::INFO
LOG.datetime_format = '%Y-%m-%d %H:%M:%S'
LOG.info "Application started!"
mutex = Mutex.new
action = 0
act = 0
state_back = 0
state_prim = 0
time_start = Time.now.to_i
time_now = Time.now.to_i
Thread.start do
loop do
sleep 1800
mutex.synchronize do
LOG.info "stats: primary: #{state_prim} backup: #{state_back}"
end
end
end
socket = UDPSocket.new
socket.bind(nil, 503)
loop do
text, sender = socket.recvfrom(16384)
len = text.length-1
char = len == 0 ? text : text[len,len]
if char == "1"
LOG.info "Going primary"
mutex.synchronize { state_prim += 1 }
Dir.chdir $workdir do
SCRIPTS.each do |s|
next unless File.exist? s
cmd = "./#{s} primary"
LOG.info " Executing '#{cmd}'"
`#{cmd}`
LOG.info " Done executing '#{cmd}'"
end
end
LOG.info "Done"
elsif char == "2"
LOG.info "Going backup"
mutex.synchronize { state_back += 1 }
Dir.chdir $workdir do
SCRIPTS.each do |s|
next unless File.exist? s
cmd = "./#{s} backup"
LOG.info " Executing '#{cmd}'"
`#{cmd}`
LOG.info " Done executing '#{cmd}'"
end
end
LOG.info "Done"
elsif char == "3"
LOG.info "Going fault"
mutex.synchronize { state_back += 1 }
Dir.chdir $workdir do
SCRIPTS.each do |s|
next unless File.exist? s
cmd = "./#{s} fault"
LOG.info " Executing '#{cmd}'"
`#{cmd}`
LOG.info " Done executing '#{cmd}'"
end
end
LOG.info "Done"
else
LOG.warn "Unknown action: #{char.gsub("\n",'\n')}"
end
end
end
# write pid
File.open("/var/run/keepalived-notifier.pid",'w') { |fh| fh.write pid }
# and detach
Process.detach pid
#!/bin/bash
if [ ! -e /var/run/keepalived-notifier.pid ]
then
(cd /usr/tools/keepalived && ./keepalived-notifier.rb)
sleep 2
fi
if [ -e /var/run/keepalived-notifier.pid ]
then
case "$1" in
primary)
echo -n 1 | nc -u 127.0.0.1 503
;;
backup)
echo -n 2 | nc -u 127.0.0.1 503
;;
fault)
echo -n 3 | nc -u 127.0.0.1 503
;;
*)
logger "ERROR: unknown state transition '$1'"
exit 1
;;
esac
else
logger "ERROR: file /var/run/keepalived-notifier.pid does not exist. Cannot notify..."
exit 1
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment