Last Updated: February 25, 2016
·
1.04K
· stevebenner

Manage a daemonized gem server with God

Tom Preston-Werner's God framework is in fact pretty godly. Look at how easy it makes managing a private gem server (geminabox):

God.watch do |w|
  w.name = 'gemserver'
  w.dir = '/usr/local/gemserver'
  w.pid_file = "#{ENV['HOME']}/.god/pids/#{w.name}.pid"
  ru = File.expand_path `which rackup`
  w.start = "#{ru} -D #{w.dir}/config.ru -P #{w.pid_file}"
  # w.stop = lambda { Process.kill(2, `lsof -i :9292`.chomp.to_i) }
  w.behavior :clean_pid_file
  w.keepalive
end

Now I can run commands like:

god start gemserver
god status gemserver
god restart gemserver

To explain the code a bit:

w.dir changes the worlking directory before running actions, unsurprisingly.

We set the 'pid file' variable, a simple location for storing the process ID, to ensure that daemonized processes (those run with -D) can be tracked later on.

Since we are in the project directory, we can run which rackup to locate the binary for your local rackup gem no matter where it is kept, which is very helpful for those using Bundler, as the actual path might vary based on the bundle directory name.

Now w.start can use the correct absolute path to call rackup, which is sensitive about those things! We have to pass the -P option with the file location in order to convince Rack to actually store the file there for us.

The commented w.stop command is not required, but could serve as an alternative means of finding the PID and manually killing the server if we wanted to do it that way. The default is a lambda function that God uses which is smart enough to kill the server for us if we already have the correct PID file location (that's why we set it earlier!).

w.behavior :clean_pid_file makes sure we delete the old file after stopping the server, so it doesn't mess up anything if we run it again.

Use your own private gem server and keep your system secure! Gems can be spoofed and run malicious code; quality developers release checksums so you know they are legit!