Created
January 20, 2012 00:35
-
-
Save rurounijones/1644058 to your computer and use it in GitHub Desktop.
Mongoid monkey-patching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Monkey-patch the mongo ruby driver to expose socket information so that we can | |
# interrogate it for port information | |
module Mongo | |
class Pool | |
def sockets | |
@sockets | |
end | |
end | |
end | |
# Add a method which will detect OperationTimeout exceptions and reconnect | |
# plus output useful logging information | |
module Mongoid | |
module Collections | |
module Retry | |
def retry_on_connection_timeout | |
retries = 0 | |
begin | |
yield | |
rescue Mongo::OperationTimeout => ex | |
retries += 1 | |
raise ex if retries > Mongoid.max_retries_on_connection_failure | |
Rails.logger.info("MONGODB #{Mongoid.database.name} OperationTimeout exception encountered on connection #{Mongoid.database.connection.primary_pool.sockets.first.addr[1]}") if defined?(Rails) | |
Mongoid.reconnect! | |
Rails.logger.info("MONGODB #{Mongoid.database.name} Reconnected with #{Mongoid.database.connection.primary_pool.sockets.first.addr[1]}") if defined?(Rails) | |
retry | |
end | |
end | |
end | |
end | |
end | |
module Mongoid | |
module Collections | |
# This class wraps the MongoDB master database. | |
class Master | |
include Mongoid::Collections::Retry | |
attr_reader :collection | |
# Monkey patch the original method to include the connection timeout situation | |
Operations::ALL.each do |name| | |
define_method(name) do |*args| | |
retry_on_connection_failure do | |
# This is the new line that was added | |
retry_on_connection_timeout do | |
collection.send(name, *args) | |
end | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment