Last active
August 29, 2015 14:17
-
-
Save totem3/6588f19dd0e28ecfee91 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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