This repository has been archived by the owner on Mar 9, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 92
/
database_reconnectable.rb
57 lines (51 loc) · 1.73 KB
/
database_reconnectable.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class PGError < StandardError; end if !defined?(PGError)
class Mysql; class Error < StandardError; end; end if !defined?(Mysql)
module Mysql2; class Error < StandardError; end; end if !defined?(Mysql2)
module ActiveRecord; end
class ActiveRecord::JDBCError < StandardError; end if !defined?(ActiveRecord::JDBCError)
module Rapns
module Daemon
module DatabaseReconnectable
ADAPTER_ERRORS = [ActiveRecord::StatementInvalid, PGError, Mysql::Error,
Mysql2::Error, ActiveRecord::JDBCError]
def with_database_reconnect_and_retry
begin
ActiveRecord::Base.connection_pool.with_connection do
yield
end
rescue *ADAPTER_ERRORS => e
Rapns::Daemon.logger.error(e)
database_connection_lost
retry
end
end
def database_connection_lost
Rapns::Daemon.logger.warn("Lost connection to database, reconnecting...")
attempts = 0
loop do
begin
Rapns::Daemon.logger.warn("Attempt #{attempts += 1}")
reconnect_database
check_database_is_connected
break
rescue *ADAPTER_ERRORS => e
Rapns::Daemon.logger.error(e, :airbrake_notify => false)
sleep_to_avoid_thrashing
end
end
Rapns::Daemon.logger.warn("Database reconnected")
end
def reconnect_database
ActiveRecord::Base.clear_all_connections!
ActiveRecord::Base.establish_connection
end
def check_database_is_connected
# Simply asking the adapter for the connection state is not sufficient.
Rapns::Notification.count
end
def sleep_to_avoid_thrashing
sleep 2
end
end
end
end