|
#!/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 |