firenxis-god 0.11.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (123) hide show
  1. data/Announce.txt +135 -0
  2. data/History.txt +393 -0
  3. data/README.txt +59 -0
  4. data/Rakefile +142 -0
  5. data/bin/god +132 -0
  6. data/ext/god/.gitignore +5 -0
  7. data/ext/god/extconf.rb +55 -0
  8. data/ext/god/kqueue_handler.c +125 -0
  9. data/ext/god/netlink_handler.c +168 -0
  10. data/god.gemspec +164 -0
  11. data/lib/god.rb +701 -0
  12. data/lib/god/behavior.rb +52 -0
  13. data/lib/god/behaviors/clean_pid_file.rb +21 -0
  14. data/lib/god/behaviors/clean_unix_socket.rb +21 -0
  15. data/lib/god/behaviors/notify_when_flapping.rb +51 -0
  16. data/lib/god/cli/command.rb +256 -0
  17. data/lib/god/cli/run.rb +172 -0
  18. data/lib/god/cli/version.rb +23 -0
  19. data/lib/god/compat19.rb +36 -0
  20. data/lib/god/condition.rb +96 -0
  21. data/lib/god/conditions/always.rb +23 -0
  22. data/lib/god/conditions/complex.rb +86 -0
  23. data/lib/god/conditions/cpu_usage.rb +80 -0
  24. data/lib/god/conditions/degrading_lambda.rb +52 -0
  25. data/lib/god/conditions/disk_usage.rb +32 -0
  26. data/lib/god/conditions/file_mtime.rb +28 -0
  27. data/lib/god/conditions/flapping.rb +128 -0
  28. data/lib/god/conditions/http_response_code.rb +168 -0
  29. data/lib/god/conditions/lambda.rb +25 -0
  30. data/lib/god/conditions/memory_usage.rb +82 -0
  31. data/lib/god/conditions/process_exits.rb +72 -0
  32. data/lib/god/conditions/process_running.rb +74 -0
  33. data/lib/god/conditions/tries.rb +44 -0
  34. data/lib/god/configurable.rb +57 -0
  35. data/lib/god/contact.rb +114 -0
  36. data/lib/god/contacts/campfire.rb +121 -0
  37. data/lib/god/contacts/email.rb +136 -0
  38. data/lib/god/contacts/jabber.rb +75 -0
  39. data/lib/god/contacts/prowl.rb +57 -0
  40. data/lib/god/contacts/scout.rb +55 -0
  41. data/lib/god/contacts/twitter.rb +51 -0
  42. data/lib/god/contacts/webhook.rb +73 -0
  43. data/lib/god/dependency_graph.rb +41 -0
  44. data/lib/god/diagnostics.rb +37 -0
  45. data/lib/god/driver.rb +206 -0
  46. data/lib/god/errors.rb +24 -0
  47. data/lib/god/event_handler.rb +108 -0
  48. data/lib/god/event_handlers/dummy_handler.rb +13 -0
  49. data/lib/god/event_handlers/kqueue_handler.rb +17 -0
  50. data/lib/god/event_handlers/netlink_handler.rb +13 -0
  51. data/lib/god/logger.rb +109 -0
  52. data/lib/god/metric.rb +59 -0
  53. data/lib/god/process.rb +363 -0
  54. data/lib/god/registry.rb +32 -0
  55. data/lib/god/simple_logger.rb +59 -0
  56. data/lib/god/socket.rb +107 -0
  57. data/lib/god/sugar.rb +47 -0
  58. data/lib/god/sys_logger.rb +45 -0
  59. data/lib/god/system/portable_poller.rb +42 -0
  60. data/lib/god/system/process.rb +50 -0
  61. data/lib/god/system/slash_proc_poller.rb +92 -0
  62. data/lib/god/task.rb +503 -0
  63. data/lib/god/timeline.rb +25 -0
  64. data/lib/god/trigger.rb +43 -0
  65. data/lib/god/watch.rb +188 -0
  66. data/test/configs/child_events/child_events.god +44 -0
  67. data/test/configs/child_events/simple_server.rb +3 -0
  68. data/test/configs/child_polls/child_polls.god +37 -0
  69. data/test/configs/child_polls/simple_server.rb +12 -0
  70. data/test/configs/complex/complex.god +59 -0
  71. data/test/configs/complex/simple_server.rb +3 -0
  72. data/test/configs/contact/contact.god +108 -0
  73. data/test/configs/contact/simple_server.rb +3 -0
  74. data/test/configs/daemon_events/daemon_events.god +37 -0
  75. data/test/configs/daemon_events/simple_server.rb +8 -0
  76. data/test/configs/daemon_events/simple_server_stop.rb +11 -0
  77. data/test/configs/daemon_polls/daemon_polls.god +17 -0
  78. data/test/configs/daemon_polls/simple_server.rb +6 -0
  79. data/test/configs/degrading_lambda/degrading_lambda.god +31 -0
  80. data/test/configs/degrading_lambda/tcp_server.rb +15 -0
  81. data/test/configs/lifecycle/lifecycle.god +25 -0
  82. data/test/configs/matias/matias.god +50 -0
  83. data/test/configs/real.rb +59 -0
  84. data/test/configs/running_load/running_load.god +16 -0
  85. data/test/configs/stop_options/simple_server.rb +12 -0
  86. data/test/configs/stop_options/stop_options.god +39 -0
  87. data/test/configs/stress/simple_server.rb +3 -0
  88. data/test/configs/stress/stress.god +15 -0
  89. data/test/configs/task/logs/.placeholder +0 -0
  90. data/test/configs/task/task.god +26 -0
  91. data/test/configs/test.rb +61 -0
  92. data/test/helper.rb +141 -0
  93. data/test/suite.rb +6 -0
  94. data/test/test_behavior.rb +18 -0
  95. data/test/test_campfire.rb +23 -0
  96. data/test/test_condition.rb +50 -0
  97. data/test/test_conditions_disk_usage.rb +50 -0
  98. data/test/test_conditions_http_response_code.rb +109 -0
  99. data/test/test_conditions_process_running.rb +40 -0
  100. data/test/test_conditions_tries.rb +67 -0
  101. data/test/test_contact.rb +109 -0
  102. data/test/test_dependency_graph.rb +62 -0
  103. data/test/test_driver.rb +11 -0
  104. data/test/test_email.rb +34 -0
  105. data/test/test_event_handler.rb +80 -0
  106. data/test/test_god.rb +570 -0
  107. data/test/test_handlers_kqueue_handler.rb +16 -0
  108. data/test/test_jabber.rb +29 -0
  109. data/test/test_logger.rb +55 -0
  110. data/test/test_metric.rb +72 -0
  111. data/test/test_process.rb +247 -0
  112. data/test/test_prowl.rb +15 -0
  113. data/test/test_registry.rb +15 -0
  114. data/test/test_socket.rb +34 -0
  115. data/test/test_sugar.rb +42 -0
  116. data/test/test_system_portable_poller.rb +17 -0
  117. data/test/test_system_process.rb +30 -0
  118. data/test/test_task.rb +246 -0
  119. data/test/test_timeline.rb +37 -0
  120. data/test/test_trigger.rb +59 -0
  121. data/test/test_watch.rb +279 -0
  122. data/test/test_webhook.rb +15 -0
  123. metadata +362 -0
data/lib/god/errors.rb ADDED
@@ -0,0 +1,24 @@
1
+ module God
2
+
3
+ class AbstractMethodNotOverriddenError < StandardError
4
+ end
5
+
6
+ class NoSuchWatchError < StandardError
7
+ end
8
+
9
+ class NoSuchConditionError < StandardError
10
+ end
11
+
12
+ class NoSuchBehaviorError < StandardError
13
+ end
14
+
15
+ class NoSuchContactError < StandardError
16
+ end
17
+
18
+ class InvalidCommandError < StandardError
19
+ end
20
+
21
+ class EventRegistrationFailedError < StandardError
22
+ end
23
+
24
+ end
@@ -0,0 +1,108 @@
1
+ module God
2
+ class EventHandler
3
+ @@actions = {}
4
+ @@handler = nil
5
+ @@loaded = false
6
+
7
+ def self.loaded?
8
+ @@loaded
9
+ end
10
+
11
+ def self.event_system
12
+ @@handler::EVENT_SYSTEM
13
+ end
14
+
15
+ def self.load
16
+ begin
17
+ case RUBY_PLATFORM
18
+ when /darwin/i, /bsd/i
19
+ require 'god/event_handlers/kqueue_handler'
20
+ @@handler = KQueueHandler
21
+ when /linux/i
22
+ require 'god/event_handlers/netlink_handler'
23
+ @@handler = NetlinkHandler
24
+ else
25
+ raise NotImplementedError, "Platform not supported for EventHandler"
26
+ end
27
+ @@loaded = true
28
+ rescue Exception
29
+ require 'god/event_handlers/dummy_handler'
30
+ @@handler = DummyHandler
31
+ @@loaded = false
32
+ end
33
+ end
34
+
35
+ def self.register(pid, event, &block)
36
+ @@actions[pid] ||= {}
37
+ @@actions[pid][event] = block
38
+ @@handler.register_process(pid, @@actions[pid].keys)
39
+ end
40
+
41
+ def self.deregister(pid, event)
42
+ if watching_pid? pid
43
+ running = ::Process.kill(0, pid.to_i) rescue false
44
+ @@actions[pid].delete(event)
45
+ @@handler.register_process(pid, @@actions[pid].keys) if running
46
+ @@actions.delete(pid) if @@actions[pid].empty?
47
+ end
48
+ end
49
+
50
+ def self.call(pid, event, extra_data = {})
51
+ @@actions[pid][event].call(extra_data) if watching_pid?(pid) && @@actions[pid][event]
52
+ end
53
+
54
+ def self.watching_pid?(pid)
55
+ @@actions[pid]
56
+ end
57
+
58
+ def self.start
59
+ Thread.new do
60
+ loop do
61
+ begin
62
+ @@handler.handle_events
63
+ rescue Exception => e
64
+ message = format("Unhandled exception (%s): %s\n%s",
65
+ e.class, e.message, e.backtrace.join("\n"))
66
+ applog(nil, :fatal, message)
67
+ end
68
+ end
69
+ end
70
+
71
+ # do a real test to make sure events are working properly
72
+ @@loaded = self.operational?
73
+ end
74
+
75
+ def self.operational?
76
+ com = [false]
77
+
78
+ Thread.new do
79
+ begin
80
+ event_system = God::EventHandler.event_system
81
+
82
+ pid = fork do
83
+ loop { sleep(1) }
84
+ end
85
+
86
+ self.register(pid, :proc_exit) do
87
+ com[0] = true
88
+ end
89
+
90
+ ::Process.kill('KILL', pid)
91
+ ::Process.waitpid(pid)
92
+
93
+ sleep(0.1)
94
+
95
+ self.deregister(pid, :proc_exit) rescue nil
96
+ rescue => e
97
+ puts e.message
98
+ puts e.backtrace.join("\n")
99
+ end
100
+ end.join
101
+
102
+ sleep(0.1)
103
+
104
+ com.first
105
+ end
106
+
107
+ end
108
+ end
@@ -0,0 +1,13 @@
1
+ module God
2
+ class DummyHandler
3
+ EVENT_SYSTEM = "none"
4
+
5
+ def self.register_process
6
+ raise NotImplementedError
7
+ end
8
+
9
+ def self.handle_events
10
+ raise NotImplementedError
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,17 @@
1
+ require 'kqueue_handler_ext'
2
+
3
+ module God
4
+ class KQueueHandler
5
+ EVENT_SYSTEM = "kqueue"
6
+
7
+ def self.register_process(pid, events)
8
+ monitor_process(pid, events_mask(events))
9
+ end
10
+
11
+ def self.events_mask(events)
12
+ events.inject(0) do |mask, event|
13
+ mask |= event_mask(event)
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,13 @@
1
+ require 'netlink_handler_ext'
2
+
3
+ module God
4
+ class NetlinkHandler
5
+ EVENT_SYSTEM = "netlink"
6
+
7
+ def self.register_process(pid, events)
8
+ # netlink doesn't need to do this
9
+ # it just reads from the eventhandler actions to see if the pid
10
+ # matches the list we're looking for -- Kev
11
+ end
12
+ end
13
+ end
data/lib/god/logger.rb ADDED
@@ -0,0 +1,109 @@
1
+ module God
2
+
3
+ class Logger < SimpleLogger
4
+
5
+ attr_accessor :logs
6
+
7
+ class << self
8
+ attr_accessor :syslog
9
+ end
10
+
11
+ self.syslog = defined?(Syslog)
12
+
13
+ # Instantiate a new Logger object
14
+ def initialize(io = $stdout)
15
+ super(io)
16
+ self.logs = {}
17
+ @mutex = Mutex.new
18
+ @capture = nil
19
+ @spool = Time.now - 10
20
+ @templogio = StringIO.new
21
+ @templog = SimpleLogger.new(@templogio)
22
+ @templog.level = Logger::INFO
23
+ end
24
+
25
+
26
+ def level=(lev)
27
+ SysLogger.level = SimpleLogger::CONSTANT_TO_SYMBOL[lev] if Logger.syslog
28
+ super(lev)
29
+ end
30
+
31
+ # Log a message
32
+ # +watch+ is the String name of the Watch (may be nil if not Watch is applicable)
33
+ # +level+ is the log level [:debug|:info|:warn|:error|:fatal]
34
+ # +text+ is the String message
35
+ #
36
+ # Returns nothing
37
+ def log(watch, level, text)
38
+ # initialize watch log if necessary
39
+ self.logs[watch.name] ||= Timeline.new(God::LOG_BUFFER_SIZE_DEFAULT) if watch
40
+
41
+ # push onto capture and timeline for the given watch
42
+ if @capture || (watch && (Time.now - @spool < 2))
43
+ @mutex.synchronize do
44
+ @templogio.truncate(0)
45
+ @templogio.rewind
46
+ @templog.send(level, text)
47
+
48
+ message = @templogio.string.dup
49
+
50
+ if @capture
51
+ @capture.puts(message)
52
+ else
53
+ self.logs[watch.name] << [Time.now, message]
54
+ end
55
+ end
56
+ end
57
+
58
+ # send to regular logger
59
+ self.send(level, text)
60
+
61
+ # send to syslog
62
+ SysLogger.log(level, text) if Logger.syslog
63
+ end
64
+
65
+ # Get all log output for a given Watch since a certain Time.
66
+ # +watch_name+ is the String name of the Watch
67
+ # +since+ is the Time since which to fetch log lines
68
+ #
69
+ # Returns String
70
+ def watch_log_since(watch_name, since)
71
+ # initialize watch log if necessary
72
+ self.logs[watch_name] ||= Timeline.new(God::LOG_BUFFER_SIZE_DEFAULT)
73
+
74
+ # get and join lines since given time
75
+ @mutex.synchronize do
76
+ @spool = Time.now
77
+ self.logs[watch_name].select do |x|
78
+ x.first > since
79
+ end.map do |x|
80
+ x[1]
81
+ end.join
82
+ end
83
+ end
84
+
85
+ # private
86
+
87
+ # Enable capturing of log
88
+ #
89
+ # Returns nothing
90
+ def start_capture
91
+ @mutex.synchronize do
92
+ @capture = StringIO.new
93
+ end
94
+ end
95
+
96
+ # Disable capturing of log and return what was captured since
97
+ # capturing was enabled with Logger#start_capture
98
+ #
99
+ # Returns String
100
+ def finish_capture
101
+ @mutex.synchronize do
102
+ cap = @capture.string if @capture
103
+ @capture = nil
104
+ cap
105
+ end
106
+ end
107
+ end
108
+
109
+ end
data/lib/god/metric.rb ADDED
@@ -0,0 +1,59 @@
1
+ module God
2
+
3
+ class Metric
4
+ attr_accessor :watch, :destination, :conditions
5
+
6
+ def initialize(watch, destination = nil)
7
+ self.watch = watch
8
+ self.destination = destination
9
+ self.conditions = []
10
+ end
11
+
12
+ # Instantiate a Condition of type +kind+ and pass it into the optional
13
+ # block. Attributes of the condition must be set in the config file
14
+ def condition(kind)
15
+ # create the condition
16
+ begin
17
+ c = Condition.generate(kind, self.watch)
18
+ rescue NoSuchConditionError => e
19
+ abort e.message
20
+ end
21
+
22
+ # send to block so config can set attributes
23
+ yield(c) if block_given?
24
+
25
+ # call prepare on the condition
26
+ c.prepare
27
+
28
+ # test generic and specific validity
29
+ unless Condition.valid?(c) && c.valid?
30
+ abort "Exiting on invalid condition"
31
+ end
32
+
33
+ # inherit interval from watch if no poll condition specific interval was set
34
+ if c.kind_of?(PollCondition) && !c.interval
35
+ if self.watch.interval
36
+ c.interval = self.watch.interval
37
+ else
38
+ abort "No interval set for Condition '#{c.class.name}' in Watch '#{self.watch.name}', and no default Watch interval from which to inherit"
39
+ end
40
+ end
41
+
42
+ # remember
43
+ self.conditions << c
44
+ end
45
+
46
+ def enable
47
+ self.conditions.each do |c|
48
+ self.watch.attach(c)
49
+ end
50
+ end
51
+
52
+ def disable
53
+ self.conditions.each do |c|
54
+ self.watch.detach(c)
55
+ end
56
+ end
57
+ end
58
+
59
+ end
@@ -0,0 +1,363 @@
1
+ module God
2
+ class Process
3
+ WRITES_PID = [:start, :restart]
4
+
5
+ attr_accessor :name, :uid, :gid, :log, :log_cmd, :err_log, :err_log_cmd,
6
+ :start, :stop, :restart, :unix_socket, :chroot, :env, :dir,
7
+ :stop_timeout, :stop_signal
8
+
9
+ def initialize
10
+ self.log = '/dev/null'
11
+
12
+ @pid_file = nil
13
+ @tracking_pid = true
14
+ @user_log = false
15
+ @pid = nil
16
+ @unix_socket = nil
17
+ @log_cmd = nil
18
+ @stop_timeout = God::STOP_TIMEOUT_DEFAULT
19
+ @stop_signal = God::STOP_SIGNAL_DEFAULT
20
+ end
21
+
22
+ def alive?
23
+ if self.pid
24
+ System::Process.new(self.pid).exists?
25
+ else
26
+ false
27
+ end
28
+ end
29
+
30
+ def file_writable?(file)
31
+ pid = fork do
32
+ begin
33
+ uid_num = Etc.getpwnam(self.uid).uid if self.uid
34
+ gid_num = Etc.getgrnam(self.gid).gid if self.gid
35
+
36
+ ::Dir.chroot(self.chroot) if self.chroot
37
+ ::Process.groups = [gid_num] if self.gid
38
+ ::Process::Sys.setgid(gid_num) if self.gid
39
+ ::Process::Sys.setuid(uid_num) if self.uid
40
+ rescue ArgumentError, Errno::EPERM, Errno::ENOENT
41
+ exit(1)
42
+ end
43
+
44
+ File.writable?(file_in_chroot(file)) ? exit(0) : exit(1)
45
+ end
46
+
47
+ wpid, status = ::Process.waitpid2(pid)
48
+ status.exitstatus == 0 ? true : false
49
+ end
50
+
51
+ def valid?
52
+ # determine if we're tracking pid or not
53
+ self.pid_file
54
+
55
+ valid = true
56
+
57
+ # a start command must be specified
58
+ if self.start.nil?
59
+ valid = false
60
+ applog(self, :error, "No start command was specified")
61
+ end
62
+
63
+ # uid must exist if specified
64
+ if self.uid
65
+ begin
66
+ Etc.getpwnam(self.uid)
67
+ rescue ArgumentError
68
+ valid = false
69
+ applog(self, :error, "UID for '#{self.uid}' does not exist")
70
+ end
71
+ end
72
+
73
+ # gid must exist if specified
74
+ if self.gid
75
+ begin
76
+ Etc.getgrnam(self.gid)
77
+ rescue ArgumentError
78
+ valid = false
79
+ applog(self, :error, "GID for '#{self.gid}' does not exist")
80
+ end
81
+ end
82
+
83
+ # dir must exist and be a directory if specified
84
+ if self.dir
85
+ if !File.exist?(self.dir)
86
+ valid = false
87
+ applog(self, :error, "Specified directory '#{self.dir}' does not exist")
88
+ elsif !File.directory?(self.dir)
89
+ valid = false
90
+ applog(self, :error, "Specified directory '#{self.dir}' is not a directory")
91
+ end
92
+ end
93
+
94
+ # pid dir must exist if specified
95
+ if !@tracking_pid && !File.exist?(File.dirname(self.pid_file))
96
+ valid = false
97
+ applog(self, :error, "PID file directory '#{File.dirname(self.pid_file)}' does not exist")
98
+ end
99
+
100
+ # pid dir must be writable if specified
101
+ if !@tracking_pid && File.exist?(File.dirname(self.pid_file)) && !file_writable?(File.dirname(self.pid_file))
102
+ valid = false
103
+ applog(self, :error, "PID file directory '#{File.dirname(self.pid_file)}' is not writable by #{self.uid || Etc.getlogin}")
104
+ end
105
+
106
+ # log dir must exist
107
+ if !File.exist?(File.dirname(self.log))
108
+ valid = false
109
+ applog(self, :error, "Log directory '#{File.dirname(self.log)}' does not exist")
110
+ end
111
+
112
+ # log file or dir must be writable
113
+ if File.exist?(self.log)
114
+ unless file_writable?(self.log)
115
+ valid = false
116
+ applog(self, :error, "Log file '#{self.log}' exists but is not writable by #{self.uid || Etc.getlogin}")
117
+ end
118
+ else
119
+ unless file_writable?(File.dirname(self.log))
120
+ valid = false
121
+ applog(self, :error, "Log directory '#{File.dirname(self.log)}' is not writable by #{self.uid || Etc.getlogin}")
122
+ end
123
+ end
124
+
125
+ # chroot directory must exist and have /dev/null in it
126
+ if self.chroot
127
+ if !File.directory?(self.chroot)
128
+ valid = false
129
+ applog(self, :error, "CHROOT directory '#{self.chroot}' does not exist")
130
+ end
131
+
132
+ if !File.exist?(File.join(self.chroot, '/dev/null'))
133
+ valid = false
134
+ applog(self, :error, "CHROOT directory '#{self.chroot}' does not contain '/dev/null'")
135
+ end
136
+ end
137
+
138
+ valid
139
+ end
140
+
141
+ # DON'T USE THIS INTERNALLY. Use the instance variable. -- Kev
142
+ # No really, trust me. Use the instance variable.
143
+ def pid_file=(value)
144
+ # if value is nil, do the right thing
145
+ if value
146
+ @tracking_pid = false
147
+ else
148
+ @tracking_pid = true
149
+ end
150
+
151
+ @pid_file = value
152
+ end
153
+
154
+ def pid_file
155
+ @pid_file ||= default_pid_file
156
+ end
157
+
158
+ # Fetch the PID from pid_file. If the pid_file does not
159
+ # exist, then use the PID from the last time it was read.
160
+ # If it has never been read, then return nil.
161
+ #
162
+ # Returns Integer(pid) or nil
163
+ def pid
164
+ contents = File.read(self.pid_file).strip rescue ''
165
+ real_pid = contents =~ /^\d+$/ ? contents.to_i : nil
166
+
167
+ if real_pid
168
+ @pid = real_pid
169
+ real_pid
170
+ else
171
+ @pid
172
+ end
173
+ end
174
+
175
+ # Send the given signal to this process.
176
+ #
177
+ # Returns nothing
178
+ def signal(sig)
179
+ sig = sig.to_i if sig.to_i != 0
180
+ applog(self, :info, "#{self.name} sending signal '#{sig}' to pid #{self.pid}")
181
+ ::Process.kill(sig, self.pid) rescue nil
182
+ end
183
+
184
+ def start!
185
+ call_action(:start)
186
+ end
187
+
188
+ def stop!
189
+ call_action(:stop)
190
+ end
191
+
192
+ def restart!
193
+ call_action(:restart)
194
+ end
195
+
196
+ def default_pid_file
197
+ File.join(God.pid_file_directory, "#{self.name}.pid")
198
+ end
199
+
200
+ def call_action(action)
201
+ command = send(action)
202
+
203
+ if action == :stop && command.nil?
204
+ pid = self.pid
205
+ name = self.name
206
+ command = lambda do
207
+ applog(self, :info, "#{self.name} stop: default lambda killer")
208
+
209
+ ::Process.kill(@stop_signal, pid) rescue nil
210
+ applog(self, :info, "#{self.name} sent SIG#{@stop_signal}")
211
+
212
+ # Poll to see if it's dead
213
+ @stop_timeout.times do
214
+ begin
215
+ ::Process.kill(0, pid)
216
+ rescue Errno::ESRCH
217
+ # It died. Good.
218
+ applog(self, :info, "#{self.name} process stopped")
219
+ return
220
+ end
221
+
222
+ sleep 1
223
+ end
224
+
225
+ ::Process.kill('KILL', pid) rescue nil
226
+ applog(self, :warn, "#{self.name} still alive after #{@stop_timeout}s; sent SIGKILL")
227
+ end
228
+ end
229
+
230
+ if command.kind_of?(String)
231
+ pid = nil
232
+
233
+ if [:start, :restart].include?(action) && @tracking_pid
234
+ # double fork god-daemonized processes
235
+ # we don't want to wait for them to finish
236
+ r, w = IO.pipe
237
+ begin
238
+ opid = fork do
239
+ STDOUT.reopen(w)
240
+ r.close
241
+ pid = self.spawn(command)
242
+ puts pid.to_s # send pid back to forker
243
+ end
244
+
245
+ ::Process.waitpid(opid, 0)
246
+ w.close
247
+ pid = r.gets.chomp
248
+ ensure
249
+ # make sure the file descriptors get closed no matter what
250
+ r.close rescue nil
251
+ w.close rescue nil
252
+ end
253
+ else
254
+ # single fork self-daemonizing processes
255
+ # we want to wait for them to finish
256
+ pid = self.spawn(command)
257
+ status = ::Process.waitpid2(pid, 0)
258
+ exit_code = status[1] >> 8
259
+
260
+ if exit_code != 0
261
+ applog(self, :warn, "#{self.name} #{action} command exited with non-zero code = #{exit_code}")
262
+ end
263
+
264
+ ensure_stop if action == :stop
265
+ end
266
+
267
+ if @tracking_pid or (@pid_file.nil? and WRITES_PID.include?(action))
268
+ File.open(default_pid_file, 'w') do |f|
269
+ f.write pid
270
+ end
271
+
272
+ @tracking_pid = true
273
+ @pid_file = default_pid_file
274
+ end
275
+ elsif command.kind_of?(Proc)
276
+ # lambda command
277
+ command.call
278
+ else
279
+ raise NotImplementedError
280
+ end
281
+ end
282
+
283
+ # Fork/exec the given command, returns immediately
284
+ # +command+ is the String containing the shell command
285
+ #
286
+ # Returns nothing
287
+ def spawn(command)
288
+ fork do
289
+ uid_num = Etc.getpwnam(self.uid).uid if self.uid
290
+ gid_num = Etc.getgrnam(self.gid).gid if self.gid
291
+
292
+ ::Dir.chroot(self.chroot) if self.chroot
293
+ ::Process.setsid
294
+ ::Process.groups = [gid_num] if self.gid
295
+ ::Process::Sys.setgid(gid_num) if self.gid
296
+ ::Process::Sys.setuid(uid_num) if self.uid
297
+ self.dir ||= '/'
298
+ Dir.chdir self.dir
299
+ $0 = command
300
+ STDIN.reopen "/dev/null"
301
+ if self.log_cmd
302
+ STDOUT.reopen IO.popen(self.log_cmd, "a")
303
+ else
304
+ STDOUT.reopen file_in_chroot(self.log), "a"
305
+ end
306
+ if err_log_cmd
307
+ STDERR.reopen IO.popen(err_log_cmd, "a")
308
+ elsif err_log && (log_cmd || err_log != log)
309
+ STDERR.reopen file_in_chroot(err_log), "a"
310
+ else
311
+ STDERR.reopen STDOUT
312
+ end
313
+
314
+ # close any other file descriptors
315
+ 3.upto(256){|fd| IO::new(fd).close rescue nil}
316
+
317
+ if self.env && self.env.is_a?(Hash)
318
+ self.env.each do |(key, value)|
319
+ ENV[key] = value
320
+ end
321
+ end
322
+
323
+ exec command unless command.empty?
324
+ end
325
+ end
326
+
327
+ # Ensure that a stop command actually stops the process. Force kill
328
+ # if necessary.
329
+ #
330
+ # Returns nothing
331
+ def ensure_stop
332
+ applog(self, :warn, "#{self.name} ensuring stop...")
333
+
334
+ unless self.pid
335
+ applog(self, :warn, "#{self.name} stop called but pid is uknown")
336
+ return
337
+ end
338
+
339
+ # Poll to see if it's dead
340
+ @stop_timeout.times do
341
+ begin
342
+ ::Process.kill(0, self.pid)
343
+ rescue Errno::ESRCH
344
+ # It died. Good.
345
+ return
346
+ end
347
+
348
+ sleep 1
349
+ end
350
+
351
+ # last resort
352
+ ::Process.kill('KILL', self.pid) rescue nil
353
+ applog(self, :warn, "#{self.name} still alive after #{@stop_timeout}s; sent SIGKILL")
354
+ end
355
+
356
+ private
357
+ def file_in_chroot(file)
358
+ return file unless self.chroot
359
+
360
+ file.gsub(/^#{Regexp.escape(File.expand_path(self.chroot))}/, '')
361
+ end
362
+ end
363
+ end