Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
The job fork is setting an $exit flag when asked to quit so that the …
…job can exit early if it makes sense
  • Loading branch information
andrewtimberlake committed Nov 29, 2012
1 parent 25be6e0 commit 4b471f2
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 3 deletions.
22 changes: 19 additions & 3 deletions lib/cascade/worker.rb
@@ -1,14 +1,23 @@
module Cascade
class Worker
attr_reader :number
attr_accessor :child_pid
def initialize(number)
@number = number
self.child_pid = nil
end
attr_reader :number

def start
proc_name = $0
$0 = [proc_name.sub(/master/, '').strip, "worker #{number}"].join(' ')

[:INT, :TERM, :QUIT].each do |sig|
trap(sig) do
Process.kill(sig, child_pid) if child_pid
$exit = true
end
end

loop do
result = run

Expand Down Expand Up @@ -44,7 +53,13 @@ def run
def run_forked(job_spec)
read, write = IO.pipe

pid = fork do
self.child_pid = fork do
[:INT, :TERM, :QUIT].each do |sig|
trap(sig) do
$exit = true
end
end

read.close

job_class = job_spec.class_name.constantize
Expand All @@ -62,7 +77,8 @@ def run_forked(job_spec)
end
write.close
result = read.read.strip
pid, status = Process.wait2(pid)
pid, status = Process.wait2(child_pid)
child_pid = nil

if status.exitstatus != 0
job_spec.reload
Expand Down
17 changes: 17 additions & 0 deletions spec/lib/cascade/worker_spec.rb
Expand Up @@ -215,5 +215,22 @@ module Cascade
results['RepeatableJob'][:failed].should eql(1)
end
end

context "when the worker exits" do
let!(:job_spec) { Worker.enqueue(ExitableJob) }

it "gives the job an option to exit early" do
pid = fork do
trap(:TERM) { $exit = true; }
Worker.new(1).start
end
sleep 0.5
Process.kill(:TERM, pid)
sleep 0.1
Timeout::timeout(2) do
Process.wait(pid)
end
end
end
end
end
14 changes: 14 additions & 0 deletions spec/spec_helper.rb
Expand Up @@ -58,3 +58,17 @@ class RepeatableJob
job_spec.re_run = true
end
end

class ExitableJob
include Cascade::Job

def run
count = 0
loop do
sleep 0.1
break if $exit
count += 1
raise 'This should have exited by now' if count > 1000
end
end
end

0 comments on commit 4b471f2

Please sign in to comment.