secobarbital-daemon_controller 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2008 Phusion
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
20
+
@@ -0,0 +1,427 @@
1
+ Introduction
2
+ ============
3
+
4
+ There is a lot of software (both Rails related and unrelated) which rely on
5
+ servers or daemons. To name a few, in no particular order:
6
+
7
+ * [Ultrasphinx](http://blog.evanweaver.com/files/doc/fauna/ultrasphinx/), a
8
+ Rails library for full-text searching. It makes use the [Sphinx search
9
+ software](http://www.sphinxsearch.com/) for indexing and searching. Indexing
10
+ is done by running a command, while searching is done by querying the Sphinx
11
+ search server.
12
+ * [acts_as_ferret](http://projects.jkraemer.net/acts_as_ferret/wiki), another
13
+ Rails library for full-text searching. It uses the Ferret search software.
14
+ On production environments, it relies on the Ferret DRB server for both
15
+ searching and indexing.
16
+ * [BackgrounDRb](http://backgroundrb.rubyforge.org/), a Ruby job server and
17
+ scheduler. Scheduling is done by contacting the BackgrounDRb daemon.
18
+ * [mongrel_cluster](http://mongrel.rubyforge.org/wiki/MongrelCluster), which
19
+ starts and stops multiple Mongrel daemons.
20
+
21
+ Relying on daemons is quite common, but not without problems. Let's go over
22
+ some of them.
23
+
24
+ ### Starting daemons is a hassle
25
+
26
+ If you've used similar software, then you might agree that managing these
27
+ daemons is a hassle. If you're using BackgrounDRb, then the daemon must be
28
+ running. Starting the daemon is not hard, but it is annoying. It's also
29
+ possible that the system administrator forgets to start the daemon. While
30
+ configuring the system to automatically start a daemon at startup is not hard,
31
+ it is an extra thing to do, and thus a hassle. We thought, why can't such
32
+ daemons be automatically started? Indeed, this won't be possible if the daemon
33
+ is to be run on a remote machine. But in by far the majority of use cases, the
34
+ daemon runs on the same host as the Rails application. If a Rails application -
35
+ or indeed, <em>any</em> application - is configured to contact a daemon on the
36
+ local host, then why not start the daemon automatically on demand?
37
+
38
+ ### Daemon starting code may not be robust or efficient
39
+
40
+ We've also observed that people write daemon controlling code over and over
41
+ again. Consider for example UltraSphinx, which provides a
42
+ `rake sphinx:daemon:start` Rake task to start the daemon. The time that a
43
+ daemon needs to initialize is variable, and depends on things such as the
44
+ current system load. The Sphinx daemon usually needs less than a second before
45
+ we can connect to it. However, the way different software handles starting of a
46
+ daemon varies. We've observed that waiting a fixed amount of time is by far the
47
+ most common way. For example, UltraSphinx's daemon starting code looks like
48
+ this:
49
+
50
+ system "searchd --config '#{Ultrasphinx::CONF_PATH}'"
51
+ sleep(4) # give daemon a chance to write the pid file
52
+ if ultrasphinx_daemon_running?
53
+ say "started successfully"
54
+ else
55
+ say "failed to start"
56
+ end
57
+
58
+ This is in no way a slam against UltraSphinx. However, if the daemon starts in
59
+ 200 miliseconds, then the user who issued the start command will be waiting for
60
+ 3.8 seconds for no good reason. This is not good for usability or for the
61
+ user's patience.
62
+
63
+ ### Startup error handling
64
+
65
+ Different software handles daemon startup errors in different ways. Some might
66
+ not even handle errors at all. For example, consider 'mongrel_cluster'. If
67
+ there's a typo in one of your application source files, then 'mongrel_cluster'
68
+ will not report the error. Instead, you have to check its log files to see what
69
+ happened. This is not good for usability: many people will be wondering why
70
+ they can't connect to their Mongrel ports after issuing a
71
+ `mongrel_rails cluster::start` - until they realize that they should read the
72
+ log file. But the thing is, not everybody realizes this. And typing in an extra
73
+ command to read the log file to check whether Mongrel started correctly, is
74
+ just a big hassle. Why can't the daemon startup code report such errors
75
+ immediately?
76
+
77
+ ### Stale or corrupt Pid files
78
+
79
+ Suppose that you're running a Mongrel cluster, and your server suddenly powers
80
+ off because of a power outage. When the server is online again, it fails to
81
+ start your Mongrel cluster because the PID file that it had written still
82
+ exists, and wasn't cleaned up properly (it's supposed to be cleaned up when
83
+ Mongrel exits). mongrel_cluster provides the `--clean` option to check whether
84
+ the PID file is *stale*, and will automatically clean it up if it is. But not
85
+ all daemon controlling software supports this. Why can't all software check for
86
+ stale PID files automatically?
87
+
88
+
89
+ Implementation problems
90
+ =======================
91
+
92
+ From the problem descriptions, it would become apparent that our wishlist is as
93
+ follows. Why is this wishlist often not implemented? Let's go over them.
94
+
95
+ - **A daemon should be automatically started on demand, instead of requiring the user to manually start it.**
96
+
97
+ The most obvious problems are related to concurrency. Suppose that your web
98
+ application has a search box, and you want to start the search daemon if it
99
+ isn't already started, then connect to. Two problems will arise:
100
+
101
+ * Suppose that Rails process A is still starting the daemon. At the same
102
+ time, another visitor tries to search something, and Rails process B
103
+ notices that the daemon is not running. If B tries to start the daemon
104
+ while it's already being started by A, then things can go wrong.
105
+ *A robust daemon starter must ensure that only one process at the same time may start the daemon.*
106
+ * It's not a good idea to wait a fixed amount of time for the daemon to
107
+ start, because you don't know in advance how long it will take for it to
108
+ start. For example, if you wait 2 seconds, then try to connect to the
109
+ daemon, and the daemon isn't done initializing yet, then it will seem as
110
+ if the daemon failed to start.
111
+
112
+ These are the most probable reasons why people don't try to write
113
+ auto-starting code, and instead require the user to start the daemon
114
+ manually.
115
+
116
+ These problems, as well as several less obvious problems, are closely
117
+ related to the next few points.
118
+
119
+ - **The daemon starter must wait until the daemon is done initializing, no longer and no shorter**
120
+
121
+ Because only after the daemon is fully initialized, is it safe to connect
122
+ to it. And because the user should not have to wait longer than he really
123
+ has to. During startup, the daemon will have to be continuously checked
124
+ whether it's done initializing or whether an error occured. Writing this
125
+ code can be quite a hassle, which is why most people don't do it.
126
+
127
+ - **The daemon starter must report any startup errors**
128
+
129
+ If the daemon starting command - e.g. `sphinx -c config_file.conf`,
130
+ `apachectl start` or `mongrel_rails cluster::start` - reports startup
131
+ errors, then all is fine as long as the user is starting the command from a
132
+ terminal. A problem occurs when the error occurs after the daemon has
133
+ already gone into the background. Such errors are only reported to the log
134
+ file.
135
+ *The daemon starter should also check the log file for any startup errors.*
136
+
137
+ Furthermore, it should be able to raise startup errors as exceptions. This
138
+ allows the the application to decide what to do with the error. For less
139
+ experienced system administrators, the error might be displayed in the
140
+ browser, allowing the administrators to become aware of the problem without
141
+ forcing them to manually check the log files. Or the error might be emailed
142
+ to a system administrator's email address.
143
+
144
+ - **The daemon starter must be able to correct stale or corrupted PID files**
145
+
146
+ If the PID file is stale, or for some reason has been corrupted, then the
147
+ daemon starter must be able to cope with that.
148
+ *It should check whether the PID file contains a valid PID, and whether the PID exists.*
149
+
150
+
151
+ Introducing daemon_controller
152
+ =============================
153
+
154
+ *daemon_controller* is a library for managing daemons in a robust manner. It is
155
+ not a tool for managing daemons. Rather, it is a library which lets you write
156
+ applications that manage daemons in a robust manner. For example,
157
+ 'mongrel_cluster' or UltraSphinx may be adapted to utilize this library, for
158
+ more robust daemon management.
159
+
160
+ *daemon_controller* implements all items in the aforementioned wishlist. It
161
+ provides the following functionalities:
162
+
163
+ ### Starting a daemon
164
+
165
+ This ensures that no two processes can start the same daemon at the same time.
166
+ It will also reports any startup errors, even errors that occur after the
167
+ daemon has already gone into the background but before it has fully initialized
168
+ yet. It also allows you to set a timeout, and will try to abort the daemon if
169
+ it takes too long to initialize.
170
+
171
+ The start function won't return until the daemon has been fully initialized,
172
+ and is responding to connections. So if the start function has returned, then
173
+ the daemon is guaranteed to be usable.
174
+
175
+ ### Stopping a daemon
176
+
177
+ It will stop the daemon, but only if it's already running. Any errors
178
+ are reported. If the daemon isn't already running, then it will silently
179
+ succeed. Just like starting a daemon, you can set a timeout for stopping the
180
+ daemon.
181
+
182
+ Like the start function, the stop function won't return until the daemon is no
183
+ longer running. This makes it save to immediately start the same daemon again
184
+ after having stopped it, without worrying that the previous daemon instance
185
+ hasn't exited yet and might conflict with the newly started daemon instance.
186
+
187
+ ### Connecting to a daemon, starting it if it isn't running
188
+
189
+ Every daemon has to be connected to using a different way. As a developer, you
190
+ tell 'daemon_controller' how to connect to the daemon. It will then attempt to
191
+ do that, and if that fails, it will check whether the daemon is running. If it
192
+ isn't running, then it will automatically start the daemon, and attempt to
193
+ connect to the daemon again. Failures are reported.
194
+
195
+ ### Checking whether a daemon is running
196
+
197
+ This information is retrieved from the PID file. It also checks whether the PID
198
+ file is stale.
199
+
200
+ ### All failures are reported via exceptions
201
+
202
+ So that you can exactly determine how you want to handle errors.
203
+
204
+ ### Lots and lots of error checking
205
+
206
+ So that there are very few ways in which the system can screw up.
207
+
208
+ daemon_controller's goal is to make daemon management less of a hassle, and as
209
+ automatic and straightforward as possible.
210
+
211
+
212
+ What about Monit/God?
213
+ =====================
214
+
215
+ daemon_controller is not a replacement for [Monit](http://www.tildeslash.com/monit/)
216
+ or [God](http://god.rubyforge.org/). Rather, it is a solution to the following
217
+ problem:
218
+
219
+ > **Hongli:** hey Ninh, do a 'git pull', I just implemented awesome searching
220
+ > features in our application!
221
+ > **Ninh:** cool. *pulls from repository*
222
+ > **Ninh:** hey Hongli, it doesn't work.
223
+ > **Hongli:** what do you mean, it doesn't work?
224
+ > **Ninh:** it says "connection refused", or something
225
+ > **Hongli:** oh I forgot to mention it, you have to run the Sphinx search
226
+ > daemon before it works. type "rake sphinx:daemon:start" to do
227
+ > that
228
+ > **Ninh:** great. but now I get a different error. something about
229
+ > BackgrounDRb.
230
+ > **Hongli:** oops, I forgot to mention this too. you need to start the
231
+ > BackgrounDRb server with "rake backgroundrb:start_server"
232
+ > **Ninh:** okay, so every time I want to use this app, I have to type
233
+ > "rake sphinx:daemon:start", "rake backgroundrb:start_server" and
234
+ > "./script/server"?
235
+ > **Hongli:** yep
236
+
237
+ Imagine the above conversation becoming just:
238
+
239
+ > **Hongli:** hey Ninh, do a 'git pull', I just implemented awesome searching
240
+ > features in our application!
241
+ > **Ninh:** cool. *pulls from repository*
242
+ > **Ninh:** awesome, it works!
243
+
244
+ This is not something that can be achieved with Monit/God. Monit/God are for
245
+ monitoring daemons, auto-restarting them when they use too much resources.
246
+ daemon_controller's goal is to allow developers to implement daemon
247
+ starting/stopping and daemon auto-starting code that's robust. daemon_controller
248
+ is intended to be used to make daemon-dependent applications Just Work(tm)
249
+ without having to start the daemons manually.
250
+
251
+
252
+ Tutorial #1: controlling Apache
253
+ ===============================
254
+
255
+ Suppose that you're a [Phusion Passenger](http://www.modrails.com/) developer,
256
+ and you need to write tests for the Apache module. In particular, you want to
257
+ test whether the different Phusion Passenger configuration directives are
258
+ working as expected. Obviously, to test the Apache module, the Apache web
259
+ server must be running. For every test, you will want the unit test suite to:
260
+
261
+ 1. Write an Apache configuration file, with the relevant configuration
262
+ directive set to a specific value.
263
+ 2. Start Apache.
264
+ 3. Send an HTTP request to Apache and check whether the HTTP response matches
265
+ your expectations.
266
+ 4. Stop Apache.
267
+
268
+ That can be done with the following code:
269
+
270
+ require 'daemon_controller'
271
+
272
+ File.open("apache.conf", "w") do |f|
273
+ f.write("PidFile apache.pid\n")
274
+ f.write("LogFile apache.log\n")
275
+ f.write("Listen 1234\n")
276
+ f.write(... other relevant configuration options ...)
277
+ end
278
+
279
+ controller = DaemonController.new(
280
+ :identifier => 'Apache web server',
281
+ :start_command => 'apachectl -f apache.conf -k start',
282
+ :ping_command => lambda { TCPSocket.new('localhost', 1234) },
283
+ :pid_file => 'apache.pid',
284
+ :log_file => 'apache.log',
285
+ :timeout => 25
286
+ )
287
+ controller.start
288
+
289
+ .... apache is now started ....
290
+ .... some test code here ....
291
+
292
+ controller.stop
293
+
294
+ The `File.open` line is obvious: it writes the relevant Apache configuration
295
+ file.
296
+
297
+ The next line is for creating a new DaemonController object. We pass a
298
+ human-readable identifier for this daemon ("Apache web server") to the
299
+ constructor. This is used for generating friendlier error messages.
300
+ We also tell it how Apache is supposed to be started (`:start_command`), how to
301
+ check whether it can be connected to (`:ping_command`), and where its PID file
302
+ and log file is. If Apache failed with an error during startup, then it will be
303
+ reported. If Apache failed with an error after it has gone into the background,
304
+ then that will be reported too: the given log file is monitored for new error
305
+ messages.
306
+ Finally, a timeout of 25 seconds is given. If Apache doesn't start within 25
307
+ seconds, then an exception will be raised.
308
+
309
+ The ping command is just a `Proc` which returns true or false. If the Proc
310
+ raises `Errno::ECONNREFUSED`, then that's also interpreted by DaemonController
311
+ as meaning that the daemon isn't responding yet.
312
+
313
+ After `controller.start` has returned, we can continue with the test case. At
314
+ this point, we know that Apache is done with initializing.
315
+ When we're done with Apache, we stop it with `controller.stop`. This does not
316
+ return until Apache has fully stopped.
317
+
318
+ The cautious reader might notice that the socket returned by the ping command
319
+ is never closed. That's true, because DaemonController will close it
320
+ automatically for us, if it notices that the ping command proc's return value
321
+ responds to `#close`.
322
+
323
+ From this example, it becomes apparent that for daemon_controller to work, you
324
+ must know how to start the daemon, how to contact the daemon, and you must know
325
+ where it will put its PID file and log file.
326
+
327
+
328
+ Tutorial #2: Sphinx indexing and search server management
329
+ =========================================================
330
+
331
+ We at Phusion are currently developing a web application with full-text search
332
+ capabilities, and we're using Sphinx for this purpose. We want to make the
333
+ lives of our developers and our system administrators as easy as possible, so
334
+ that there's little room for human screw-up, and so we've developed this
335
+ library. Our Sphinx search daemon is completely managed through this library
336
+ and is automatically started on demand.
337
+
338
+ Our Sphinx config file is generated from an ERB template. This ERB template
339
+ writes different values in the config file, depending on whether we're in
340
+ development, test or production mode. We will want to regenerate this config
341
+ file every time, just before we start the search daemon.
342
+ But there's more. The search daemon will fail if there is no search index. If a
343
+ new developer has just checked out the application's source code, then there is
344
+ no search index yet. We don't want him to go through the pain of having to
345
+ generate the index manually. (That said, it isn't that much of a pain, but it's
346
+ just yet-another-thing to do, which can and should be automated.) So before
347
+ starting the daemon, we will also want to check whether the index exists. If
348
+ not, then we'll generate it, and then start the daemon. Of course, no two Rails
349
+ processes may generate the config file or the index at the same time.
350
+
351
+ When querying the search server, we will want to automatically start it if it
352
+ isn't running.
353
+
354
+ This can be achieved with the following code:
355
+
356
+ require 'daemon_controller'
357
+
358
+ class SearchServer
359
+ SEARCH_SERVER_PORT = 1234
360
+
361
+ def initialize
362
+ @controller = DaemonController.new(
363
+ :identifier => 'Sphinx search server',
364
+ :start_command => "searchd -c config/sphinx.conf",
365
+ :before_start => method(:before_start),
366
+ :ping_command => lambda { TCPSocket.new('localhost', SEARCH_SERVER_PORT) },
367
+ :pid_file => 'tmp/pids/sphinx.pid',
368
+ :log_file => 'log/sphinx.log')
369
+ end
370
+
371
+ def query(search_terms)
372
+ socket = @controller.connect do
373
+ TCPSocket.new('localhost', SEARCH_SERVER_PORT)
374
+ end
375
+ send_query(socket, search_terms)
376
+ return retrieve_results(socket)
377
+ end
378
+
379
+ private
380
+ def before_start
381
+ generate_configuration_file
382
+ if !index_exists?
383
+ generate_index
384
+ end
385
+ end
386
+
387
+ ...
388
+ end
389
+
390
+ Notice the `:before_start` option. We pass a block of code which is to be run,
391
+ just before the daemon is started. This block, along with starting the daemon,
392
+ is completely serialized. That is, if you're inside the block, then it's
393
+ guaranteed that no other process is running this block at the same time as well.
394
+
395
+ The `#query` method is the method for querying the search server with search
396
+ terms. It returns a list of result. It uses `DaemonController#connect`: one
397
+ passes a block of that method, which contains code for connecting to the
398
+ daemon. If the block returns nil, or if it raises `Errno::ECONNREFUSED`, then
399
+ `DaemonController#connect` will automatically take care of auto-starting the
400
+ Sphinx daemon for us.
401
+
402
+
403
+ A little bit of history
404
+ =======================
405
+
406
+ The issue of managing daemons has been a thorn in our eyes for quite some time
407
+ now. Until now, we've solved this problem by equipping any daemons that we
408
+ write with the ability to gracefully handle being concurrently started, the
409
+ ability to initialize as much as possible *before* forking into the background,
410
+ etc. However, equipping all this robustness into our code over and over is a
411
+ lot of work. We've considered documenting a standard behavior for daemons so
412
+ that they can properly support auto-starting and such.
413
+
414
+ However, we've recently realized that that's probably a futile effort.
415
+ Convincing everybody to write a lot of code for a bit more robustness is
416
+ probably not realistic. So we took the pragmatic approach and developed a
417
+ library which adds more robustness on top of daemons' existing behavior. And
418
+ thus, daemon_controller was born. It is a little bit less efficient compared to
419
+ when the daemon is designed from the beginning with such abilities in mind, but
420
+ it's compatible with virtually all daemons, and is easy to use.
421
+
422
+
423
+ API documentation
424
+ =================
425
+
426
+ Detailed API documentation is available in the form of inline comments in
427
+ `lib/daemon_controller.rb`.
@@ -0,0 +1,19 @@
1
+ Gem::Specification.new do |s|
2
+ s.name = "daemon_controller"
3
+ s.version = "0.2.0"
4
+ s.date = "2009-01-26"
5
+ s.summary = "A library for implementing daemon management capabilities"
6
+ s.email = "hongli@phusion.nl"
7
+ s.homepage = "http://github.com/FooBarWidget/daemon_controller/tree/master"
8
+ s.description = "A library for robust daemon management."
9
+ s.has_rdoc = true
10
+ s.authors = ["Hongli Lai"]
11
+
12
+ s.files = [
13
+ "README.markdown", "LICENSE.txt", "daemon_controller.gemspec",
14
+ "lib/daemon_controller.rb",
15
+ "lib/daemon_controller/lock_file.rb",
16
+ "spec/daemon_controller_spec.rb",
17
+ "spec/echo_server.rb"
18
+ ]
19
+ end