Skip to content

Instantly share code, notes, and snippets.

@rbarfoed
Created October 9, 2012 12:28
Show Gist options
  • Save rbarfoed/3858520 to your computer and use it in GitHub Desktop.
Save rbarfoed/3858520 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'thread'
require 'timeout'
require 'amqp'
require 'vcevent'
EventMachine.run {
# FIXME avoid hardcoding amqp url
connection = AMQP.connect('amqp://admin:pleasemakemerandom@localhost/vetconnect-dev')
channel = AMQP::Channel.new(connection, :auto_recovery => true)
channel.on_error do |ch, channel_close|
raise "Channel-level exception: #{channel_close.reply_text}"
end
@bouncer_lock = Mutex.new
@active_sync_lock = Mutex.new
@active_sync_runs = 0
@logger = VCEvent::Logger.new
channel.queue("", :durable => false, :auto_delete => true).bind("services_notification").subscribe do |metadata, payload|
#TODO selective sync only on VCOperation updates on special datatypes
begin
timeout = Timeout::timeout(5) {
sync
}
rescue Timeout::Error => e
@logger.warn "Got timeout #{e}"
end
end
def wait_on_sync_and_exit
@bouncer_lock.synchronize {
EM.stop
}
end
def sync
# avoid having more than one sync call waiting
# if we already have one sync call piled up waiting we won't gain anything adding more
@logger.debug "Starting sync"
@active_sync_lock.synchronize {
if @active_sync_runs > 1 then
return
end
@active_sync_runs += 1
}
begin
@bouncer_lock.synchronize {
# do the actual sync here
}
ensure
@active_sync_lock.synchronize {
@active_sync_runs -= 1
}
end
end
Signal.trap("INT") { wait_on_sync_and_exit }
Signal.trap("TERM") { wait_on_sync_and_exit }
@logger.debug "Done setting things up"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment