resque 0.2.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of resque might be problematic. Click here for more details.

Files changed (61) hide show
  1. data/.kick +26 -0
  2. data/HISTORY.md +3 -0
  3. data/LICENSE +20 -0
  4. data/README.markdown +638 -0
  5. data/Rakefile +61 -0
  6. data/TODO.md +60 -0
  7. data/bin/resque +57 -0
  8. data/bin/resque-web +47 -0
  9. data/config.ru +8 -0
  10. data/deps.rip +5 -0
  11. data/examples/async_helper.rb +31 -0
  12. data/examples/demo/README.markdown +71 -0
  13. data/examples/demo/Rakefile +3 -0
  14. data/examples/demo/app.rb +27 -0
  15. data/examples/demo/config.ru +19 -0
  16. data/examples/demo/job.rb +12 -0
  17. data/examples/existing_classes_as_jobs.rb +3 -0
  18. data/examples/instance.rb +11 -0
  19. data/examples/simple.rb +30 -0
  20. data/init.rb +1 -0
  21. data/lib/resque.rb +184 -0
  22. data/lib/resque/errors.rb +7 -0
  23. data/lib/resque/failure.rb +57 -0
  24. data/lib/resque/failure/base.rb +54 -0
  25. data/lib/resque/failure/hoptoad.rb +88 -0
  26. data/lib/resque/failure/redis.rb +28 -0
  27. data/lib/resque/helpers.rb +57 -0
  28. data/lib/resque/job.rb +91 -0
  29. data/lib/resque/server.rb +154 -0
  30. data/lib/resque/server/public/idle.png +0 -0
  31. data/lib/resque/server/public/jquery-1.3.2.min.js +19 -0
  32. data/lib/resque/server/public/jquery.relatize_date.js +95 -0
  33. data/lib/resque/server/public/nav-bg.png +0 -0
  34. data/lib/resque/server/public/ranger.js +7 -0
  35. data/lib/resque/server/public/reset.css +51 -0
  36. data/lib/resque/server/public/style.css +67 -0
  37. data/lib/resque/server/public/tab_b.gif +0 -0
  38. data/lib/resque/server/public/tab_r.gif +0 -0
  39. data/lib/resque/server/public/tabs.css +189 -0
  40. data/lib/resque/server/public/working.png +0 -0
  41. data/lib/resque/server/views/error.erb +1 -0
  42. data/lib/resque/server/views/failed.erb +29 -0
  43. data/lib/resque/server/views/key.erb +17 -0
  44. data/lib/resque/server/views/layout.erb +43 -0
  45. data/lib/resque/server/views/next_more.erb +12 -0
  46. data/lib/resque/server/views/overview.erb +2 -0
  47. data/lib/resque/server/views/queues.erb +40 -0
  48. data/lib/resque/server/views/stats.erb +62 -0
  49. data/lib/resque/server/views/workers.erb +72 -0
  50. data/lib/resque/server/views/working.erb +66 -0
  51. data/lib/resque/stat.rb +53 -0
  52. data/lib/resque/tasks.rb +24 -0
  53. data/lib/resque/version.rb +3 -0
  54. data/lib/resque/worker.rb +406 -0
  55. data/tasks/redis.rake +125 -0
  56. data/tasks/resque.rake +2 -0
  57. data/test/redis-test.conf +132 -0
  58. data/test/resque_test.rb +160 -0
  59. data/test/test_helper.rb +90 -0
  60. data/test/worker_test.rb +212 -0
  61. metadata +124 -0
@@ -0,0 +1,66 @@
1
+ <% if params[:id] && (worker = Resque::Worker.find(params[:id])) && worker.job %>
2
+ <h1><%= worker %>'s job</h1>
3
+
4
+ <table>
5
+ <tr>
6
+ <th>&nbsp;</th>
7
+ <th>Where</th>
8
+ <th>Queue</th>
9
+ <th>Started</th>
10
+ <th>Class</th>
11
+ <th>Args</th>
12
+ </tr>
13
+ <tr>
14
+ <td><img src="<%=u 'working.png' %>" alt="working" title="working"></td>
15
+ <% host, pid, _ = worker.to_s.split(':') %>
16
+ <td><a href="<%=u "/workers/#{worker}" %>"><%= host %>:<%= pid %></a></td>
17
+ <% data = worker.job %>
18
+ <% queue = data['queue'] %>
19
+ <td><a class="queue" href="<%=u "/queues/#{queue}" %>"><%= queue %></a></td>
20
+ <td><span class="time"><%= data['run_at'] %></span></td>
21
+ <td>
22
+ <code><%= data['payload']['class'] %></code>
23
+ </td>
24
+ <td><%=h data['payload']['args'].inspect %></td>
25
+ </tr>
26
+ </table>
27
+
28
+ <% else %>
29
+
30
+ <% workers = resque.working %>
31
+ <h1><%= workers.size %> of <%= resque.workers.size %> Workers Working</h1>
32
+ <table>
33
+ <tr>
34
+ <th>&nbsp;</th>
35
+ <th>Where</th>
36
+ <th>Queue</th>
37
+ <th>Processing</th>
38
+ </tr>
39
+ <% if workers.empty? %>
40
+ <tr>
41
+ <td colspan="4">Not a one.</td>
42
+ </tr>
43
+ <% end %>
44
+
45
+ <% for worker in workers.sort_by { |w| w.job['run_at'] ? w.job['run_at'] : '' } %>
46
+ <% job = worker.job %>
47
+ <tr>
48
+ <td><img src="<%=u state = worker.state %>.png" alt="<%= state %>" title="<%= state %>"></td>
49
+ <% host, pid, queues = worker.to_s.split(':') %>
50
+ <td><a href="<%=u "/workers/#{worker}" %>"><%= host %>:<%= pid %></a></td>
51
+ <td>
52
+ <a class="queue" href="<%=u "/queues/#{job['queue']}" %>"><%= job['queue'] %></a>
53
+ </td>
54
+ <td>
55
+ <% if job['queue'] %>
56
+ <code><%= job['payload']['class'] %></code>
57
+ <small><a class="queue time" href="<%=u "/working/#{worker}" %>"><%= job['run_at'] %></a></small>
58
+ <% else %>
59
+ Waiting for more
60
+ <% end %>
61
+ </td>
62
+ </tr>
63
+ <% end %>
64
+ </table>
65
+
66
+ <% end %>
@@ -0,0 +1,53 @@
1
+ module Resque
2
+ # The stat subsystem. Used to keep track of integer counts.
3
+ #
4
+ # Get a stat: Stat[name]
5
+ # Incr a stat: Stat.incr(name)
6
+ # Decr a stat: Stat.decr(name)
7
+ # Kill a stat: Stat.clear(name)
8
+ module Stat
9
+ extend self
10
+ extend Helpers
11
+
12
+ # Returns the int value of a stat, given a string stat name.
13
+ def get(stat)
14
+ redis.get("stat:#{stat}").to_i
15
+ end
16
+
17
+ # Alias of `get`
18
+ def [](stat)
19
+ get(stat)
20
+ end
21
+
22
+ # For a string stat name, increments the stat by one.
23
+ #
24
+ # Can optionally accept a second int parameter. The stat is then
25
+ # incremented by that amount.
26
+ def incr(stat, by = 1)
27
+ redis.incr("stat:#{stat}", by)
28
+ end
29
+
30
+ # Increments a stat by one.
31
+ def <<(stat)
32
+ incr stat
33
+ end
34
+
35
+ # For a string stat name, decrements the stat by one.
36
+ #
37
+ # Can optionally accept a second int parameter. The stat is then
38
+ # decremented by that amount.
39
+ def decr(stat, by = 1)
40
+ redis.decr("stat:#{stat}", by)
41
+ end
42
+
43
+ # Decrements a stat by one.
44
+ def >>(stat)
45
+ decr stat
46
+ end
47
+
48
+ # Removes a stat from Redis, effectively setting it to 0.
49
+ def clear(stat)
50
+ redis.del("stat:#{stat}")
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,24 @@
1
+ # require 'resque/tasks'
2
+ # will give you the resque tasks
3
+
4
+ namespace :resque do
5
+ desc "Start a Resque Ranger"
6
+ task :work do
7
+ Rake::Task['resque:setup'].invoke rescue nil
8
+
9
+ worker = nil
10
+ queues = (ENV['QUEUES'] || ENV['QUEUE']).to_s.split(',')
11
+
12
+ begin
13
+ worker = Resque::Worker.new(*queues)
14
+ worker.verbose = ENV['LOGGING'] || ENV['VERBOSE']
15
+ worker.very_verbose = ENV['VVERBOSE']
16
+ rescue Resque::NoQueueError
17
+ abort "set QUEUE env var, e.g. $ QUEUE=critical,high rake resque:work"
18
+ end
19
+
20
+ puts "*** Starting worker #{worker}"
21
+
22
+ worker.work(ENV['INTERVAL'] || 5) # interval, will block
23
+ end
24
+ end
@@ -0,0 +1,3 @@
1
+ module Resque
2
+ Version = '0.2.0'
3
+ end
@@ -0,0 +1,406 @@
1
+ module Resque
2
+ # A Resque Worker processes jobs. On platforms that support fork(2),
3
+ # the worker will fork off a child to process each job. This ensures
4
+ # a clean slate when beginning the next job and cuts down on gradual
5
+ # memory growth as well as low level failures.
6
+ #
7
+ # It also ensures workers are always listening to signals from you,
8
+ # their master, and can react accordingly.
9
+ class Worker
10
+ include Resque::Helpers
11
+ extend Resque::Helpers
12
+
13
+ # Whether the worker should log basic info to STDOUT
14
+ attr_accessor :verbose
15
+
16
+ # Whether the worker should log lots of info to STDOUT
17
+ attr_accessor :very_verbose
18
+
19
+ # Boolean indicating whether this worker can or can not fork.
20
+ # Automatically set if a fork(2) fails.
21
+ attr_accessor :cant_fork
22
+
23
+ attr_writer :to_s
24
+
25
+ # Returns an array of all worker objects.
26
+ def self.all
27
+ redis.smembers(:workers).map { |id| find(id) }
28
+ end
29
+
30
+ # Returns an array of all worker objects currently processing
31
+ # jobs.
32
+ def self.working
33
+ names = all
34
+ return [] unless names.any?
35
+ names.map! { |name| "worker:#{name}" }
36
+ redis.mapped_mget(*names).keys.map do |key|
37
+ find key.sub("worker:", '')
38
+ end
39
+ end
40
+
41
+ # Returns a single worker object. Accepts a string id.
42
+ def self.find(worker_id)
43
+ if exists? worker_id
44
+ queues = worker_id.split(':')[-1].split(',')
45
+ worker = new(*queues)
46
+ worker.to_s = worker_id
47
+ worker
48
+ else
49
+ nil
50
+ end
51
+ end
52
+
53
+ # Alias of `find`
54
+ def self.attach(worker_id)
55
+ find(worker_id)
56
+ end
57
+
58
+ # Given a string worker id, return a boolean indicating whether the
59
+ # worker exists
60
+ def self.exists?(worker_id)
61
+ redis.sismember(:workers, worker_id)
62
+ end
63
+
64
+ # Workers should be initialized with an array of string queue
65
+ # names. The order is important: a Worker will check the first
66
+ # queue given for a job. If none is found, it will check the
67
+ # second queue name given. If a job is found, it will be
68
+ # processed. Upon completion, the Worker will again check the
69
+ # first queue given, and so forth. In this way the queue list
70
+ # passed to a Worker on startup defines the priorities of queues.
71
+ #
72
+ # If passed a single "*", this Worker will operate on all queues
73
+ # in alphabetical order. Queues can be dynamically added or
74
+ # removed without needing to restart workers using this method.
75
+ def initialize(*queues)
76
+ @queues = queues
77
+ validate_queues
78
+ end
79
+
80
+ # A worker must be given a queue, otherwise it won't know what to
81
+ # do with itself.
82
+ #
83
+ # You probably never need to call this.
84
+ def validate_queues
85
+ if @queues.nil? || @queues.empty?
86
+ raise NoQueueError.new("Please give each worker at least one queue.")
87
+ end
88
+ end
89
+
90
+ # This is the main workhorse method. Called on a Worker instance,
91
+ # it begins the worker life cycle.
92
+ #
93
+ # The following events occur during a worker's life cycle:
94
+ #
95
+ # 1. startup: Signals are registered, dead workers are pruned,
96
+ # and this worker is registered.
97
+ # 2. work loop: Jobs are pulled from a queue and processed
98
+ # 3. teardown: This worker is unregistered.
99
+ #
100
+ # Can be passed an integered representing the polling
101
+ # frequency. The default is 5 seconds, but for a semi-active site
102
+ # you may want to use a smaller value.
103
+ #
104
+ # Also accepts a block which will be passed the job as soon as it
105
+ # has completed processing. Useful for testing.
106
+ def work(interval = 5, &block)
107
+ $0 = "resque: Starting"
108
+ startup
109
+
110
+ loop do
111
+ break if @shutdown
112
+
113
+ if job = reserve
114
+ log "got: #{job.inspect}"
115
+
116
+ if @child = fork
117
+ procline = "resque: Forked #{@child} at #{Time.now.to_i}"
118
+ $0 = procline
119
+ log! procline
120
+ Process.wait
121
+ else
122
+ procline = "resque: Processing #{job.queue} since #{Time.now.to_i}"
123
+ $0 = procline
124
+ log! procline
125
+ process(job, &block)
126
+ exit! unless @cant_fork
127
+ end
128
+
129
+ @child = nil
130
+ else
131
+ break if interval.to_i == 0
132
+ log! "Sleeping for #{interval.to_i}"
133
+ $0 = "resque: Waiting for #{@queues.join(',')}"
134
+ sleep interval.to_i
135
+ end
136
+ end
137
+
138
+ ensure
139
+ unregister_worker
140
+ end
141
+
142
+ # Processes a single job. If none is given, it will try to produce
143
+ # one.
144
+ def process(job = nil)
145
+ return unless job ||= reserve
146
+
147
+ begin
148
+ working_on job
149
+ job.perform
150
+ rescue Object => e
151
+ log "#{job.inspect} failed: #{e.inspect}"
152
+ job.fail(e)
153
+ failed!
154
+ else
155
+ log "done: #{job.inspect}"
156
+ ensure
157
+ yield job if block_given?
158
+ done_working
159
+ end
160
+ end
161
+
162
+ # Attempts to grab a job off one of the provided queues. Returns
163
+ # nil if no job can be found.
164
+ def reserve
165
+ queues.each do |queue|
166
+ log! "Checking #{queue}"
167
+ if job = Resque::Job.reserve(queue)
168
+ log! "Found job on #{queue}"
169
+ return job
170
+ end
171
+ end
172
+
173
+ nil
174
+ end
175
+
176
+ # Returns a list of queues to use when searching for a job.
177
+ # A splat ("*") means you want every queue (in alpha order) - this
178
+ # can be useful for dynamically adding new queues.
179
+ def queues
180
+ @queues[0] == "*" ? Resque.queues.sort : @queues
181
+ end
182
+
183
+ # Not every platform supports fork. Here we do our magic to
184
+ # determine if yours does.
185
+ def fork
186
+ @cant_fork = true if $TESTING
187
+
188
+ return if @cant_fork
189
+
190
+ begin
191
+ Kernel.fork
192
+ rescue NotImplementedError
193
+ @cant_fork = true
194
+ nil
195
+ end
196
+ end
197
+
198
+ # Runs all the methods needed when a worker begins its lifecycle.
199
+ def startup
200
+ enable_gc_optimizations
201
+ register_signal_handlers
202
+ prune_dead_workers
203
+ register_worker
204
+ end
205
+
206
+ # Enables GC Optimizations if you're running REE.
207
+ # http://www.rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
208
+ def enable_gc_optimizations
209
+ if GC.respond_to?(:copy_on_write_friendly=)
210
+ GC.copy_on_write_friendly = true
211
+ end
212
+ end
213
+
214
+ # Registers the various signal handlers a worker responds to.
215
+ #
216
+ # TERM: Shutdown immediately, stop processing jobs.
217
+ # INT: Shutdown immediately, stop processing jobs.
218
+ # QUIT: Shutdown after the current job has finished processing.
219
+ # USR1: Kill the forked child immediately, continue processing jobs.
220
+ def register_signal_handlers
221
+ trap('TERM') { shutdown! }
222
+ trap('INT') { shutdown! }
223
+ unless defined? JRUBY_VERSION
224
+ trap('QUIT') { shutdown }
225
+ trap('USR1') { kill_child }
226
+ end
227
+ log! "Registered signals"
228
+ end
229
+
230
+ # Schedule this worker for shutdown. Will finish processing the
231
+ # current job.
232
+ def shutdown
233
+ log 'Exiting...'
234
+ @shutdown = true
235
+ end
236
+
237
+ # Kill the child and shutdown immediately.
238
+ def shutdown!
239
+ shutdown
240
+ kill_child
241
+ end
242
+
243
+ # Kills the forked child immediately, without remorse. The job it
244
+ # is processing will not be completed.
245
+ def kill_child
246
+ if @child
247
+ log! "Killing child at #{@child}"
248
+ Process.kill("KILL", @child) rescue nil
249
+ end
250
+ end
251
+
252
+ # Looks for any workers which should be running on this server
253
+ # and, if they're not, removes them from Redis.
254
+ #
255
+ # This is a form of garbage collection. If a server is killed by a
256
+ # hard shutdown, power failure, or something else beyond our
257
+ # control, the Resque workers will not die gracefully and therefor
258
+ # will leave stale state information in Redis.
259
+ #
260
+ # By checking the current Redis state against the actual
261
+ # environment, we can determine if Redis is old and clean it up a bit.
262
+ def prune_dead_workers
263
+ Worker.all.each do |worker|
264
+ host, pid, queues = worker.id.split(':')
265
+ next unless host == hostname
266
+ next if worker_pids.include?(pid)
267
+ log! "Pruning dead worker: #{worker}"
268
+ worker.unregister_worker
269
+ end
270
+ end
271
+
272
+ # Registers ourself as a worker. Useful when entering the worker
273
+ # lifecycle on startup.
274
+ def register_worker
275
+ redis.sadd(:workers, self)
276
+ started!
277
+ end
278
+
279
+ # Unregisters ourself as a worker. Useful when shutting down.
280
+ def unregister_worker
281
+ done_working
282
+
283
+ redis.srem(:workers, self)
284
+ redis.del("worker:#{self}:started")
285
+
286
+ Stat.clear("processed:#{self}")
287
+ Stat.clear("failed:#{self}")
288
+ end
289
+
290
+ # Given a job, tells Redis we're working on it. Useful for seeing
291
+ # what workers are doing and when.
292
+ def working_on(job)
293
+ job.worker = self
294
+ data = encode \
295
+ :queue => job.queue,
296
+ :run_at => Time.now.to_s,
297
+ :payload => job.payload
298
+ redis.set("worker:#{self}", data)
299
+ end
300
+
301
+ # Called when we are done working - clears our `working_on` state
302
+ # and tells Redis we processed a job.
303
+ def done_working
304
+ processed!
305
+ redis.del("worker:#{self}")
306
+ end
307
+
308
+ # How many jobs has this worker processed? Returns an int.
309
+ def processed
310
+ Stat["processed:#{self}"]
311
+ end
312
+
313
+ # Tell Redis we've processed a job.
314
+ def processed!
315
+ Stat << "processed"
316
+ Stat << "processed:#{self}"
317
+ end
318
+
319
+ # How many failed jobs has this worker seen? Returns an int.
320
+ def failed
321
+ Stat["failed:#{self}"]
322
+ end
323
+
324
+ # Tells Redis we've failed a job.
325
+ def failed!
326
+ Stat << "failed"
327
+ Stat << "failed:#{self}"
328
+ end
329
+
330
+ # What time did this worker start? Returns an instance of `Time`
331
+ def started
332
+ redis.get "worker:#{self}:started"
333
+ end
334
+
335
+ # Tell Redis we've started
336
+ def started!
337
+ redis.set("worker:#{self}:started", Time.now.to_s)
338
+ end
339
+
340
+ # Returns a hash explaining the Job we're currently processing, if any.
341
+ def job
342
+ decode(redis.get("worker:#{self}")) || {}
343
+ end
344
+ alias_method :processing, :job
345
+
346
+ # Boolean - true if working, false if not
347
+ def working?
348
+ state == :working
349
+ end
350
+
351
+ # Boolean - true if idle, false if not
352
+ def idle?
353
+ state == :idle
354
+ end
355
+
356
+ # Returns a symbol representing the current worker state,
357
+ # which can be either :working or :idle
358
+ def state
359
+ redis.exists("worker:#{self}") ? :working : :idle
360
+ end
361
+
362
+ # Is this worker the same as another worker?
363
+ def ==(other)
364
+ to_s == other.to_s
365
+ end
366
+
367
+ def inspect
368
+ "#<Worker #{to_s}>"
369
+ end
370
+
371
+ # The string representation is the same as the id for this worker
372
+ # instance. Can be used with `Worker.find`.
373
+ def to_s
374
+ @to_s ||= "#{hostname}:#{Process.pid}:#{@queues.join(',')}"
375
+ end
376
+ alias_method :id, :to_s
377
+
378
+ # chomp'd hostname of this machine
379
+ def hostname
380
+ @hostname ||= `hostname`.chomp
381
+ end
382
+
383
+ # Returns an array of string pids of all the other workers on this
384
+ # machine. Useful when pruning dead workers on startup.
385
+ def worker_pids
386
+ `ps -e -o pid,command | grep [r]esque`.split("\n").map do |line|
387
+ line.split(' ')[0]
388
+ end
389
+ end
390
+
391
+ # Log a message to STDOUT if we are verbose or very_verbose.
392
+ def log(message)
393
+ if verbose
394
+ puts "*** #{message}"
395
+ elsif very_verbose
396
+ time = Time.now.strftime('%I:%M:%S %Y-%m-%d')
397
+ puts "** [#{time}] #$$: #{message}"
398
+ end
399
+ end
400
+
401
+ # Logs a very verbose message to STDOUT.
402
+ def log!(message)
403
+ log message if very_verbose
404
+ end
405
+ end
406
+ end