Skip to content

Instantly share code, notes, and snippets.

@totem3
Last active August 29, 2015 14:17
Show Gist options
  • Save totem3/6588f19dd0e28ecfee91 to your computer and use it in GitHub Desktop.
Save totem3/6588f19dd0e28ecfee91 to your computer and use it in GitHub Desktop.
require 'celluloid'
require 'timeout'
Celluloid.task_class = Celluloid::TaskThread
class Worker
include Celluloid
def run(check)
puts "run"
command = check[:command]
timeout = check[:timeout] || 1
r, w = IO.pipe
pid = spawn(command, pgroup: true, out: w)
thread = Process.detach(pid)
Timeout.timeout(timeout) do
thread.join
end
w.close
result = r.readlines
puts "result = #{result}"
p thread.value.exitstatus
rescue Timeout::Error
puts "execution expired"
Process.kill(:TERM, pid)
ensure
r.close unless r.closed?
w.close unless w.closed?
end
end
class Manager
include Celluloid
def initialize(jobs)
@jobs = jobs
@worker = Celluloid::Actor[:worker]
async.run
end
def run
while job = @jobs.pop
@worker.async.run(job)
end
end
end
class Supervisor < Celluloid::SupervisionGroup
end
def self.replicate(n, x)
n.times.map { |_| x }
end
check = {command: "sleep 2; echo 'hoge'"}
checks = replicate(10, check)
Supervisor.pool Worker, as: :worker, size: 5
Supervisor.supervise Manager, as: :manager, args: [checks]
g = Supervisor.run!
sleep 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment