Class: UnicornHorn::Worker

Inherits:
Object
  • Object
show all
Extended by:
Configurer
Defined in:
lib/unicorn_horn/worker.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(handler) ⇒ Worker

Returns a new instance of Worker.



10
11
12
13
# File 'lib/unicorn_horn/worker.rb', line 10

def initialize handler
  @name    = handler.respond_to?(:name) ? handler.name : handler.inspect
  @handler = handler
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



8
9
10
# File 'lib/unicorn_horn/worker.rb', line 8

def name
  @name
end

#wpidObject (readonly)

Returns the value of attribute wpid.



8
9
10
# File 'lib/unicorn_horn/worker.rb', line 8

def wpid
  @wpid
end

Instance Method Details

#kill(signal) ⇒ Object



48
49
50
51
52
53
54
# File 'lib/unicorn_horn/worker.rb', line 48

def kill(signal)
  return unless @wpid
  Process.kill(signal, @wpid)
  rescue Errno::ESRCH
    @wpid = nil
    @tmp.close rescue nil
end

#kill_if_idleObject



38
39
40
41
42
43
44
45
46
# File 'lib/unicorn_horn/worker.rb', line 38

def kill_if_idle
  return unless @tmp and @wpid
  stat = @tmp.stat
  stat.mode == 0100600 and return
  (diff = (Time.now - stat.ctime)) <= idle_timeout and return
  logger.error "worker=#{name} PID:#{@wpid} timeout " \
               "(#{diff}s > #{idle_timeout}s), killing"
  kill(:KILL)
end

#launch!Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/unicorn_horn/worker.rb', line 15

def launch!
  @tmp = Utils.tmpio
  @wpid = fork do

    # the prep work
    Utils.proc_name "worker[#{name}]"
    AFTER_FORK.each{ |x| x.call }
    @tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
    [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } }
    alive = @tmp
    m = 0
    @handler = @handler.new if @handler.respond_to?(:new)
    logger.info "worker=#{name} ready"

    # the actual loop
    while Process.ppid && alive
      alive.chmod(m = 0 == m ? 1 : 0)
      @handler.call
    end

  end
end

#reap(status) ⇒ Object



56
57
58
59
60
61
# File 'lib/unicorn_horn/worker.rb', line 56

def reap(status)
  @wpid = nil
  @tmp.close rescue nil
  m = "reaped #{status.inspect} worker=#{name}"
  status.success? ? logger.info(m) : logger.error(m)
end