Created
March 12, 2014 13:25
-
-
Save wkf/9506870 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env ruby | |
require 'logger' | |
require 'timeout' | |
def trap_signal(s) | |
Signal.trap s do | |
Signal.trap('INT', 'IGNORE') | |
Signal.trap('TERM', 'IGNORE') | |
raise Interrupt | |
end | |
end | |
class Runit | |
def run | |
@pid = Process.spawn "/usr/bin/runsvdir -P /etc/service 'log:#{'.' * 395}'" | |
if $stdout.isatty | |
wait_to_die Process.spawn ('/bin/bash') | |
else | |
@status = wait_to_die | |
end | |
end | |
def stop | |
`/usr/bin/sv down /etc/service/*` | |
kill_self | |
kill_children | |
end | |
private | |
def kill(pid, signal = 'TERM') | |
Process.kill(signal, pid) | |
rescue Errno::ESRCH | |
end | |
def kill_self | |
kill(@pid) | |
Timeout::timeout(5) { wait_to_die } | |
rescue Timeout::Error | |
kill(@pid, 'KILL') | |
wait_to_die | |
end | |
def kill_children | |
kill(-1) | |
Timeout::timeout(5) { Process.waitpid(-1) and redo } | |
rescue Timeout::Error | |
kill(-1, 'KILL') | |
rescue Errno::ECHILD | |
end | |
def wait_to_die(pid = @pid) | |
while true do | |
break $?.exitstatus if Process.waitpid(-1) == pid | |
end | |
rescue Errno::ECHILD | |
'??' | |
end | |
end | |
trap_signal('INT') | |
trap_signal('TERM') | |
runit = Runit.new | |
log = Logger.new(STDOUT) | |
begin | |
log.info "Exited with status #{runit.run}" | |
rescue Interrupt | |
log.warn "Keyboard interrupt, halting" | |
ensure | |
runit.stop | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice