summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorElvin Efendi <elvin.efendiyev@gmail.com>2015-12-04 13:49:17 -0500
committerElvin Efendi <elvin.efendiyev@gmail.com>2015-12-04 13:49:17 -0500
commitcdb6cf6f2cd3d93d5b704025bdd618b2f4a59859 (patch)
tree5a0b67f6698472cd916b752ff28a536ca21516aa /lib
parenteead03c1557117882b42759de2de4114e3a4b5cd (diff)
parente73de9397d110a1442e3717823605d3020016b17 (diff)
Merge pull request #7 from Shopify/pid-guard
do not start new instance when there is one running
Diffstat (limited to 'lib')
-rw-r--r--lib/oxidized/cli.rb47
1 files changed, 47 insertions, 0 deletions
diff --git a/lib/oxidized/cli.rb b/lib/oxidized/cli.rb
index 00ea4b6..0c87d53 100644
--- a/lib/oxidized/cli.rb
+++ b/lib/oxidized/cli.rb
@@ -4,7 +4,9 @@ module Oxidized
require 'slop'
def run
+ check_pid
Process.daemon if @opts[:daemonize]
+ write_pid
begin
Oxidized.new
rescue => error
@@ -19,6 +21,7 @@ module Oxidized
Log.info "Oxidized starting, running as pid #{$$}"
_args, @opts = parse_opts
Oxidized.config.debug = true if @opts[:debug]
+ @pidfile = File.expand_path("pid")
end
def crash error
@@ -40,5 +43,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