diff options
author | ytti <saku@ytti.fi> | 2016-01-04 18:50:54 +0200 |
---|---|---|
committer | ytti <saku@ytti.fi> | 2016-01-04 18:50:54 +0200 |
commit | 0eeba91b426c8b4a6335a88da9c65ba38e5fac15 (patch) | |
tree | 02ba46c4f7d43b5721f3eb7de38599e0e019e5cf /lib/oxidized/cli.rb | |
parent | f112dfa0c604ae1c990f6411a002806924c00bf3 (diff) | |
parent | e41f7b429901eb38ad785ad1fc2527dd41f35959 (diff) |
Merge pull request #250 from Shopify/master0.10.0
refactoring, test coverage and github hook
Diffstat (limited to 'lib/oxidized/cli.rb')
-rw-r--r-- | lib/oxidized/cli.rb | 58 |
1 files changed, 54 insertions, 4 deletions
diff --git a/lib/oxidized/cli.rb b/lib/oxidized/cli.rb index c66ec8d..15d20c5 100644 --- a/lib/oxidized/cli.rb +++ b/lib/oxidized/cli.rb @@ -1,11 +1,14 @@ module Oxidized class CLI - require 'oxidized' require 'slop' + require 'oxidized' def run + check_pid Process.daemon if @opts[:daemonize] + write_pid begin + Oxidized.logger.info "Oxidized starting, running as pid #{$$}" Oxidized.new rescue => error crash error @@ -16,13 +19,16 @@ module Oxidized private def initialize - Log.info "Oxidized starting, running as pid #{$$}" _args, @opts = parse_opts - CFG.debug = true if @opts[:debug] + + Config.load(@opts) + Oxidized.setup_logger + + @pidfile = File.expand_path("pid") end def crash error - Log.fatal "Oxidized crashed, crashfile written in #{Config::Crash}" + Oxidized.logger.fatal "Oxidized crashed, crashfile written in #{Config::Crash}" open Config::Crash, 'w' do |file| file.puts '-' * 50 file.puts Time.now.utc @@ -40,5 +46,49 @@ module Oxidized end [opts.parse!, opts] end + + def pidfile + @pidfile + end + + def pidfile? + !!pidfile + end + + def write_pid + if pidfile? + begin + File.open(pidfile, ::File::CREAT | ::File::EXCL | ::File::WRONLY){|f| f.write("#{Process.pid}") } + at_exit { File.delete(pidfile) if File.exists?(pidfile) } + rescue Errno::EEXIST + check_pid + retry + end + end + end + + def check_pid + if pidfile? + case pid_status(pidfile) + when :running, :not_owned + puts "A server is already running. Check #{pidfile}" + exit(1) + when :dead + File.delete(pidfile) + end + end + end + + def pid_status(pidfile) + return :exited unless File.exists?(pidfile) + pid = ::File.read(pidfile).to_i + return :dead if pid == 0 + Process.kill(0, pid) + :running + rescue Errno::ESRCH + :dead + rescue Errno::EPERM + :not_owned + end end end |