Class: RQ::Feeder

Inherits:
MainHelper show all
Defined in:
lib/rq/feeder.rb

Overview

the Feeder class is responsible for running jobs from a queue - or ‘feeding’ from that queue. the mode of operation is essentially to run jobs as quickly as possible, return them to the queue, and then to run more jobs if any exist. if no jobs exist the Feeder will periodically poll the queue to see if any new jobs have arrived.

Constant Summary collapse

DEFAULT_MIN_SLEEP =

–{{{

42
DEFAULT_MAX_SLEEP =
240
DEFAULT_FEED =
2

Constants included from Logging

Logging::DIV0, Logging::DIV1, Logging::DIV2, Logging::DIV3, Logging::EOL, Logging::SEC0, Logging::SEC1, Logging::SEC2, Logging::SEC3

Class Attribute Summary collapse

Attributes inherited from MainHelper

#argv, #cmd, #dot_rq_dir, #env, #fields, #job_stdin, #loops, #main, #mode, #options, #program, #q, #qpath, #quiet, #stdin

Instance Method Summary collapse

Methods inherited from MainHelper

#dumping_yaml_tuples, #field_match, #init_job_stdin!, #initialize, #loadio, #loadyaml, #set_q

Methods included from Logging

append_features

Methods included from Logging::LogMethods

#debug, #error, #fatal, #info, #logerr, #logger, #logger=, #warn

Methods included from Util

#alive?, append_features, #btrace, #columnize, #defval, #emsg, #erreq, #errmsg, #escape, #escape!, #exec, export, #fork, #getopt, #hashify, #hms, #host, #hostname, #klass, #maim, #mcp, #realpath, #stamptime, #system, #timestamp, #tmpnam, #uncache, #which_ruby

Constructor Details

This class inherits a constructor from RQ::MainHelper

Class Attribute Details

.feedObject

Returns the value of attribute feed.



37
38
39
# File 'lib/rq/feeder.rb', line 37

def feed
  @feed
end

.max_sleepObject

Returns the value of attribute max_sleep.



36
37
38
# File 'lib/rq/feeder.rb', line 36

def max_sleep
  @max_sleep
end

.min_sleepObject

–{{{



35
36
37
# File 'lib/rq/feeder.rb', line 35

def min_sleep
  @min_sleep
end

Instance Method Details

#busy?Boolean

–}}}

Returns:

  • (Boolean)


510
511
512
513
514
# File 'lib/rq/feeder.rb', line 510

def busy?
#--{{{
  @children.size >= @max_feed
#--}}}
end

#daemonObject

–}}}



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/rq/feeder.rb', line 104

def daemon
#--{{{
  if @options['daemon']
    fork do
      Process::setsid
      pid =
        fork do
          Dir::chdir(Util.realpath('~'))
          File::umask 0
          @daemon = true
          yield
          exit EXIT_SUCCESS
        end
      # STDOUT.puts "#{ pid }"
      exit!
    end
    exit!
  else
    @daemon = false 
    yield
    exit EXIT_SUCCESS
  end
#--}}}
end

#feedObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/rq/feeder.rb', line 41

def feed
#--{{{
  daemon do
    gen_pidfile
    @main.init_logging
    @logger = @main.logger
    set_q

    @pid = Process::pid
    @cmd = @main.cmd 
    @started = Util::timestamp
    @min_sleep = Integer(@options['min_sleep'] || defval('min_sleep'))
    @max_sleep = Integer(@options['max_sleep'] || defval('max_sleep'))
    @max_feed = Integer(@options['max_feed'] || defval('feed'))
    @loops = Integer @options['loops'] rescue nil
    @children = Hash::new 
    @jrd = JobRunnerDaemon::daemon @q

    install_signal_handlers

    if @daemon and not @quiet
      STDOUT.puts "pid <#{ Process::pid }> started"
      STDOUT.flush
    end

    install_redirects

    info{ "** STARTED **" }
    info{ "version <#{ RQ::VERSION }>" }
    info{ "cmd <#{ @cmd }>" }
    info{ "pid <#{ @pid }>" }
    info{ "pidfile <#{ @pidfile.path }>" }
    info{ "jobrunnerdaemon uri <#{ @jrd.uri }> pid <#{ @jrd.pid }>" }
    info{ "qpath <#{ @qpath }>" }
    debug{ "mode <#{ @mode }>" }
    debug{ "max_feed <#{ @max_feed }>" }
    debug{ "min_sleep <#{ @min_sleep }>" }
    debug{ "max_sleep <#{ @max_sleep }>" }

    transaction do
      fill_morgue
      reap_zombie_ios
    end

    looping do
      handle_signal if $rq_signaled
      throttle(@min_sleep) do
        start_jobs unless busy?
        if nothing_running?
          relax
        else
          reap_jobs
        end
      end
    end
  end
#--}}}
end

#fill_morgueObject

–}}}



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/rq/feeder.rb', line 283

def fill_morgue
#--{{{
  debug{ "filling morgue..." }
  transaction do
    deadjobs = @q.getdeadjobs @started
    deadjobs.each do |job|
      @q.jobisdead job
      unless job['restartable']
        info{ "burried job <#{ job['jid'] }>" }
      else
        warn{ "dead job <#{ job['jid'] }> will be restarted" }
      end
    end
  end
  debug{ "filled morgue" }
#--}}}
end

#finish_job(job, status) ⇒ Object

–}}}



480
481
482
483
484
485
486
487
488
489
490
491
492
493
# File 'lib/rq/feeder.rb', line 480

def finish_job job, status
#--{{{
  job['finished'] = Util::timestamp(Time::now)
  job['elapsed'] = Util::stamptime(job['finished']) - Util::stamptime(job['started'])
  t = status.exitstatus rescue nil 
  job['exit_status'] = t 
  job['state'] = 'finished' 
  if t and t == 0
    info{ "finished - jid <#{ job['jid'] }> pid <#{ job['pid'] }> exit_status <#{ job['exit_status'] }>" }
  else
    warn{ "finished - jid <#{ job['jid'] }> pid <#{ job['pid'] }> exit_status <#{ job['exit_status'] }>" }
  end
#--}}}
end

#gen_feeder_name(path = nil) ⇒ Object

–}}}



216
217
218
219
220
221
222
223
224
225
# File 'lib/rq/feeder.rb', line 216

def gen_feeder_name path = nil
#--{{{
  path ||= (@options['name'] || @qpath)
  path = Util::realpath(path).gsub(%r|/|o, '_')
  #File::join(Util::realpath('~'), ".#{ path }.feeder")
  basename = ".#{ Util::host }_#{ path }.feeder".gsub(%r/_+/,'_')
  dirname = Util::realpath '~'
  File::join dirname, basename
#--}}}
end

#gen_pidfile(name = nil) ⇒ Object

–}}}



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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/rq/feeder.rb', line 128

def gen_pidfile name = nil
#--{{{
  gen_pidfilepath

  begin
    FileUtils::mkdir_p(File::dirname(@pidfilepath))
  rescue
    nil
  end

  locked = nil 
  no_other_feeder = nil 

  2.times do
    locked = false
    no_other_feeder = false 

    @pidfile = 
      begin
        open @pidfilepath, File::CREAT | File::EXCL | File::RDWR
      rescue
        open @pidfilepath, File::RDWR
      end

    ret = @pidfile.posixlock(File::LOCK_EX | File::LOCK_NB)
    locked = (ret == 0)

    begin
      pid = Integer(IO::read(@pidfilepath)) rescue nil

      unless pid
        no_other_feeder = true 
        break
      end

      if Util::alive?(pid)
        no_other_feeder = Process::pid == pid ? true : false
          #no_other_feeder = false 
        #else
          #no_other_feeder = false 
        #end
        break
      else
        no_other_feeder = true 
        STDERR.puts "WARNING : process <#{ pid }> died holding lock on <#{ @pidfilepath }>"
        STDERR.puts "WARNING : attempting autorecovery!"
        break if locked
        STDERR.puts "WARNING : your NFS locking setup is FUBAR - iptables or firewall issues!"
        STDERR.puts "WARNING : attempting autorecovery!"
        FileUtils::rm_f @pidfilepath 
        4.times{ sleep rand }
      end

    rescue Exception => e
      STDERR.puts "WARNING : #{ e.message } (#{ e.class })"
    end
  end


  unless(locked and no_other_feeder)
    pid = Integer(IO::read(@pidfilepath)) rescue 'UNKNOWN' 
    if @options['quiet']
      exit EXIT_FAILURE
    else
      abort "process <#{ pid }> is already feeding from this queue"
    end
  else
    @pidfile.chmod 0600 rescue nil
    @pidfile.rewind
    @pidfile.sync = true
    @pidfile.print Process::pid
    @pidfile.truncate @pidfile.pos
    @pidfile.flush

    at_exit do 
      FileUtils::rm_f @pidfilepath rescue nil
      @pidfile.posixlock File::LOCK_UN rescue nil
      @pidfile.close rescue nil
    end
  end
#--}}}
end

#gen_pidfilepathObject

–}}}



210
211
212
213
214
215
# File 'lib/rq/feeder.rb', line 210

def gen_pidfilepath
#--{{{
  # @pidfilepath ||= gen_feeder_name
  @pidfilepath ||= File::join(@dot_rq_dir, 'pid') 
#--}}}
end

#handle_signalObject

–}}}



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/rq/feeder.rb', line 328

def handle_signal
#--{{{
  if $rq_sigterm or $rq_sigint
    reap_jobs(reap_only = true) until nothing_running? 
    info{ "** STOPPING **" }
    @jrd.shutdown rescue nil
    @pidfile.posixlock File::LOCK_UN
    exit EXIT_SUCCESS
  end

  if $rq_sighup
    reap_jobs(reap_only = true) until nothing_running? 
    info{ "** RESTARTING **" }
    info{ "** ARGV <#{ @cmd }> **" }
    begin
      @jrd.shutdown rescue nil
      Util::uncache __FILE__ 
      @pidfile.posixlock File::LOCK_UN
      Util::exec @cmd
    rescue Exception => e
      fatal{"** FAILED TO RESTART! **"}
      fatal{ e }
      exit EXIT_FAILURE
    end
  end
#--}}}
end

#install_redirectsObject

–}}}



272
273
274
275
276
277
278
279
280
281
282
# File 'lib/rq/feeder.rb', line 272

def install_redirects
#--{{{
  if @daemon
    open('/dev/null','r+') do |f|
      STDIN.reopen f 
      STDOUT.reopen f 
      STDERR.reopen f 
    end
  end
#--}}}
end

#install_signal_handlersObject

–}}}



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/rq/feeder.rb', line 226

def install_signal_handlers
#--{{{
  if @daemon or ENV['RQ_SIGNALS']
    $rq_signaled = false
    $rq_sighup = false
    $rq_sigterm = false
    $rq_sigint = false
    trap('SIGHUP') do
      $rq_signaled = $rq_sighup = 'SIGHUP' 
      if nothing_running?
        warn{ "signal <SIGHUP>" }
        handle_signal
      else
        warn{ "finishing running jobs before handling signal" }
      end
    end
    trap('SIGTERM') do
      $rq_signaled = $rq_sigterm = 'SIGTERM' 
      if nothing_running?
        warn{ "signal <SIGTERM>" }
        handle_signal
      else
        warn{ "finishing running jobs before handling signal" }
      end
    end
    trap('SIGINT') do
      $rq_signaled = $rq_sigint = 'SIGINT' 
      if nothing_running?
        warn{ "signal <SIGINT>" }
        handle_signal
      else
        warn{ "finishing running jobs before handling signal" }
      end
    end
    @jrd.install_signal_handlers
  else
    %w(SIGHUP SIGTERM SIGINT).each do |sig|
      trap(sig) do
        warn{ "signal <#{ sig }>" }
        warn{ "not cleaning up - only daemon mode cleans up!" }
        exit
      end
    end
  end
#--}}}
end

#loopingObject

–}}}



99
100
101
102
103
# File 'lib/rq/feeder.rb', line 99

def looping
  #--{{{
  @loops && @loops > 0 ? @loops.times{ yield } : loop{ yield }
  #--}}}
end

#nothing_running?Boolean

–}}}

Returns:

  • (Boolean)


417
418
419
420
421
# File 'lib/rq/feeder.rb', line 417

def nothing_running?
#--{{{
  @children.size == 0
#--}}}
end

#reap_jobs(reap_only = false, blocking = true) ⇒ Object

–}}}



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# File 'lib/rq/feeder.rb', line 422

def reap_jobs reap_only = false, blocking = true
#--{{{
  debug{ "reaping jobs..." }
  reaped = []

  cid = status = nil
    
  if blocking
    if busy? or reap_only
      cid, status = @jrd.waitpid2 -1, Process::WUNTRACED 
    else
      loop do
        debug{ "not busy - busywait loop" }
        cid, status = @jrd.waitpid2 -1, Process::WNOHANG | Process::WUNTRACED 
        break if cid
        start_jobs unless $rq_signaled
        break if busy?
        cid, status = @jrd.waitpid2 -1, Process::WNOHANG | Process::WUNTRACED 
        break if cid
        sleep 4.2 
      end
      cid, status = @jrd.waitpid2 -1, Process::WUNTRACED unless cid
    end
  else
    cid, status = @jrd.waitpid2 -1, Process::WNOHANG | Process::WUNTRACED 
  end
    
  if cid and status
    job = @children[cid]
    finish_job job, status
    
    transaction do
      loopno = 0
      loop do
        @q.jobisdone job
        @children.delete cid
        reaped << cid
    
        start_jobs unless reap_only or $rq_signaled
    
        if @children.size == 0 or loopno > 42
          sleep 8 if loopno > 42 # wow - we are CRANKING through jobs so BACK OFF!!
          break
        else
          sleep 0.1
          cid, status = @jrd.waitpid2 -1, Process::WNOHANG | Process::WUNTRACED 
          break unless cid and status
          job = @children[cid]
          finish_job job, status
        end
        loopno += 1
      end
    end
  end
  debug{ "<#{ reaped.size }> jobs reaped" }
  reaped
#--}}}
end

#reap_zombie_iosObject

–}}}



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/rq/feeder.rb', line 300

def reap_zombie_ios 
#--{{{
  debug{ "reaping zombie ios" }
  begin
    transaction do
      stdin, stdout, stderr, data = @q.stdin, @q.stdout, @q.stderr, @q.data
      jids = @q.execute("select jid from jobs").map{|tuple| Integer tuple.first}
      jids = jids.inject({}){|h,jid| h.update jid => true}
      %w[ stdin stdout stderr data ].each do |d|
        Dir::glob(File::join(@q.send(d), "*")).each do |iof|
          begin
            jid = Integer iof[%r/\d+\s*$/]
            unless jids[jid]
              debug{ "removing zombie io <#{ iof }>" }
              FileUtils::rm_rf iof
            end
          rescue
            next
          end
        end
      end
    end
  rescue Exception => e # because this is a non-essential function
    warn{ e }
  end
  debug{ "reaped" }
#--}}}
end

#relaxObject

–}}}



515
516
517
518
519
520
521
# File 'lib/rq/feeder.rb', line 515

def relax
#--{{{
  seconds = rand(@max_sleep - @min_sleep + 1) + @min_sleep
  debug{ "relaxing <#{ seconds }>" }
  sleep seconds
#--}}}
end

#start_job(job) ⇒ Object

–}}}



387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/rq/feeder.rb', line 387

def start_job job
#--{{{
  jid, command = job['jid'], job['command']

#
# we setup state slightly prematurely so jobrunner will have it availible
#
  job['state'] = 'running'
  job['started'] = Util::timestamp Time::now
  job['runner'] = Util::hostname 

  job['stdout'] = @q.stdout4 jid
  job['stderr'] = @q.stderr4 jid

  jr = @jrd.runner job
  cid = jr.cid
    
  if jr and cid
    jr.run
    job['pid'] = cid
    @children[cid] = job
    @q.jobisrunning job
    info{ "started - jid <#{ job['jid'] }> pid <#{ job['pid'] }> command <#{ job['command'] }>" }
  else
    error{ "not started - jid <#{ job['jid'] }> command <#{ job['command'] }>" }
  end
    
  cid
#--}}}
end

#start_jobsObject

–}}}



372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# File 'lib/rq/feeder.rb', line 372

def start_jobs
#--{{{
  debug{ "starting jobs..." }
  n_started = 0 
  transaction do
    until busy?
      break unless((job = @q.getjob))
      start_job job
      n_started += 1 
    end
  end
  debug{ "<#{ n_started }> jobs started" }
  n_started
#--}}}
end

#throttle(rate = @min_sleep) ⇒ Object

–}}}



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/rq/feeder.rb', line 355

def throttle rate = @min_sleep 
#--{{{
  if Numeric === rate and rate > 0 
    if defined? @last_throttle_time and @last_throttle_time
      elapsed = Time.now - @last_throttle_time
      timeout = rate - elapsed
      if timeout > 0
        timeout = timeout + rand(rate * 0.10)
        debug{ "throttle rate of <#{ rate }> exceeded - sleeping <#{ timeout }>" }
        sleep timeout
      end
    end
    @last_throttle_time = Time.now 
  end
  yield
#--}}}
end

#transactionObject

–}}}



494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# File 'lib/rq/feeder.rb', line 494

def transaction
#--{{{
  ret = nil
  if @in_transaction
    ret = yield
  else
    begin
      @in_transaction = true
      @q.transaction{ ret = yield }
    ensure
      @in_transaction = false 
    end
  end
  ret
#--}}}
end