delayed_job 1.8.5 → 2.0.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,110 @@
1
+ require 'mongo_mapper'
2
+
3
+ module ::MongoMapper
4
+ module Document
5
+ module ClassMethods
6
+ def load_for_delayed_job(id)
7
+ find!(id)
8
+ end
9
+ end
10
+
11
+ module InstanceMethods
12
+ def dump_for_delayed_job
13
+ "#{self.class};#{id}"
14
+ end
15
+ end
16
+ end
17
+ end
18
+
19
+ module Delayed
20
+ module Backend
21
+ module MongoMapper
22
+ class Job
23
+ include ::MongoMapper::Document
24
+ include Delayed::Backend::Base
25
+ set_collection_name 'delayed_jobs'
26
+
27
+ key :priority, Integer, :default => 0
28
+ key :attempts, Integer, :default => 0
29
+ key :handler, String
30
+ key :run_at, Time
31
+ key :locked_at, Time
32
+ key :locked_by, String, :index => true
33
+ key :failed_at, Time
34
+ key :last_error, String
35
+ timestamps!
36
+
37
+ before_save :set_default_run_at
38
+
39
+ ensure_index [[:priority, 1], [:run_at, 1]]
40
+
41
+ def self.before_fork
42
+ ::MongoMapper.connection.close
43
+ end
44
+
45
+ def self.after_fork
46
+ ::MongoMapper.connection.connect_to_master
47
+ end
48
+
49
+ def self.db_time_now
50
+ ::MongoMapper.time_class.now.utc
51
+ end
52
+
53
+ def self.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time)
54
+ right_now = db_time_now
55
+
56
+ conditions = {
57
+ :run_at => {"$lte" => right_now},
58
+ :limit => -limit, # In mongo, positive limits are 'soft' and negative are 'hard'
59
+ :failed_at => nil,
60
+ :sort => [['priority', 1], ['run_at', 1]]
61
+ }
62
+
63
+ where = "this.locked_at == null || this.locked_at < #{make_date(right_now - max_run_time)}"
64
+
65
+ (conditions[:priority] ||= {})['$gte'] = Worker.min_priority if Worker.min_priority
66
+ (conditions[:priority] ||= {})['$lte'] = Worker.max_priority if Worker.max_priority
67
+
68
+ results = all(conditions.merge(:locked_by => worker_name))
69
+ results += all(conditions.merge('$where' => where)) if results.size < limit
70
+ results
71
+ end
72
+
73
+ # When a worker is exiting, make sure we don't have any locked jobs.
74
+ def self.clear_locks!(worker_name)
75
+ collection.update({:locked_by => worker_name}, {"$set" => {:locked_at => nil, :locked_by => nil}}, :multi => true)
76
+ end
77
+
78
+ # Lock this job for this worker.
79
+ # Returns true if we have the lock, false otherwise.
80
+ def lock_exclusively!(max_run_time, worker = worker_name)
81
+ right_now = self.class.db_time_now
82
+ overtime = right_now - max_run_time.to_i
83
+
84
+ query = "this.locked_at == null || this.locked_at < #{make_date(overtime)} || this.locked_by == #{worker.to_json}"
85
+ conditions = {:_id => id, :run_at => {"$lte" => right_now}, "$where" => query}
86
+
87
+ collection.update(conditions, {"$set" => {:locked_at => right_now, :locked_by => worker}})
88
+ affected_rows = collection.find({:_id => id, :locked_by => worker}).count
89
+ if affected_rows == 1
90
+ self.locked_at = right_now
91
+ self.locked_by = worker
92
+ return true
93
+ else
94
+ return false
95
+ end
96
+ end
97
+
98
+ private
99
+
100
+ def self.make_date(date_or_seconds)
101
+ "new Date(#{date_or_seconds.to_f * 1000})"
102
+ end
103
+
104
+ def make_date(date)
105
+ self.class.make_date(date)
106
+ end
107
+ end
108
+ end
109
+ end
110
+ end
@@ -36,6 +36,8 @@ module Delayed
36
36
  end
37
37
 
38
38
  def daemonize
39
+ Delayed::Worker.backend.before_fork
40
+
39
41
  ObjectSpace.each_object(File) do |file|
40
42
  @files_to_reopen << file unless file.closed?
41
43
  end
@@ -64,11 +66,11 @@ module Delayed
64
66
  if Delayed::Worker.logger.respond_to? :auto_flushing=
65
67
  Delayed::Worker.logger.auto_flushing = true
66
68
  end
67
- ActiveRecord::Base.connection.reconnect!
68
-
69
- Delayed::Job.worker_name = "#{worker_name} #{Delayed::Job.worker_name}"
69
+ Delayed::Worker.backend.after_fork
70
70
 
71
- Delayed::Worker.new(@options).start
71
+ worker = Delayed::Worker.new(@options)
72
+ worker.name_prefix = "#{worker_name} "
73
+ worker.start
72
74
  rescue => e
73
75
  Rails.logger.fatal e
74
76
  STDERR.puts e.message
@@ -1,7 +1,19 @@
1
+ class Class
2
+ def load_for_delayed_job(arg)
3
+ self
4
+ end
5
+
6
+ def dump_for_delayed_job
7
+ name
8
+ end
9
+ end
10
+
1
11
  module Delayed
2
12
  class PerformableMethod < Struct.new(:object, :method, :args)
3
- CLASS_STRING_FORMAT = /^CLASS\:([A-Z][\w\:]+)$/
4
- AR_STRING_FORMAT = /^AR\:([A-Z][\w\:]+)\:(\d+)$/
13
+ STRING_FORMAT = /^LOAD\;([A-Z][\w\:]+)(?:\;(\w+))?$/
14
+
15
+ class LoadError < StandardError
16
+ end
5
17
 
6
18
  def initialize(object, method, args)
7
19
  raise NoMethodError, "undefined method `#{method}' for #{object.inspect}" unless object.respond_to?(method)
@@ -11,45 +23,40 @@ module Delayed
11
23
  self.method = method.to_sym
12
24
  end
13
25
 
14
- def display_name
15
- case self.object
16
- when CLASS_STRING_FORMAT then "#{$1}.#{method}"
17
- when AR_STRING_FORMAT then "#{$1}##{method}"
18
- else "Unknown##{method}"
19
- end
20
- end
21
-
26
+ def display_name
27
+ if STRING_FORMAT === object
28
+ "#{$1}#{$2 ? '#' : '.'}#{method}"
29
+ else
30
+ "#{object.class}##{method}"
31
+ end
32
+ end
33
+
22
34
  def perform
23
35
  load(object).send(method, *args.map{|a| load(a)})
24
- rescue ActiveRecord::RecordNotFound
25
- # We cannot do anything about objects which were deleted in the meantime
36
+ rescue PerformableMethod::LoadError
37
+ # We cannot do anything about objects that can't be loaded
26
38
  true
27
39
  end
28
40
 
29
41
  private
30
42
 
31
- def load(arg)
32
- case arg
33
- when CLASS_STRING_FORMAT then $1.constantize
34
- when AR_STRING_FORMAT then $1.constantize.find($2)
35
- else arg
43
+ def load(obj)
44
+ if STRING_FORMAT === obj
45
+ $1.constantize.load_for_delayed_job($2)
46
+ else
47
+ obj
36
48
  end
49
+ rescue => e
50
+ Delayed::Worker.logger.warn "Could not load object for job: #{e.message}"
51
+ raise PerformableMethod::LoadError
37
52
  end
38
53
 
39
- def dump(arg)
40
- case arg
41
- when Class then class_to_string(arg)
42
- when ActiveRecord::Base then ar_to_string(arg)
43
- else arg
54
+ def dump(obj)
55
+ if obj.respond_to?(:dump_for_delayed_job)
56
+ "LOAD;#{obj.dump_for_delayed_job}"
57
+ else
58
+ obj
44
59
  end
45
60
  end
46
-
47
- def ar_to_string(obj)
48
- "AR:#{obj.class}:#{obj.id}"
49
- end
50
-
51
- def class_to_string(obj)
52
- "CLASS:#{obj.name}"
53
- end
54
61
  end
55
- end
62
+ end
@@ -1,24 +1,61 @@
1
+ require 'timeout'
2
+ require 'active_support/core_ext/numeric/time'
3
+
1
4
  module Delayed
2
5
  class Worker
3
- @@sleep_delay = 5
6
+ cattr_accessor :min_priority, :max_priority, :max_attempts, :max_run_time, :sleep_delay, :logger
7
+ self.sleep_delay = 5
8
+ self.max_attempts = 25
9
+ self.max_run_time = 4.hours
10
+
11
+ # By default failed jobs are destroyed after too many attempts. If you want to keep them around
12
+ # (perhaps to inspect the reason for the failure), set this to false.
13
+ cattr_accessor :destroy_failed_jobs
14
+ self.destroy_failed_jobs = true
4
15
 
5
- cattr_accessor :sleep_delay
6
-
7
- cattr_accessor :logger
8
16
  self.logger = if defined?(Merb::Logger)
9
17
  Merb.logger
10
18
  elsif defined?(RAILS_DEFAULT_LOGGER)
11
19
  RAILS_DEFAULT_LOGGER
12
20
  end
13
21
 
22
+ # name_prefix is ignored if name is set directly
23
+ attr_accessor :name_prefix
24
+
25
+ cattr_reader :backend
26
+
27
+ def self.backend=(backend)
28
+ if backend.is_a? Symbol
29
+ require "delayed/backend/#{backend}"
30
+ backend = "Delayed::Backend::#{backend.to_s.classify}::Job".constantize
31
+ end
32
+ @@backend = backend
33
+ silence_warnings { ::Delayed.const_set(:Job, backend) }
34
+ end
35
+
14
36
  def initialize(options={})
15
37
  @quiet = options[:quiet]
16
- Delayed::Job.min_priority = options[:min_priority] if options.has_key?(:min_priority)
17
- Delayed::Job.max_priority = options[:max_priority] if options.has_key?(:max_priority)
38
+ self.class.min_priority = options[:min_priority] if options.has_key?(:min_priority)
39
+ self.class.max_priority = options[:max_priority] if options.has_key?(:max_priority)
40
+ end
41
+
42
+ # Every worker has a unique name which by default is the pid of the process. There are some
43
+ # advantages to overriding this with something which survives worker retarts: Workers can#
44
+ # safely resume working on tasks which are locked by themselves. The worker will assume that
45
+ # it crashed before.
46
+ def name
47
+ return @name unless @name.nil?
48
+ "#{@name_prefix}host:#{Socket.gethostname} pid:#{Process.pid}" rescue "#{@name_prefix}pid:#{Process.pid}"
49
+ end
50
+
51
+ # Sets the name of the worker.
52
+ # Setting the name to nil will reset the default worker name
53
+ def name=(val)
54
+ @name = val
18
55
  end
19
56
 
20
57
  def start
21
- say "*** Starting job worker #{Delayed::Job.worker_name}"
58
+ say "*** Starting job worker #{name}"
22
59
 
23
60
  trap('TERM') { say 'Exiting...'; $exit = true }
24
61
  trap('INT') { say 'Exiting...'; $exit = true }
@@ -27,7 +64,7 @@ module Delayed
27
64
  result = nil
28
65
 
29
66
  realtime = Benchmark.realtime do
30
- result = Delayed::Job.work_off
67
+ result = work_off
31
68
  end
32
69
 
33
70
  count = result.sum
@@ -44,13 +81,86 @@ module Delayed
44
81
  end
45
82
 
46
83
  ensure
47
- Delayed::Job.clear_locks!
84
+ Delayed::Job.clear_locks!(name)
85
+ end
86
+
87
+ # Do num jobs and return stats on success/failure.
88
+ # Exit early if interrupted.
89
+ def work_off(num = 100)
90
+ success, failure = 0, 0
91
+
92
+ num.times do
93
+ case reserve_and_run_one_job
94
+ when true
95
+ success += 1
96
+ when false
97
+ failure += 1
98
+ else
99
+ break # leave if no work could be done
100
+ end
101
+ break if $exit # leave if we're exiting
102
+ end
103
+
104
+ return [success, failure]
105
+ end
106
+
107
+ def run(job)
108
+ runtime = Benchmark.realtime do
109
+ Timeout.timeout(self.class.max_run_time.to_i) { job.invoke_job }
110
+ job.destroy
111
+ end
112
+ # TODO: warn if runtime > max_run_time ?
113
+ say "* [JOB] #{name} completed after %.4f" % runtime
114
+ return true # did work
115
+ rescue Exception => e
116
+ handle_failed_job(job, e)
117
+ return false # work failed
118
+ end
119
+
120
+ # Reschedule the job in the future (when a job fails).
121
+ # Uses an exponential scale depending on the number of failed attempts.
122
+ def reschedule(job, time = nil)
123
+ if (job.attempts += 1) < self.class.max_attempts
124
+ time ||= Job.db_time_now + (job.attempts ** 4) + 5
125
+ job.run_at = time
126
+ job.unlock
127
+ job.save!
128
+ else
129
+ say "* [JOB] PERMANENTLY removing #{job.name} because of #{job.attempts} consecutive failures.", Logger::INFO
130
+ self.class.destroy_failed_jobs ? job.destroy : job.update_attributes(:failed_at => Delayed::Job.db_time_now)
131
+ end
48
132
  end
49
133
 
50
- def say(text)
134
+ def say(text, level = Logger::INFO)
51
135
  puts text unless @quiet
52
- logger.info text if logger
136
+ logger.add level, "#{Time.now.strftime('%FT%T%z')}: #{text}" if logger
53
137
  end
54
138
 
139
+ protected
140
+
141
+ def handle_failed_job(job, error)
142
+ job.last_error = error.message + "\n" + error.backtrace.join("\n")
143
+ say "* [JOB] #{name} failed with #{error.class.name}: #{error.message} - #{job.attempts} failed attempts", Logger::ERROR
144
+ reschedule(job)
145
+ end
146
+
147
+ # Run the next job we can get an exclusive lock on.
148
+ # If no jobs are left we return nil
149
+ def reserve_and_run_one_job
150
+
151
+ # We get up to 5 jobs from the db. In case we cannot get exclusive access to a job we try the next.
152
+ # this leads to a more even distribution of jobs across the worker processes
153
+ job = Delayed::Job.find_available(name, 5, self.class.max_run_time).detect do |job|
154
+ if job.lock_exclusively!(self.class.max_run_time, name)
155
+ say "* [Worker(#{name})] acquired lock on #{job.name}"
156
+ true
157
+ else
158
+ say "* [Worker(#{name})] failed to acquire exclusive lock for #{job.name}", Logger::WARN
159
+ false
160
+ end
161
+ end
162
+
163
+ run(job) if job
164
+ end
55
165
  end
56
166
  end
data/lib/delayed_job.rb CHANGED
@@ -1,8 +1,8 @@
1
- autoload :ActiveRecord, 'activerecord'
1
+ require 'active_support'
2
2
 
3
3
  require File.dirname(__FILE__) + '/delayed/message_sending'
4
4
  require File.dirname(__FILE__) + '/delayed/performable_method'
5
- require File.dirname(__FILE__) + '/delayed/job'
5
+ require File.dirname(__FILE__) + '/delayed/backend/base'
6
6
  require File.dirname(__FILE__) + '/delayed/worker'
7
7
 
8
8
  Object.send(:include, Delayed::MessageSending)
data/rails/init.rb ADDED
@@ -0,0 +1,12 @@
1
+ require 'delayed_job'
2
+
3
+ config.after_initialize do
4
+ Delayed::Worker.backend ||= if defined?(ActiveRecord)
5
+ :active_record
6
+ elsif defined?(MongoMapper)
7
+ :mongo_mapper
8
+ else
9
+ Delayed::Worker.logger.warn "Could not decide on a backend, defaulting to active_record"
10
+ :active_record
11
+ end
12
+ end
@@ -0,0 +1,39 @@
1
+ require 'spec_helper'
2
+ require 'backend/shared_backend_spec'
3
+ require 'delayed/backend/active_record'
4
+
5
+ describe Delayed::Backend::ActiveRecord::Job do
6
+ before(:all) do
7
+ @backend = Delayed::Backend::ActiveRecord::Job
8
+ end
9
+
10
+ before(:each) do
11
+ Delayed::Backend::ActiveRecord::Job.delete_all
12
+ SimpleJob.runs = 0
13
+ end
14
+
15
+ after do
16
+ Time.zone = nil
17
+ end
18
+
19
+ it_should_behave_like 'a backend'
20
+
21
+ context "db_time_now" do
22
+ it "should return time in current time zone if set" do
23
+ Time.zone = 'Eastern Time (US & Canada)'
24
+ %w(EST EDT).should include(Delayed::Job.db_time_now.zone)
25
+ end
26
+
27
+ it "should return UTC time if that is the AR default" do
28
+ Time.zone = nil
29
+ ActiveRecord::Base.default_timezone = :utc
30
+ Delayed::Backend::ActiveRecord::Job.db_time_now.zone.should == 'UTC'
31
+ end
32
+
33
+ it "should return local time if that is the AR default" do
34
+ Time.zone = 'Central Time (US & Canada)'
35
+ ActiveRecord::Base.default_timezone = :local
36
+ %w(CST CDT).should include(Delayed::Backend::ActiveRecord::Job.db_time_now.zone)
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,16 @@
1
+ require 'spec_helper'
2
+ require 'backend/shared_backend_spec'
3
+ require 'delayed/backend/data_mapper'
4
+
5
+ describe Delayed::Backend::DataMapper::Job do
6
+ before(:all) do
7
+ @backend = Delayed::Backend::DataMapper::Job
8
+ end
9
+
10
+ before(:each) do
11
+ # reset database before each example is run
12
+ DataMapper.auto_migrate!
13
+ end
14
+
15
+ it_should_behave_like 'a backend'
16
+ end
@@ -0,0 +1,69 @@
1
+ require 'spec_helper'
2
+ require 'backend/shared_backend_spec'
3
+ require 'delayed/backend/mongo_mapper'
4
+
5
+ describe Delayed::Backend::MongoMapper::Job do
6
+ before(:all) do
7
+ @backend = Delayed::Backend::MongoMapper::Job
8
+ end
9
+
10
+ before(:each) do
11
+ MongoMapper.database.collections.each(&:remove)
12
+ end
13
+
14
+ it_should_behave_like 'a backend'
15
+
16
+ describe "indexes" do
17
+ it "should have combo index on priority and run_at" do
18
+ @backend.collection.index_information.detect { |index| index[0] == 'priority_1_run_at_1' }.should_not be_nil
19
+ end
20
+
21
+ it "should have index on locked_by" do
22
+ @backend.collection.index_information.detect { |index| index[0] == 'locked_by_1' }.should_not be_nil
23
+ end
24
+ end
25
+
26
+ describe "delayed method" do
27
+ class MongoStoryReader
28
+ def read(story)
29
+ "Epilog: #{story.tell}"
30
+ end
31
+ end
32
+
33
+ class MongoStory
34
+ include ::MongoMapper::Document
35
+ key :text, String
36
+
37
+ def tell
38
+ text
39
+ end
40
+ end
41
+
42
+ it "should ignore not found errors because they are permanent" do
43
+ story = MongoStory.create :text => 'Once upon a time...'
44
+ job = story.send_later(:tell)
45
+ story.destroy
46
+ lambda { job.invoke_job }.should_not raise_error
47
+ end
48
+
49
+ it "should store the object as string" do
50
+ story = MongoStory.create :text => 'Once upon a time...'
51
+ job = story.send_later(:tell)
52
+
53
+ job.payload_object.class.should == Delayed::PerformableMethod
54
+ job.payload_object.object.should == "LOAD;MongoStory;#{story.id}"
55
+ job.payload_object.method.should == :tell
56
+ job.payload_object.args.should == []
57
+ job.payload_object.perform.should == 'Once upon a time...'
58
+ end
59
+
60
+ it "should store arguments as string" do
61
+ story = MongoStory.create :text => 'Once upon a time...'
62
+ job = MongoStoryReader.new.send_later(:read, story)
63
+ job.payload_object.class.should == Delayed::PerformableMethod
64
+ job.payload_object.method.should == :read
65
+ job.payload_object.args.should == ["LOAD;MongoStory;#{story.id}"]
66
+ job.payload_object.perform.should == 'Epilog: Once upon a time...'
67
+ end
68
+ end
69
+ end