deadlock_retry_insane 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ *.swp
@@ -0,0 +1,26 @@
1
+ deadlock_retry changes
2
+
3
+ == v1.2.0
4
+
5
+ * Support for postgres (tomhughes)
6
+ * Testing AR versions (kbrock)
7
+
8
+ == v1.1.2
9
+
10
+ * Exponential backoff, sleep 0, 1, 2, 4... seconds between retries.
11
+ * Support new syntax for InnoDB status in MySQL 5.5.
12
+
13
+ == v1.1.1 (2011-05-13)
14
+
15
+ * Conditionally log INNODB STATUS only if user has permission. (osheroff)
16
+
17
+ == v1.1.0 (2011-04-20)
18
+
19
+ * Modernize.
20
+ * Drop support for Rails 2.1 and earlier.
21
+
22
+ == v1.0 - (2009-02-07)
23
+
24
+ * Add INNODB status logging for debugging deadlock issues.
25
+ * Clean up so the code will run as a gem plugin.
26
+ * Small fix for ActiveRecord 2.1.x compatibility.
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source "http://rubygems.org"
2
+
3
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ # Copyright (c) 2005 Jamis Buck
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README ADDED
@@ -0,0 +1,21 @@
1
+ = Deadlock Retry INSANE EDITION (more retries)
2
+
3
+ Deadlock retry allows the database adapter (currently only tested with the
4
+ MySQLAdapter) to retry transactions that fall into deadlock. It will retry
5
+ such transactions three times before finally failing.
6
+
7
+ This capability is automatically added to ActiveRecord. No code changes or otherwise are required.
8
+
9
+ == Installation
10
+
11
+ Add it to your Rails application by installing the gem:
12
+
13
+ gem install deadlock_retry_insane
14
+
15
+ and including a reference to it in your application's Gemfile:
16
+
17
+ gem 'deadlock_retry_insane'
18
+
19
+ == Original Authors
20
+
21
+ Jamis Buck and Mike Perham made it. I just changed a number.
@@ -0,0 +1,12 @@
1
+ require 'rake'
2
+ require 'rake/testtask'
3
+
4
+ desc "Default task"
5
+ task :default => [ :test ]
6
+
7
+ Rake::TestTask.new do |t|
8
+ t.libs = ['lib', 'test']
9
+ t.test_files = Dir["test/**/*_test.rb"]
10
+ t.verbose = true
11
+ t.warning = true
12
+ end
@@ -0,0 +1,19 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ $:.push File.expand_path("../lib", __FILE__)
4
+
5
+ require "deadlock_retry/version"
6
+
7
+ Gem::Specification.new do |s|
8
+ s.name = %q{deadlock_retry_insane}
9
+ s.version = DeadlockRetry::VERSION
10
+ s.authors = ["Jamis Buck", "Mike Perham", "Jason Coene"]
11
+ s.description = s.summary = %q{Provides automatic deadlock retry and logging functionality for ActiveRecord and MySQL}
12
+ s.email = %q{jcoene@gmail.com}
13
+ s.files = `git ls-files`.split("\n")
14
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
15
+ s.homepage = %q{http://github.com/jcoene/deadlock_retry}
16
+ s.require_paths = ["lib"]
17
+ s.add_development_dependency 'mocha'
18
+ s.add_development_dependency 'activerecord', ENV['ACTIVERECORD_VERSION'] || ' ~>3.0'
19
+ end
@@ -0,0 +1,107 @@
1
+ require 'active_support/core_ext/module/attribute_accessors'
2
+
3
+ module DeadlockRetry
4
+ def self.included(base)
5
+ base.extend(ClassMethods)
6
+ base.class_eval do
7
+ class << self
8
+ alias_method_chain :transaction, :deadlock_handling
9
+ end
10
+ end
11
+ end
12
+
13
+ mattr_accessor :innodb_status_cmd
14
+
15
+ module ClassMethods
16
+ DEADLOCK_ERROR_MESSAGES = [
17
+ "Deadlock found when trying to get lock",
18
+ "Lock wait timeout exceeded",
19
+ "deadlock detected"
20
+ ]
21
+
22
+ MAXIMUM_RETRIES_ON_DEADLOCK = 10
23
+
24
+
25
+ def transaction_with_deadlock_handling(*objects, &block)
26
+ retry_count = 0
27
+
28
+ check_innodb_status_available
29
+
30
+ begin
31
+ transaction_without_deadlock_handling(*objects, &block)
32
+ rescue ActiveRecord::StatementInvalid => error
33
+ raise if in_nested_transaction?
34
+ if DEADLOCK_ERROR_MESSAGES.any? { |msg| error.message =~ /#{Regexp.escape(msg)}/ }
35
+ raise if retry_count >= MAXIMUM_RETRIES_ON_DEADLOCK
36
+ retry_count += 1
37
+ logger.info "Deadlock detected on retry #{retry_count}, restarting transaction"
38
+ log_innodb_status if DeadlockRetry.innodb_status_cmd
39
+ exponential_pause(retry_count)
40
+ retry
41
+ else
42
+ raise
43
+ end
44
+ end
45
+ end
46
+
47
+ private
48
+
49
+ WAIT_TIMES = [0, 1, 2, 4, 8, 16, 32]
50
+
51
+ def exponential_pause(count)
52
+ sec = WAIT_TIMES[count-1] || 32
53
+ # sleep 0, 1, 2, 4, ... seconds up to the MAXIMUM_RETRIES.
54
+ # Cap the pause time at 32 seconds.
55
+ sleep(sec) if sec != 0
56
+ end
57
+
58
+ def in_nested_transaction?
59
+ # open_transactions was added in 2.2's connection pooling changes.
60
+ connection.open_transactions != 0
61
+ end
62
+
63
+ def show_innodb_status
64
+ self.connection.select_value(DeadlockRetry.innodb_status_cmd)
65
+ end
66
+
67
+ # Should we try to log innodb status -- if we don't have permission to,
68
+ # we actually break in-flight transactions, silently (!)
69
+ def check_innodb_status_available
70
+ return unless DeadlockRetry.innodb_status_cmd == nil
71
+
72
+ if self.connection.adapter_name == "MySQL"
73
+ begin
74
+ mysql_version = self.connection.select_rows('show variables like \'version\'')[0][1]
75
+ cmd = if mysql_version < '5.5'
76
+ 'show innodb status'
77
+ else
78
+ 'show engine innodb status'
79
+ end
80
+ self.connection.select_value(cmd)
81
+ DeadlockRetry.innodb_status_cmd = cmd
82
+ rescue
83
+ logger.info "Cannot log innodb status: #{$!.message}"
84
+ DeadlockRetry.innodb_status_cmd = false
85
+ end
86
+ else
87
+ DeadlockRetry.innodb_status_cmd = false
88
+ end
89
+ end
90
+
91
+ def log_innodb_status
92
+ # show innodb status is the only way to get visiblity into why
93
+ # the transaction deadlocked. log it.
94
+ lines = show_innodb_status
95
+ logger.warn "INNODB Status follows:"
96
+ lines.each_line do |line|
97
+ logger.warn line
98
+ end
99
+ rescue => e
100
+ # Access denied, ignore
101
+ logger.info "Cannot log innodb status: #{e.message}"
102
+ end
103
+
104
+ end
105
+ end
106
+
107
+ ActiveRecord::Base.send(:include, DeadlockRetry) if defined?(ActiveRecord)
@@ -0,0 +1,3 @@
1
+ module DeadlockRetry
2
+ VERSION = '1.2.0'
3
+ end
@@ -0,0 +1,118 @@
1
+ require 'rubygems'
2
+
3
+ # Change the version if you want to test a different version of ActiveRecord
4
+ gem 'activerecord', ENV['ACTIVERECORD_VERSION'] || ' ~>3.0'
5
+ require 'active_record'
6
+ require 'active_record/version'
7
+ puts "Testing ActiveRecord #{ActiveRecord::VERSION::STRING}"
8
+
9
+ require 'test/unit'
10
+ require 'mocha'
11
+ require 'logger'
12
+ require "deadlock_retry"
13
+
14
+ class MockModel
15
+ @@open_transactions = 0
16
+
17
+ def self.transaction(*objects)
18
+ @@open_transactions += 1
19
+ yield
20
+ ensure
21
+ @@open_transactions -= 1
22
+ end
23
+
24
+ def self.open_transactions
25
+ @@open_transactions
26
+ end
27
+
28
+ def self.connection
29
+ self
30
+ end
31
+
32
+ def self.logger
33
+ @logger ||= Logger.new(nil)
34
+ end
35
+
36
+ def self.show_innodb_status
37
+ []
38
+ end
39
+
40
+ def self.select_rows(sql)
41
+ [['version', '5.1.45']]
42
+ end
43
+
44
+ def self.select_value(sql)
45
+ true
46
+ end
47
+
48
+ def self.adapter_name
49
+ "MySQL"
50
+ end
51
+
52
+ include DeadlockRetry
53
+ end
54
+
55
+ class DeadlockRetryTest < Test::Unit::TestCase
56
+ DEADLOCK_ERROR = "MySQL::Error: Deadlock found when trying to get lock"
57
+ TIMEOUT_ERROR = "MySQL::Error: Lock wait timeout exceeded"
58
+
59
+ def setup
60
+ MockModel.stubs(:exponential_pause)
61
+ end
62
+
63
+ def test_no_errors
64
+ assert_equal :success, MockModel.transaction { :success }
65
+ end
66
+
67
+ def test_no_errors_with_deadlock
68
+ errors = [ DEADLOCK_ERROR ] * 3
69
+ assert_equal :success, MockModel.transaction { raise ActiveRecord::StatementInvalid, errors.shift unless errors.empty?; :success }
70
+ assert errors.empty?
71
+ end
72
+
73
+ def test_no_errors_with_lock_timeout
74
+ errors = [ TIMEOUT_ERROR ] * 3
75
+ assert_equal :success, MockModel.transaction { raise ActiveRecord::StatementInvalid, errors.shift unless errors.empty?; :success }
76
+ assert errors.empty?
77
+ end
78
+
79
+ def test_error_if_limit_exceeded
80
+ assert_raise(ActiveRecord::StatementInvalid) do
81
+ MockModel.transaction { raise ActiveRecord::StatementInvalid, DEADLOCK_ERROR }
82
+ end
83
+ end
84
+
85
+ def test_error_if_unrecognized_error
86
+ assert_raise(ActiveRecord::StatementInvalid) do
87
+ MockModel.transaction { raise ActiveRecord::StatementInvalid, "Something else" }
88
+ end
89
+ end
90
+
91
+ def test_included_by_default
92
+ assert ActiveRecord::Base.respond_to?(:transaction_with_deadlock_handling)
93
+ end
94
+
95
+ def test_innodb_status_availability
96
+ DeadlockRetry.innodb_status_cmd = nil
97
+ MockModel.transaction {}
98
+ assert_equal "show innodb status", DeadlockRetry.innodb_status_cmd
99
+ end
100
+
101
+
102
+ def test_error_in_nested_transaction_should_retry_outermost_transaction
103
+ tries = 0
104
+ errors = 0
105
+
106
+ MockModel.transaction do
107
+ tries += 1
108
+ MockModel.transaction do
109
+ MockModel.transaction do
110
+ errors += 1
111
+ raise ActiveRecord::StatementInvalid, "MySQL::Error: Lock wait timeout exceeded" unless errors > 3
112
+ end
113
+ end
114
+ end
115
+
116
+ assert_equal 4, tries
117
+ end
118
+ end
metadata ADDED
@@ -0,0 +1,81 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: deadlock_retry_insane
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.2.0
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Jamis Buck
9
+ - Mike Perham
10
+ - Jason Coene
11
+ autorequire:
12
+ bindir: bin
13
+ cert_chain: []
14
+ date: 2012-04-21 00:00:00.000000000 Z
15
+ dependencies:
16
+ - !ruby/object:Gem::Dependency
17
+ name: mocha
18
+ requirement: &70332997754400 !ruby/object:Gem::Requirement
19
+ none: false
20
+ requirements:
21
+ - - ! '>='
22
+ - !ruby/object:Gem::Version
23
+ version: '0'
24
+ type: :development
25
+ prerelease: false
26
+ version_requirements: *70332997754400
27
+ - !ruby/object:Gem::Dependency
28
+ name: activerecord
29
+ requirement: &70332997753680 !ruby/object:Gem::Requirement
30
+ none: false
31
+ requirements:
32
+ - - ~>
33
+ - !ruby/object:Gem::Version
34
+ version: '3.0'
35
+ type: :development
36
+ prerelease: false
37
+ version_requirements: *70332997753680
38
+ description: Provides automatic deadlock retry and logging functionality for ActiveRecord
39
+ and MySQL
40
+ email: jcoene@gmail.com
41
+ executables: []
42
+ extensions: []
43
+ extra_rdoc_files: []
44
+ files:
45
+ - .gitignore
46
+ - CHANGELOG
47
+ - Gemfile
48
+ - LICENSE
49
+ - README
50
+ - Rakefile
51
+ - deadlock_retry_insane.gemspec
52
+ - lib/deadlock_retry.rb
53
+ - lib/deadlock_retry/version.rb
54
+ - test/deadlock_retry_test.rb
55
+ homepage: http://github.com/jcoene/deadlock_retry
56
+ licenses: []
57
+ post_install_message:
58
+ rdoc_options: []
59
+ require_paths:
60
+ - lib
61
+ required_ruby_version: !ruby/object:Gem::Requirement
62
+ none: false
63
+ requirements:
64
+ - - ! '>='
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ none: false
69
+ requirements:
70
+ - - ! '>='
71
+ - !ruby/object:Gem::Version
72
+ version: '0'
73
+ requirements: []
74
+ rubyforge_project:
75
+ rubygems_version: 1.8.11
76
+ signing_key:
77
+ specification_version: 3
78
+ summary: Provides automatic deadlock retry and logging functionality for ActiveRecord
79
+ and MySQL
80
+ test_files:
81
+ - test/deadlock_retry_test.rb