Class: Resque::Worker

Inherits:
Object
  • Object
show all
Extended by:
Helpers
Includes:
Helpers
Defined in:
lib/resque/worker.rb

Overview

A Resque Worker processes jobs. On platforms that support fork(2), the worker will fork off a child to process each job. This ensures a clean slate when beginning the next job and cuts down on gradual memory growth as well as low level failures.

It also ensures workers are always listening to signals from you, their master, and can react accordingly.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Helpers

classify, constantize, decode, encode, redis

Constructor Details

#initialize(*queues) ⇒ Worker

Workers should be initialized with an array of string queue names. The order is important: a Worker will check the first queue given for a job. If none is found, it will check the second queue name given. If a job is found, it will be processed. Upon completion, the Worker will again check the first queue given, and so forth. In this way the queue list passed to a Worker on startup defines the priorities of queues.

If passed a single “*”, this Worker will operate on all queues in alphabetical order. Queues can be dynamically added or removed without needing to restart workers using this method.



95
96
97
98
99
100
# File 'lib/resque/worker.rb', line 95

def initialize(*queues)
  @queues = queues.map { |queue| queue.to_s.strip }
  @shutdown = nil
  @paused = nil
  validate_queues
end

Instance Attribute Details

#cant_forkObject

Boolean indicating whether this worker can or can not fork. Automatically set if a fork(2) fails.



21
22
23
# File 'lib/resque/worker.rb', line 21

def cant_fork
  @cant_fork
end

#term_childObject

decide whether to use new_kill_child logic



26
27
28
# File 'lib/resque/worker.rb', line 26

def term_child
  @term_child
end

#term_timeoutObject

Returns the value of attribute term_timeout.



23
24
25
# File 'lib/resque/worker.rb', line 23

def term_timeout
  @term_timeout
end

#to_sObject Also known as: id

The string representation is the same as the id for this worker instance. Can be used with ‘Worker.find`.



528
529
530
# File 'lib/resque/worker.rb', line 528

def to_s
  @to_s ||= "#{hostname}:#{Process.pid}:#{@queues.join(',')}"
end

#verboseObject

Whether the worker should log basic info to STDOUT



14
15
16
# File 'lib/resque/worker.rb', line 14

def verbose
  @verbose
end

#very_verboseObject

Whether the worker should log lots of info to STDOUT



17
18
19
# File 'lib/resque/worker.rb', line 17

def very_verbose
  @very_verbose
end

Class Method Details

.allObject

Returns an array of all worker objects.



31
32
33
# File 'lib/resque/worker.rb', line 31

def self.all
  Array(redis.smembers(:workers)).map { |id| find(id) }.compact
end

.attach(worker_id) ⇒ Object

Alias of ‘find`



74
75
76
# File 'lib/resque/worker.rb', line 74

def self.attach(worker_id)
  find(worker_id)
end

.exists?(worker_id) ⇒ Boolean

Given a string worker id, return a boolean indicating whether the worker exists

Returns:

  • (Boolean)


80
81
82
# File 'lib/resque/worker.rb', line 80

def self.exists?(worker_id)
  redis.sismember(:workers, worker_id)
end

.find(worker_id) ⇒ Object

Returns a single worker object. Accepts a string id.



62
63
64
65
66
67
68
69
70
71
# File 'lib/resque/worker.rb', line 62

def self.find(worker_id)
  if exists? worker_id
    queues = worker_id.split(':')[-1].split(',')
    worker = new(*queues)
    worker.to_s = worker_id
    worker
  else
    nil
  end
end

.workingObject

Returns an array of all worker objects currently processing jobs.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/resque/worker.rb', line 37

def self.working
  names = all
  return [] unless names.any?

  names.map! { |name| "worker:#{name}" }

  reportedly_working = {}

  begin
    reportedly_working = redis.mapped_mget(*names).reject do |key, value|
      value.nil? || value.empty?
    end
  rescue Redis::Distributed::CannotDistribute
    names.each do |name|
      value = redis.get name
      reportedly_working[name] = value unless value.nil? || value.empty?
    end
  end

  reportedly_working.keys.map do |key|
    find key.sub("worker:", '')
  end.compact
end

Instance Method Details

#==(other) ⇒ Object

Is this worker the same as another worker?



518
519
520
# File 'lib/resque/worker.rb', line 518

def ==(other)
  to_s == other.to_s
end

#done_workingObject

Called when we are done working - clears our ‘working_on` state and tells Redis we processed a job.



458
459
460
461
# File 'lib/resque/worker.rb', line 458

def done_working
  processed!
  redis.del("worker:#{self}")
end

#enable_gc_optimizationsObject

Enables GC Optimizations if you’re running REE. www.rubyenterpriseedition.com/faq.html#adapt_apps_for_cow



265
266
267
268
269
# File 'lib/resque/worker.rb', line 265

def enable_gc_optimizations
  if GC.respond_to?(:copy_on_write_friendly=)
    GC.copy_on_write_friendly = true
  end
end

#failedObject

How many failed jobs has this worker seen? Returns an int.



475
476
477
# File 'lib/resque/worker.rb', line 475

def failed
  Stat["failed:#{self}"]
end

#failed!Object

Tells Redis we’ve failed a job.



480
481
482
483
# File 'lib/resque/worker.rb', line 480

def failed!
  Stat << "failed"
  Stat << "failed:#{self}"
end

#forkObject

Not every platform supports fork. Here we do our magic to determine if yours does.



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/resque/worker.rb', line 231

def fork
  @cant_fork = true if $TESTING

  return if @cant_fork

  begin
    # IronRuby doesn't support `Kernel.fork` yet
    if Kernel.respond_to?(:fork)
      Kernel.fork
    else
      raise NotImplementedError
    end
  rescue NotImplementedError
    @cant_fork = true
    nil
  end
end

#hostnameObject

chomp’d hostname of this machine



534
535
536
# File 'lib/resque/worker.rb', line 534

def hostname
  @hostname ||= `hostname`.chomp
end

#idle?Boolean

Boolean - true if idle, false if not

Returns:

  • (Boolean)


507
508
509
# File 'lib/resque/worker.rb', line 507

def idle?
  state == :idle
end

#inspectObject



522
523
524
# File 'lib/resque/worker.rb', line 522

def inspect
  "#<Worker #{to_s}>"
end

#jobObject Also known as: processing

Returns a hash explaining the Job we’re currently processing, if any.



496
497
498
# File 'lib/resque/worker.rb', line 496

def job
  decode(redis.get("worker:#{self}")) || {}
end

#kill_childObject

Kills the forked child immediately, without remorse. The job it is processing will not be completed.



335
336
337
338
339
340
341
342
343
344
345
# File 'lib/resque/worker.rb', line 335

def kill_child
  if @child
    log! "Killing child at #{@child}"
    if system("ps -o pid,state -p #{@child}")
      Process.kill("KILL", @child) rescue nil
    else
      log! "Child #{@child} not found, restarting."
      shutdown
    end
  end
end

#linux_worker_pidsObject

Find Resque worker pids on Linux and OS X.

Returns an Array of string pids of all the other workers on this machine. Useful when pruning dead workers on startup.



557
558
559
560
561
# File 'lib/resque/worker.rb', line 557

def linux_worker_pids
  `ps -A -o pid,command | grep "[r]esque" | grep -v "resque-web"`.split("\n").map do |line|
    line.split(' ')[0]
  end
end

#log(message) ⇒ Object

Log a message to STDOUT if we are verbose or very_verbose.



586
587
588
589
590
591
592
593
# File 'lib/resque/worker.rb', line 586

def log(message)
  if verbose
    puts "*** #{message}"
  elsif very_verbose
    time = Time.now.strftime('%H:%M:%S %Y-%m-%d')
    puts "** [#{time}] #$$: #{message}"
  end
end

#log!(message) ⇒ Object

Logs a very verbose message to STDOUT.



596
597
598
# File 'lib/resque/worker.rb', line 596

def log!(message)
  log message if very_verbose
end

#new_kill_childObject

Kills the forked child immediately with minimal remorse. The job it is processing will not be completed. Send the child a TERM signal, wait 5 seconds, and then a KILL signal if it has not quit



350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/resque/worker.rb', line 350

def new_kill_child
  if @child
    unless Process.waitpid(@child, Process::WNOHANG)
      log! "Sending TERM signal to child #{@child}"
      Process.kill("TERM", @child)
      (term_timeout.to_f * 10).round.times do |i|
        sleep(0.1)
        return if Process.waitpid(@child, Process::WNOHANG)
      end
      log! "Sending KILL signal to child #{@child}"
      Process.kill("KILL", @child)
    else
      log! "Child #{@child} already quit."
    end
  end
rescue SystemCallError
  log! "Child #{@child} already quit and reaped."
end

#pause_processingObject

Stop processing jobs after the current one has completed (if we’re currently running one).



376
377
378
379
# File 'lib/resque/worker.rb', line 376

def pause_processing
  log "USR2 received; pausing job processing"
  @paused = true
end

#paused?Boolean

are we paused?

Returns:

  • (Boolean)


370
371
372
# File 'lib/resque/worker.rb', line 370

def paused?
  @paused
end

#perform(job) ⇒ Object

Processes a given job in the child.



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/resque/worker.rb', line 185

def perform(job)
  begin
    run_hook :after_fork, job
    job.perform
  rescue Object => e
    log "#{job.inspect} failed: #{e.inspect}"
    begin
      job.fail(e)
    rescue Object => e
      log "Received exception when reporting failure: #{e.inspect}"
    end
    failed!
  else
    log "done: #{job.inspect}"
  ensure
    yield job if block_given?
  end
end

#pidObject

Returns Integer PID of running worker



539
540
541
# File 'lib/resque/worker.rb', line 539

def pid
  Process.pid
end

#process(job = nil, &block) ⇒ Object

DEPRECATED. Processes a single job. If none is given, it will try to produce one. Usually run in the child.



174
175
176
177
178
179
180
181
182
# File 'lib/resque/worker.rb', line 174

def process(job = nil, &block)
  return unless job ||= reserve

  job.worker = self
  working_on job
  perform(job, &block)
ensure
  done_working
end

#processedObject

How many jobs has this worker processed? Returns an int.



464
465
466
# File 'lib/resque/worker.rb', line 464

def processed
  Stat["processed:#{self}"]
end

#processed!Object

Tell Redis we’ve processed a job.



469
470
471
472
# File 'lib/resque/worker.rb', line 469

def processed!
  Stat << "processed"
  Stat << "processed:#{self}"
end

#procline(string) ⇒ Object

Given a string, sets the procline ($0) and logs. Procline is always in the format of:

resque-VERSION: STRING


580
581
582
583
# File 'lib/resque/worker.rb', line 580

def procline(string)
  $0 = "resque-#{Resque::Version}: #{string}"
  log! $0
end

#prune_dead_workersObject

Looks for any workers which should be running on this server and, if they’re not, removes them from Redis.

This is a form of garbage collection. If a server is killed by a hard shutdown, power failure, or something else beyond our control, the Resque workers will not die gracefully and therefore will leave stale state information in Redis.

By checking the current Redis state against the actual environment, we can determine if Redis is old and clean it up a bit.



397
398
399
400
401
402
403
404
405
406
407
# File 'lib/resque/worker.rb', line 397

def prune_dead_workers
  all_workers = Worker.all
  known_workers = worker_pids unless all_workers.empty?
  all_workers.each do |worker|
    host, pid, queues = worker.id.split(':')
    next unless host == hostname
    next if known_workers.include?(pid)
    log! "Pruning dead worker: #{worker}"
    worker.unregister_worker
  end
end

#queuesObject

Returns a list of queues to use when searching for a job. A splat (“*”) means you want every queue (in alpha order) - this can be useful for dynamically adding new queues.



225
226
227
# File 'lib/resque/worker.rb', line 225

def queues
  @queues.map {|queue| queue == "*" ? Resque.queues.sort : queue }.flatten.uniq
end

#register_signal_handlersObject

Registers the various signal handlers a worker responds to.

TERM: Shutdown immediately, stop processing jobs.

INT: Shutdown immediately, stop processing jobs.

QUIT: Shutdown after the current job has finished processing. USR1: Kill the forked child immediately, continue processing jobs. USR2: Don’t process any new jobs CONT: Start processing jobs again after a USR2



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/resque/worker.rb', line 279

def register_signal_handlers
  trap('TERM') { shutdown!  }
  trap('INT')  { shutdown!  }

  begin
    trap('QUIT') { shutdown   }
    if term_child
      trap('USR1') { new_kill_child }
    else
      trap('USR1') { kill_child }
    end
    trap('USR2') { pause_processing }
    trap('CONT') { unpause_processing }
  rescue ArgumentError
    warn "Signals QUIT, USR1, USR2, and/or CONT not supported."
  end

  log! "Registered signals"
end

#register_workerObject

Registers ourself as a worker. Useful when entering the worker lifecycle on startup.



411
412
413
414
# File 'lib/resque/worker.rb', line 411

def register_worker
  redis.sadd(:workers, self)
  started!
end

#reserveObject

Attempts to grab a job off one of the provided queues. Returns nil if no job can be found.



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/resque/worker.rb', line 206

def reserve
  queues.each do |queue|
    log! "Checking #{queue}"
    if job = Resque.reserve(queue)
      log! "Found job on #{queue}"
      return job
    end
  end

  nil
rescue Exception => e
  log "Error reserving job: #{e.inspect}"
  log e.backtrace.join("\n")
  raise e
end

#run_hook(name, *args) ⇒ Object

Runs a named hook, passing along any arguments.



417
418
419
420
421
422
423
424
# File 'lib/resque/worker.rb', line 417

def run_hook(name, *args)
  return unless hook = Resque.send(name)
  msg = "Running #{name} hook"
  msg << " with #{args.inspect}" if args.any?
  log msg

  args.any? ? hook.call(*args) : hook.call
end

#shutdownObject

Schedule this worker for shutdown. Will finish processing the current job.



313
314
315
316
# File 'lib/resque/worker.rb', line 313

def shutdown
  log 'Exiting...'
  @shutdown = true
end

#shutdown!Object

Kill the child and shutdown immediately.



319
320
321
322
323
324
325
326
# File 'lib/resque/worker.rb', line 319

def shutdown!
  shutdown
  if term_child
    new_kill_child
  else
    kill_child
  end
end

#shutdown?Boolean

Should this worker shutdown as soon as current job is finished?

Returns:

  • (Boolean)


329
330
331
# File 'lib/resque/worker.rb', line 329

def shutdown?
  @shutdown
end

#solaris_worker_pidsObject

Find Resque worker pids on Solaris.

Returns an Array of string pids of all the other workers on this machine. Useful when pruning dead workers on startup.



567
568
569
570
571
572
573
574
575
# File 'lib/resque/worker.rb', line 567

def solaris_worker_pids
  `ps -A -o pid,comm | grep "[r]uby" | grep -v "resque-web"`.split("\n").map do |line|
    real_pid = line.split(' ')[0]
    pargs_command = `pargs -a #{real_pid} 2>/dev/null | grep [r]esque | grep -v "resque-web"`
    if pargs_command.split(':')[1] == " resque-#{Resque::Version}"
      real_pid
    end
  end.compact
end

#startedObject

What time did this worker start? Returns an instance of ‘Time`



486
487
488
# File 'lib/resque/worker.rb', line 486

def started
  redis.get "worker:#{self}:started"
end

#started!Object

Tell Redis we’ve started



491
492
493
# File 'lib/resque/worker.rb', line 491

def started!
  redis.set("worker:#{self}:started", Time.now.to_s)
end

#startupObject

Runs all the methods needed when a worker begins its lifecycle.



250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/resque/worker.rb', line 250

def startup
  warn "WARNING: This way of doing signal handling is now deprecated. Please see http://hone.heroku.com/resque/2012/08/21/resque-signals.html for more info." unless term_child
  enable_gc_optimizations
  register_signal_handlers
  prune_dead_workers
  run_hook :before_first_fork
  register_worker

  # Fix buffering so we can `rake resque:work > resque.log` and
  # get output from the child in there.
  $stdout.sync = true
end

#stateObject

Returns a symbol representing the current worker state, which can be either :working or :idle



513
514
515
# File 'lib/resque/worker.rb', line 513

def state
  redis.exists("worker:#{self}") ? :working : :idle
end

#unpause_processingObject

Start processing jobs again after a pause



382
383
384
385
# File 'lib/resque/worker.rb', line 382

def unpause_processing
  log "CONT received; resuming job processing"
  @paused = false
end

#unregister_signal_handlersObject



299
300
301
302
303
304
305
306
307
308
309
# File 'lib/resque/worker.rb', line 299

def unregister_signal_handlers
  trap('TERM') { raise TermException.new("SIGTERM") }
  trap('INT', 'DEFAULT')

  begin
    trap('QUIT', 'DEFAULT')
    trap('USR1', 'DEFAULT')
    trap('USR2', 'DEFAULT')
  rescue ArgumentError
  end
end

#unregister_workerObject

Unregisters ourself as a worker. Useful when shutting down.



427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'lib/resque/worker.rb', line 427

def unregister_worker
  # If we're still processing a job, make sure it gets logged as a
  # failure.
  if (hash = processing) && !hash.empty?
    job = Job.new(hash['queue'], hash['payload'])
    # Ensure the proper worker is attached to this job, even if
    # it's not the precise instance that died.
    job.worker = self
    job.fail(DirtyExit.new)
  end

  redis.srem(:workers, self)
  redis.del("worker:#{self}")
  redis.del("worker:#{self}:started")

  Stat.clear("processed:#{self}")
  Stat.clear("failed:#{self}")
end

#validate_queuesObject

A worker must be given a queue, otherwise it won’t know what to do with itself.

You probably never need to call this.



106
107
108
109
110
# File 'lib/resque/worker.rb', line 106

def validate_queues
  if @queues.nil? || @queues.empty?
    raise NoQueueError.new("Please give each worker at least one queue.")
  end
end

#work(interval = 5.0, &block) ⇒ Object

This is the main workhorse method. Called on a Worker instance, it begins the worker life cycle.

The following events occur during a worker’s life cycle:

  1. Startup: Signals are registered, dead workers are pruned,

    and this worker is registered.
    
  2. Work loop: Jobs are pulled from a queue and processed.

  3. Teardown: This worker is unregistered.

Can be passed a float representing the polling frequency. The default is 5 seconds, but for a semi-active site you may want to use a smaller value.

Also accepts a block which will be passed the job as soon as it has completed processing. Useful for testing.



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/resque/worker.rb', line 128

def work(interval = 5.0, &block)
  interval = Float(interval)
  $0 = "resque: Starting"
  startup

  loop do
    break if shutdown?

    if not paused? and job = reserve
      log "got: #{job.inspect}"
      job.worker = self
      run_hook :before_fork, job
      working_on job

      if @child = fork
        srand # Reseeding
        procline "Forked #{@child} at #{Time.now.to_i}"
        begin
          Process.waitpid(@child)
        rescue SystemCallError
          nil
        end
      else
        unregister_signal_handlers if !@cant_fork && term_child
        procline "Processing #{job.queue} since #{Time.now.to_i}"
        redis.client.reconnect # Don't share connection with parent
        perform(job, &block)
        exit! unless @cant_fork
      end

      done_working
      @child = nil
    else
      break if interval.zero?
      log! "Sleeping for #{interval} seconds"
      procline paused? ? "Paused" : "Waiting for #{@queues.join(',')}"
      sleep interval
    end
  end

ensure
  unregister_worker
end

#worker_pidsObject

Returns an Array of string pids of all the other workers on this machine. Useful when pruning dead workers on startup.



545
546
547
548
549
550
551
# File 'lib/resque/worker.rb', line 545

def worker_pids
  if RUBY_PLATFORM =~ /solaris/
    solaris_worker_pids
  else
    linux_worker_pids
  end
end

#working?Boolean

Boolean - true if working, false if not

Returns:

  • (Boolean)


502
503
504
# File 'lib/resque/worker.rb', line 502

def working?
  state == :working
end

#working_on(job) ⇒ Object

Given a job, tells Redis we’re working on it. Useful for seeing what workers are doing and when.



448
449
450
451
452
453
454
# File 'lib/resque/worker.rb', line 448

def working_on(job)
  data = encode \
    :queue   => job.queue,
    :run_at  => Time.now.strftime("%Y/%m/%d %H:%M:%S %Z"),
    :payload => job.payload
  redis.set("worker:#{self}", data)
end