File: ApplicationPoolServer.h

package info (click to toggle)
passenger 2.2.11debian-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 11,576 kB
  • ctags: 28,138
  • sloc: cpp: 66,323; ruby: 9,646; ansic: 2,425; python: 141; sh: 56; makefile: 29
file content (794 lines) | stat: -rw-r--r-- 24,195 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
/*
 *  Phusion Passenger - http://www.modrails.com/
 *  Copyright (c) 2008, 2009 Phusion
 *
 *  "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */
#ifndef _PASSENGER_APPLICATION_POOL_SERVER_H_
#define _PASSENGER_APPLICATION_POOL_SERVER_H_

#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <oxt/system_calls.hpp>
#include <oxt/backtrace.hpp>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <cstdio>
#include <cstdlib>
#include <limits.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>

#include "MessageChannel.h"
#include "ApplicationPool.h"
#include "Application.h"
#include "Exceptions.h"
#include "Logging.h"

namespace Passenger {

using namespace std;
using namespace boost;
using namespace oxt;


/**
 * Multi-process usage support for ApplicationPool.
 *
 * ApplicationPoolServer implements a client/server architecture for ApplicationPool.
 * This allows one to use ApplicationPool in a multi-process environment (unlike
 * StandardApplicationPool). The cache/pool data is stored in the server. Different
 * processes can then access the pool through the server.
 *
 * ApplicationPoolServer itself does not inherit ApplicationPool. Instead, it returns
 * an ApplicationPool object via the connect() call. For example:
 * @code
 *   // Create an ApplicationPoolServer.
 *   ApplicationPoolServer server(...);
 *   
 *   // Now fork a child process, like Apache's prefork MPM eventually will.
 *   pid_t pid = fork();
 *   if (pid == 0) {
 *       // Child process
 *       
 *       // Connect to the server. After connection, we have an ApplicationPool
 *       // object!
 *       ApplicationPoolPtr pool(server.connect());
 *
 *       // We don't need to connect to the server anymore, so we detach from it.
 *       // This frees up some resources, such as file descriptors.
 *       server.detach();
 *
 *       ApplicationPool::SessionPtr session(pool->get("/home/webapps/foo"));
 *       do_something_with(session);
 *
 *       _exit(0);
 *   } else {
 *       // Parent process
 *       waitpid(pid, NULL, 0);
 *   }
 * @endcode
 *
 * <h2>Implementation notes</h2>
 *
 * <h3>Separate server executable</h3>
 * The actual server is implemented in ApplicationPoolServerExecutable.cpp, this class is
 * just a convenience class for starting/stopping the server executable and connecting
 * to it.
 *
 * In the past, the server logic itself was implemented in this class. This implies that
 * the ApplicationPool server ran inside the Apache process. This presented us with several
 * problems:
 * - Because of the usage of threads in the ApplicationPool server, the Apache VM size would
 *   go way up. This gave people the (wrong) impression that Passenger uses a lot of memory,
 *   or that it leaks memory.
 * - Although it's not entirely confirmed, we suspect that it caused heap fragmentation as
 *   well. Apache allocates lots and lots of small objects on the heap, and ApplicationPool
 *   server isn't exactly helping. This too gave people the (wrong) impression that
 *   Passenger leaks memory.
 * - It would unnecessarily bloat the VM size of Apache worker processes.
 * - We had to resort to all kinds of tricks to make sure that fork()ing a process doesn't
 *   result in file descriptor leaks.
 * - Despite everything, there was still a small chance that file descriptor leaks would
 *   occur, and this could not be fixed. The reason for this is that the Apache control
 *   process may call fork() right after the ApplicationPool server has established a new
 *   connection with a client.
 *
 * Because of these problems, it was decided to split the ApplicationPool server to a
 * separate executable. This comes with no performance hit.
 *
 * <h3>Anonymous server socket</h3>
 * Notice that ApplicationPoolServer does do not use TCP sockets at all, or even named Unix
 * sockets, despite being a server that can handle multiple clients! So ApplicationPoolServer
 * will expose no open ports or temporary Unix socket files. Only child processes are able
 * to use the ApplicationPoolServer.
 *
 * This is implemented through anonymous Unix sockets (<tt>socketpair()</tt>) and file descriptor
 * passing. It allows one to emulate <tt>accept()</tt>. ApplicationPoolServer is connected to
 * the server executable through a Unix socket pair. connect() sends a connect request to the
 * server through that socket. The server will then create a new socket pair, and pass one of
 * them back. This new socket pair represents the newly established connection.
 *
 * @ingroup Support
 */
class ApplicationPoolServer {
private:
	/**
	 * Contains data shared between RemoteSession and Client.
	 * Since RemoteSession and Client have different life times, i.e. one may be
	 * destroyed before the other, they both use a smart pointer that points to
	 * a SharedData. This way, the SharedData object is only destroyed when
	 * both the RemoteSession and the Client object has been destroyed.
	 */
	struct SharedData {
		/**
		 * The socket connection to the ApplicationPool server, as was
		 * established by ApplicationPoolServer::connect().
		 *
		 * The value may be -1, which indicates that the connection has
		 * been closed.
		 */
		int server;
		
		mutable boost::mutex lock;
		
		~SharedData() {
			TRACE_POINT();
			if (server != -1) {
				disconnect();
			}
		}
		
		/**
		 * Disconnect from the ApplicationPool server.
		 */
		void disconnect() {
			TRACE_POINT();
			int ret;
			do {
				ret = close(server);
			} while (ret == -1 && errno == EINTR);
			server = -1;
		}
	};
	
	typedef shared_ptr<SharedData> SharedDataPtr;
	
	/**
	 * An Application::Session which works together with ApplicationPoolServer.
	 */
	class RemoteSession: public Application::Session {
	private:
		SharedDataPtr data;
		int id;
		int fd;
		pid_t pid;
	public:
		RemoteSession(SharedDataPtr data, pid_t pid, int id, int fd) {
			this->data = data;
			this->pid = pid;
			this->id = id;
			this->fd = fd;
		}
		
		virtual ~RemoteSession() {
			closeStream();
			boost::mutex::scoped_lock(data->lock);
			MessageChannel(data->server).write("close", toString(id).c_str(), NULL);
		}
		
		virtual int getStream() const {
			return fd;
		}
		
		virtual void setReaderTimeout(unsigned int msec) {
			MessageChannel(fd).setReadTimeout(msec);
		}
		
		virtual void setWriterTimeout(unsigned int msec) {
			MessageChannel(fd).setWriteTimeout(msec);
		}
		
		virtual void shutdownReader() {
			if (fd != -1) {
				int ret = syscalls::shutdown(fd, SHUT_RD);
				if (ret == -1) {
					throw SystemException("Cannot shutdown the reader stream",
						errno);
				}
			}
		}
		
		virtual void shutdownWriter() {
			if (fd != -1) {
				int ret = syscalls::shutdown(fd, SHUT_WR);
				if (ret == -1) {
					throw SystemException("Cannot shutdown the writer stream",
						errno);
				}
			}
		}
		
		virtual void closeStream() {
			if (fd != -1) {
				int ret = syscalls::close(fd);
				fd = -1;
				if (ret == -1) {
					if (errno == EIO) {
						throw SystemException("A write operation on the session stream failed",
							errno);
					} else {
						throw SystemException("Cannot close the session stream",
							errno);
					}
				}
			}
		}
		
		virtual void discardStream() {
			fd = -1;
		}
		
		virtual pid_t getPid() const {
			return pid;
		}
	};
	
	/**
	 * An ApplicationPool implementation that works together with ApplicationPoolServer.
	 * It doesn't do much by itself, its job is mostly to forward queries/commands to
	 * the server and returning the result. Most of the logic is in the server executable.
	 */
	class Client: public ApplicationPool {
	private:
		// The smart pointer only serves to keep the shared data alive.
		// We access the shared data via a normal pointer, for performance.
		SharedDataPtr dataSmartPointer;
		SharedData *data;
		
	public:
		/**
		 * Create a new Client.
		 *
		 * @param sock The newly established socket connection with the ApplicationPoolServer.
		 */
		Client(int sock) {
			dataSmartPointer = ptr(new SharedData());
			data = dataSmartPointer.get();
			data->server = sock;
		}
		
		virtual bool connected() const {
			boost::mutex::scoped_lock(data->lock);
			return data->server != -1;
		}
		
		virtual void clear() {
			MessageChannel channel(data->server);
			boost::mutex::scoped_lock l(data->lock);
			try {
				channel.write("clear", NULL);
			} catch (...) {
				data->disconnect();
				throw;
			}
		}
		
		virtual void setMaxIdleTime(unsigned int seconds) {
			MessageChannel channel(data->server);
			boost::mutex::scoped_lock l(data->lock);
			try {
				channel.write("setMaxIdleTime", toString(seconds).c_str(), NULL);
			} catch (...) {
				data->disconnect();
				throw;
			}
		}
		
		virtual void setMax(unsigned int max) {
			MessageChannel channel(data->server);
			boost::mutex::scoped_lock l(data->lock);
			try {
				channel.write("setMax", toString(max).c_str(), NULL);
			} catch (...) {
				data->disconnect();
				throw;
			}
		}
		
		virtual unsigned int getActive() const {
			MessageChannel channel(data->server);
			boost::mutex::scoped_lock l(data->lock);
			vector<string> args;
			
			try {
				channel.write("getActive", NULL);
				channel.read(args);
				return atoi(args[0].c_str());
			} catch (...) {
				data->disconnect();
				throw;
			}
		}
		
		virtual unsigned int getCount() const {
			MessageChannel channel(data->server);
			boost::mutex::scoped_lock l(data->lock);
			vector<string> args;
			
			try {
				channel.write("getCount", NULL);
				channel.read(args);
				return atoi(args[0].c_str());
			} catch (...) {
				data->disconnect();
				throw;
			}
		}
		
		virtual void setMaxPerApp(unsigned int max) {
			MessageChannel channel(data->server);
			boost::mutex::scoped_lock l(data->lock);
			try {
				channel.write("setMaxPerApp", toString(max).c_str(), NULL);
			} catch (...) {
				data->disconnect();
				throw;
			}
		}
		
		virtual pid_t getSpawnServerPid() const {
			this_thread::disable_syscall_interruption dsi;
			MessageChannel channel(data->server);
			boost::mutex::scoped_lock l(data->lock);
			vector<string> args;
			
			try {
				channel.write("getSpawnServerPid", NULL);
				channel.read(args);
				return atoi(args[0].c_str());
			} catch (...) {
				data->disconnect();
				throw;
			}
		}
		
		virtual Application::SessionPtr get(const PoolOptions &options) {
			this_thread::disable_syscall_interruption dsi;
			TRACE_POINT();
			
			MessageChannel channel(data->server);
			boost::mutex::scoped_lock l(data->lock);
			vector<string> args;
			int stream;
			bool result;
			bool serverMightNeedEnvironmentVariables = true;
			
			/* Send a 'get' request to the ApplicationPool server.
			 * For efficiency reasons, we do not send the data for
			 * options.environmentVariables over the wire yet until
			 * it's necessary.
			 */
			try {
				vector<string> args;
				
				args.push_back("get");
				options.toVector(args, false);
				channel.write(args);
			} catch (const SystemException &e) {
				UPDATE_TRACE_POINT();
				data->disconnect();
				
				string message("Could not send data to the ApplicationPool server: ");
				message.append(e.brief());
				throw SystemException(message, e.code());
			}
			
			/* The first few replies from the server might be for requesting
			 * environment variables in the pool options object, so keep handling
			 * these requests until we receive a different reply.
			 */
			while (serverMightNeedEnvironmentVariables) {
				try {
					result = channel.read(args);
				} catch (const SystemException &e) {
					UPDATE_TRACE_POINT();
					data->disconnect();
					throw SystemException("Could not read a response from "
						"the ApplicationPool server for the 'get' command", e.code());
				}
				if (!result) {
					UPDATE_TRACE_POINT();
					data->disconnect();
					throw IOException("The ApplicationPool server unexpectedly "
						"closed the connection while we're reading a response "
						"for the 'get' command.");
				}
				
				if (args[0] == "getEnvironmentVariables") {
					try {
						if (options.environmentVariables) {
							UPDATE_TRACE_POINT();
							channel.writeScalar(options.serializeEnvironmentVariables());
						} else {
							UPDATE_TRACE_POINT();
							channel.writeScalar("");
						}
					} catch (const SystemException &e) {
						data->disconnect();
						throw SystemException("Could not send a response "
							"for the 'getEnvironmentVariables' request "
							"to the ApplicationPool server",
							e.code());
					}
				} else {
					serverMightNeedEnvironmentVariables = false;
				}
			}
			
			/* We've now received a reply other than "getEnvironmentVariables".
			 * Handle this...
			 */
			if (args[0] == "ok") {
				UPDATE_TRACE_POINT();
				pid_t pid = (pid_t) atol(args[1]);
				int sessionID = atoi(args[2]);
				
				try {
					stream = channel.readFileDescriptor();
				} catch (...) {
					UPDATE_TRACE_POINT();
					data->disconnect();
					throw;
				}
				
				return ptr(new RemoteSession(dataSmartPointer,
					pid, sessionID, stream));
			} else if (args[0] == "SpawnException") {
				UPDATE_TRACE_POINT();
				if (args[2] == "true") {
					string errorPage;
					
					try {
						result = channel.readScalar(errorPage);
					} catch (...) {
						data->disconnect();
						throw;
					}
					if (!result) {
						throw IOException("The ApplicationPool server "
							"unexpectedly closed the connection while "
							"we're reading the error page data.");
					}
					throw SpawnException(args[1], errorPage);
				} else {
					throw SpawnException(args[1]);
				}
			} else if (args[0] == "BusyException") {
				UPDATE_TRACE_POINT();
				throw BusyException(args[1]);
			} else if (args[0] == "IOException") {
				UPDATE_TRACE_POINT();
				data->disconnect();
				throw IOException(args[1]);
			} else {
				UPDATE_TRACE_POINT();
				data->disconnect();
				throw IOException("The ApplicationPool server returned "
					"an unknown message: " + toString(args));
			}
		}
	};
	
	
	static const int SERVER_SOCKET_FD = 3;
	
	string m_serverExecutable;
	string m_spawnServerCommand;
	string m_logFile;
	string m_rubyCommand;
	string m_user;
	
	/**
	 * The PID of the ApplicationPool server process. If no server process
	 * is running, then <tt>serverPid == 0</tt>.
	 *
	 * @invariant
	 *    if serverPid == 0:
	 *       serverSocket == -1
	 */
	pid_t serverPid;
	
	/**
	 * The connection to the ApplicationPool server process. If no server
	 * process is running, then <tt>serverSocket == -1</tt>.
	 *
	 * @invariant
	 *    if serverPid == 0:
	 *       serverSocket == -1
	 */
	int serverSocket;
	
	/**
	 * Shutdown the currently running ApplicationPool server process.
	 *
	 * @pre System call interruption is disabled.
	 * @pre serverSocket != -1 && serverPid != 0
	 * @post serverSocket == -1 && serverPid == 0
	 */
	void shutdownServer() {
		TRACE_POINT();
		this_thread::disable_syscall_interruption dsi;
		int ret, status;
		time_t begin;
		bool done = false;
		
		syscalls::close(serverSocket);
		
		P_TRACE(2, "Waiting for existing ApplicationPoolServerExecutable (PID " <<
			serverPid << ") to exit...");
		begin = syscalls::time(NULL);
		while (!done && syscalls::time(NULL) < begin + 5) {
			/*
			 * Some Apache modules fork(), but don't close file descriptors.
			 * mod_wsgi is one such example. Because of that, closing serverSocket
			 * won't always cause the ApplicationPool server to exit. So we send it a
			 * signal. This must be the same as the oxt/system_calls.hpp interruption
			 * signal.
			 */
			syscalls::kill(serverPid, oxt::INTERRUPTION_SIGNAL);
			
			ret = syscalls::waitpid(serverPid, &status, WNOHANG);
			done = ret > 0 || ret == -1;
			if (!done) {
				syscalls::usleep(100000);
			}
		}
		if (done) {
			if (ret > 0) {
				if (WIFEXITED(status)) {
					P_TRACE(2, "ApplicationPoolServerExecutable exited with exit status " <<
						WEXITSTATUS(status) << ".");
				} else if (WIFSIGNALED(status)) {
					P_TRACE(2, "ApplicationPoolServerExecutable exited because of signal " <<
						WTERMSIG(status) << ".");
				} else {
					P_TRACE(2, "ApplicationPoolServerExecutable exited for an unknown reason.");
				}
			} else {
				P_TRACE(2, "ApplicationPoolServerExecutable exited.");
			}
		} else {
			P_DEBUG("ApplicationPoolServerExecutable not exited in time. Killing it...");
			syscalls::kill(serverPid, SIGKILL);
			syscalls::waitpid(serverPid, NULL, 0);
		}
		
		serverSocket = -1;
		serverPid = 0;
	}
	
	/**
	 * Start an ApplicationPool server process. If there's already one running,
	 * then the currently running one will be shutdown.
	 *
	 * @pre System call interruption is disabled.
	 * @post serverSocket != -1 && serverPid != 0
	 * @throw SystemException Something went wrong.
	 */
	void restartServer() {
		TRACE_POINT();
		int fds[2];
		pid_t pid;
		
		if (serverPid != 0) {
			shutdownServer();
		}
		
		if (syscalls::socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == -1) {
			throw SystemException("Cannot create a Unix socket pair", errno);
		}
		
		pid = syscalls::fork();
		if (pid == 0) { // Child process.
			dup2(STDERR_FILENO, STDOUT_FILENO);  // Redirect stdout to the same channel as stderr.
			dup2(fds[0], SERVER_SOCKET_FD);
			
			// Close all unnecessary file descriptors
			for (long i = sysconf(_SC_OPEN_MAX) - 1; i > SERVER_SOCKET_FD; i--) {
				close(i);
			}
			
			execlp(
				#if 0
					"valgrind",
					"valgrind",
				#else
					m_serverExecutable.c_str(),
				#endif
				m_serverExecutable.c_str(),
				toString(Passenger::getLogLevel()).c_str(),
				m_spawnServerCommand.c_str(),
				m_logFile.c_str(),
				m_rubyCommand.c_str(),
				m_user.c_str(),
				getPassengerTempDir().c_str(),
				(char *) 0);
			int e = errno;
			fprintf(stderr, "*** Passenger ERROR (%s:%d):\n"
				"Cannot execute %s: %s (%d)\n",
				__FILE__, __LINE__,
				m_serverExecutable.c_str(), strerror(e), e);
			fflush(stderr);
			_exit(1);
		} else if (pid == -1) { // Error.
			syscalls::close(fds[0]);
			syscalls::close(fds[1]);
			throw SystemException("Cannot create a new process", errno);
		} else { // Parent process.
			syscalls::close(fds[0]);
			serverSocket = fds[1];
			
			int flags = fcntl(serverSocket, F_GETFD);
			if (flags != -1) {
				fcntl(serverSocket, F_SETFD, flags | FD_CLOEXEC);
			}
			
			serverPid = pid;
		}
	}

public:
	/**
	 * Create a new ApplicationPoolServer object.
	 *
	 * @param serverExecutable The filename of the ApplicationPool server
	 *            executable to use.
	 * @param spawnServerCommand The filename of the spawn server to use.
	 * @param logFile Specify a log file that the spawn server should use.
	 *            Messages on its standard output and standard error channels
	 *            will be written to this log file. If an empty string is
	 *            specified, no log file will be used, and the spawn server
	 *            will use the same standard output/error channels as the
	 *            current process.
	 * @param rubyCommand The Ruby interpreter's command.
	 * @param user The user that the spawn manager should run as. This
	 *             parameter only has effect if the current process is
	 *             running as root. If the empty string is given, or if
	 *             the <tt>user</tt> is not a valid username, then
	 *             the spawn manager will be run as the current user.
	 * @throws SystemException An error occured while trying to setup the spawn server
	 *            or the server socket.
	 * @throws IOException The specified log file could not be opened.
	 */
	ApplicationPoolServer(const string &serverExecutable,
	             const string &spawnServerCommand,
	             const string &logFile = "",
	             const string &rubyCommand = "ruby",
	             const string &user = "")
	: m_serverExecutable(serverExecutable),
	  m_spawnServerCommand(spawnServerCommand),
	  m_logFile(logFile),
	  m_rubyCommand(rubyCommand),
	  m_user(user) {
		TRACE_POINT();
		serverSocket = -1;
		serverPid = 0;
		this_thread::disable_syscall_interruption dsi;
		restartServer();
	}
	
	~ApplicationPoolServer() {
		TRACE_POINT();
		if (serverSocket != -1) {
			UPDATE_TRACE_POINT();
			this_thread::disable_syscall_interruption dsi;
			shutdownServer();
		}
	}
	
	/**
	 * Connects to the server and returns a usable ApplicationPool object.
	 * All cache/pool data of this ApplicationPool is actually stored on
	 * the server and shared with other clients, but that is totally
	 * transparent to the user of the ApplicationPool object.
	 *
	 * @note
	 *   All methods of the returned ApplicationPool object may throw
	 *   SystemException, IOException or boost::thread_interrupted.
	 *
	 * @warning
	 * One may only use the returned ApplicationPool object for handling
	 * one session at a time. For example, don't do stuff like this:
	 * @code
	 *   ApplicationPoolPtr pool = server.connect();
	 *   Application::SessionPtr session1 = pool->get(...);
	 *   Application::SessionPtr session2 = pool->get(...);
	 * @endcode
	 * Otherwise, a deadlock can occur under certain circumstances.
	 * @warning
	 * Instead, one should call connect() multiple times:
	 * @code
	 *   ApplicationPoolPtr pool1 = server.connect();
	 *   Application::SessionPtr session1 = pool1->get(...);
	 *   
	 *   ApplicationPoolPtr pool2 = server.connect();
	 *   Application::SessionPtr session2 = pool2->get(...);
	 * @endcode
	 *
	 * @throws SystemException Something went wrong.
	 * @throws IOException Something went wrong.
	 */
	ApplicationPoolPtr connect() {
		TRACE_POINT();
		try {
			this_thread::disable_syscall_interruption dsi;
			MessageChannel channel(serverSocket);
			int clientConnection;
			
			// Write some random data to wake up the server.
			channel.writeRaw("x", 1);
			
			clientConnection = channel.readFileDescriptor(false);
			return ptr(new Client(clientConnection));
		} catch (const SystemException &e) {
			throw SystemException("Could not connect to the ApplicationPool server", e.code());
		} catch (const IOException &e) {
			string message("Could not connect to the ApplicationPool server: ");
			message.append(e.what());
			throw IOException(message);
		}
	}
	
	/**
	 * Detach the server, thereby telling it that we don't want to connect
	 * to it anymore. This frees up some resources in the current process,
	 * such as file descriptors.
	 *
	 * This method is particularily useful to Apache worker processes that
	 * have just established a connection with the ApplicationPool server.
	 * Any sessions that are opened prior to calling detach(), will keep
	 * working even after a detach().
	 *
	 * This method may only be called once. The ApplicationPoolServer object
	 * will become unusable once detach() has been called, so call connect()
	 * before calling detach().
	 */
	void detach() {
		TRACE_POINT();
		int ret;
		do {
			ret = close(serverSocket);
		} while (ret == -1 && errno == EINTR);
		serverSocket = -1;
	}
};

typedef shared_ptr<ApplicationPoolServer> ApplicationPoolServerPtr;

} // namespace Passenger

#endif /* _PASSENGER_APPLICATION_POOL_SERVER_H_ */