Skip to content

Instantly share code, notes, and snippets.

@ayosec
Created May 22, 2013 14:27
Show Gist options
  • Save ayosec/5627951 to your computer and use it in GitHub Desktop.
Save ayosec/5627951 to your computer and use it in GitHub Desktop.
Script to launch (and restart when stopped servers)
require "etc"
# Script used to launch servers, and track their status
groups = {}
pid = nil
uid = nil
ARGV.each do |argument|
case argument
when /(\w+):(.*)/
group, command = [$1, $2]
groups[group] ||= []
groups[group] << command
when /pid=(.*)/
pid = $1
when /uid=(\d+)$/
uid = $1.to_i
when /uid=(.*)/
uid = Etc.getpwnam($1).uid
end
end
def log(message)
print "[#{Time.now.strftime("%F %X")}] [Launcher] #{message}\n"
end
if pid
log("Write PID to #{pid}")
File.open(pid, "w") {|f| f.write $$ }
end
if uid
log("Set UID to #{uid}")
Process.uid = uid
Process.euid = uid
end
PIDs = {}
def run(command)
pid = fork { exec("/bin/sh", "-c", command) }
log("[PID #{pid}] #{command.inspect}")
PIDs[pid] = command
end
Signal.trap("CLD") do
pid = Process.wait()
command = PIDs[pid]
log "<#{command}> terminated. Restarting"
PIDs.delete(pid)
run(command)
end
groups.each_value do |group|
group.each do |command|
run(command)
end
end
sleep 1000 while true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment