public
Description: Phusion Passenger (mod_rails)
Homepage: http://www.modrails.com/
Clone URL: git://github.com/FooBarWidget/passenger.git
Click here to lend your support to: passenger and make a donation at www.pledgie.com !
Hongli Lai (Phusion) (author)
Thu May 15 13:34:52 -0700 2008
commit  7a1591fd13112faf256317990740d52e371c9013
tree    29430c1c2795d6fc7b9df96ccc5e8efd3f5164a4
parent  74234781068c109ba523f84c1b48540eb9581499 parent  df976934a3d757ef98abbd8b70ee487097a527b6
passenger / ext / apache2 / ApplicationPoolServerExecutable.cpp
100644 467 lines (405 sloc) 12.19 kb
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
/*
* Phusion Passenger - http://www.modrails.com/
* Copyright (C) 2008 Phusion
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef _PASSENGER_APPLICATION_POOL_SERVER_EXECUTABLE_H_
#define _PASSENGER_APPLICATION_POOL_SERVER_EXECUTABLE_H_
 
/*
* This is the ApplicationPool server executable. See the ApplicationPoolServer
* class for background information.
*
* Each client is handled by a seperate thread. This is necessary because we use
* StandardApplicationPool, and the current algorithm for StandardApplicationPool::get()
* can block (in the case that the spawning limit has been exceeded). While it is
* possible to get around this problem without using threads, a thread-based implementation
* is easier to write.
*/
 
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
 
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#include <signal.h>
#include <string>
#include <vector>
#include <set>
#include <map>
 
#include "MessageChannel.h"
#include "StandardApplicationPool.h"
#include "Application.h"
#include "Logging.h"
#include "Exceptions.h"
 
 
using namespace boost;
using namespace std;
using namespace Passenger;
 
class Server;
class Client;
typedef shared_ptr<Client> ClientPtr;
 
#define SERVER_SOCKET_FD 3
 
/**
* Whether we received a signal indicating that we shut gracefully shutdown.
*/
static bool serverDone = false;
 
 
/*****************************************
* Server
*****************************************/
 
class Server {
private:
  friend class Client;
 
  int serverSocket;
  StandardApplicationPool pool;
  set<ClientPtr> clients;
  mutex lock;
  string statusReportFIFO;
  
  void statusReportThreadMain() {
    while (!serverDone) {
      struct stat buf;
      int ret;
      
      do {
        ret = stat(statusReportFIFO.c_str(), &buf);
      } while (ret == -1 && errno == EINTR);
      if (ret == -1 || !S_ISFIFO(buf.st_mode)) {
        // Something bad happened with the status report
        // FIFO, so we bail out.
        break;
      }
      
      FILE *f;
      
      if (!serverDone) {
        do {
          f = fopen(statusReportFIFO.c_str(), "w");
        } while (f == NULL && errno == EINTR && !serverDone);
      }
      if (f == NULL || serverDone) {
        break;
      }
      
      string report(pool.toString());
      fwrite(report.c_str(), 1, report.size(), f);
      fclose(f);
      
      // Prevent sending too much data at once.
      sleep(1);
    }
  }
  
  void deleteStatusReportFIFO() {
    if (!statusReportFIFO.empty()) {
      int ret;
      do {
        ret = unlink(statusReportFIFO.c_str());
      } while (ret == -1 && errno == EINTR);
    }
  }
 
public:
  Server(int serverSocket,
   const string &spawnServerCommand,
   const string &logFile,
   const string &rubyCommand,
   const string &user,
   const string &statusReportFIFO)
    : pool(spawnServerCommand, logFile, rubyCommand, user) {
    
    this->serverSocket = serverSocket;
    this->statusReportFIFO = statusReportFIFO;
  }
  
  ~Server() {
    int ret;
    do {
      ret = close(serverSocket);
    } while (ret == -1 && errno == EINTR);
    
    // Wait for all clients to disconnect.
    set<ClientPtr> clientsCopy;
    {
      /* If we clear _clients_ directly, then it may result in a deadlock.
       * So we make a copy of the set inside a critical section in order to increase
       * the reference counts, and then we release all references outside the critical
       * section.
       */
      mutex::scoped_lock l(lock);
      clientsCopy = clients;
      clients.clear();
    }
    clientsCopy.clear();
    deleteStatusReportFIFO();
  }
  
  int start(); // Will be defined later, because Client depends on Server's interface.
};
 
 
/*****************************************
* Client
*****************************************/
 
/**
* Represents a single ApplicationPool client, connected to this server.
*
* @invariant
* The life time of a Client object is guaranteed to be less than
* that of its associated Server object.
*/
class Client {
private:
  static const int CLIENT_THREAD_STACK_SIZE = 1024 * 128;
 
  /** The Server that this Client object belongs to. */
  Server &server;
  
  /** The connection to the client. */
  int fd;
  MessageChannel channel;
  
  /** The thread which handles the client connection. */
  thread *thr;
  
  /**
   * Maps session ID to sessions created by ApplicationPool::get(). Session IDs
   * are sent back to the ApplicationPool client. This allows the ApplicationPool
   * client to tell us which of the multiple sessions it wants to close, later on.
   */
  map<int, Application::SessionPtr> sessions;
  
  /** Last used session ID. */
  int lastSessionID;
  
  void processGet(const vector<string> &args) {
    Application::SessionPtr session;
    bool failed = false;
    
    try {
      session = server.pool.get(args[1], args[2] == "true", args[3], args[4], args[5]);
      sessions[lastSessionID] = session;
      lastSessionID++;
    } catch (const SpawnException &e) {
      if (e.hasErrorPage()) {
        P_TRACE(3, "Client " << this << ": SpawnException "
          "occured (with error page)");
        channel.write("SpawnException", e.what(), "true", NULL);
        channel.writeScalar(e.getErrorPage());
      } else {
        P_TRACE(3, "Client " << this << ": SpawnException "
          "occured (no error page)");
        channel.write("SpawnException", e.what(), "false", NULL);
      }
      failed = true;
    } catch (const IOException &e) {
      channel.write("IOException", e.what(), NULL);
      failed = true;
    }
    if (!failed) {
      try {
        channel.write("ok", toString(session->getPid()).c_str(),
          toString(lastSessionID - 1).c_str(), NULL);
        channel.writeFileDescriptor(session->getStream());
        session->closeStream();
      } catch (const exception &) {
        P_TRACE(3, "Client " << this << ": something went wrong "
          "while sending 'ok' back to the client.");
        sessions.erase(lastSessionID - 1);
        throw;
      }
    }
  }
  
  void processClose(const vector<string> &args) {
    sessions.erase(atoi(args[1]));
  }
  
  void processClear(const vector<string> &args) {
    server.pool.clear();
  }
  
  void processSetMaxIdleTime(const vector<string> &args) {
    server.pool.setMaxIdleTime(atoi(args[1]));
  }
  
  void processSetMax(const vector<string> &args) {
    server.pool.setMax(atoi(args[1]));
  }
  
  void processGetActive(const vector<string> &args) {
    channel.write(toString(server.pool.getActive()).c_str(), NULL);
  }
  
  void processGetCount(const vector<string> &args) {
    channel.write(toString(server.pool.getCount()).c_str(), NULL);
  }
  
  void processSetMaxPerApp(unsigned int maxPerApp) {
    server.pool.setMaxPerApp(maxPerApp);
  }
  
  void processGetSpawnServerPid(const vector<string> &args) {
    channel.write(toString(server.pool.getSpawnServerPid()).c_str(), NULL);
  }
  
  void processUnknownMessage(const vector<string> &args) {
    string name;
    if (args.empty()) {
      name = "(null)";
    } else {
      name = args[0];
    }
    P_WARN("An ApplicationPool client sent an invalid command: "
      << name << " (" << args.size() << " elements)");
  }
  
  /**
   * The entry point of the thread that handles the client connection.
   */
  void threadMain(const weak_ptr<Client> self) {
    vector<string> args;
    while (true) {
      try {
        if (!channel.read(args)) {
          // Client closed connection.
          break;
        }
      } catch (const SystemException &e) {
        if (!serverDone) {
          P_WARN("Exception in ApplicationPoolServer client thread during "
            "reading of a message: " << e.what());
        }
        break;
      }
      
      P_TRACE(4, "Client " << this << ": received message: " <<
        toString(args));
      try {
        if (args[0] == "get" && args.size() == 6) {
          processGet(args);
        } else if (args[0] == "close" && args.size() == 2) {
          processClose(args);
        } else if (args[0] == "clear" && args.size() == 1) {
          processClear(args);
        } else if (args[0] == "setMaxIdleTime" && args.size() == 2) {
          processSetMaxIdleTime(args);
        } else if (args[0] == "setMax" && args.size() == 2) {
          processSetMax(args);
        } else if (args[0] == "getActive" && args.size() == 1) {
          processGetActive(args);
        } else if (args[0] == "getCount" && args.size() == 1) {
          processGetCount(args);
        } else if (args[0] == "setMaxPerApp" && args.size() == 2) {
          processSetMaxPerApp(atoi(args[1]));
        } else if (args[0] == "getSpawnServerPid" && args.size() == 1) {
          processGetSpawnServerPid(args);
        } else {
          processUnknownMessage(args);
          break;
        }
      } catch (const exception &e) {
        P_WARN("Uncaught exception in ApplicationPoolServer client thread:\n"
          << " message: " << toString(args) << "\n"
          << " exception: " << e.what());
        break;
      }
    }
    
    mutex::scoped_lock l(server.lock);
    ClientPtr myself(self.lock());
    if (myself != NULL) {
      server.clients.erase(myself);
    }
  }
 
public:
  /**
   * Create a new Client object.
   *
   * @param the_server The Server object that this Client belongs to.
   * @param connection The connection to the ApplicationPool client.
   *
   * @note
   * <tt>connection</tt> will be closed upon destruction
   */
  Client(Server &the_server, int connection)
    : server(the_server),
     fd(connection),
     channel(connection) {
    thr = NULL;
    lastSessionID = 0;
  }
  
  /**
   * Start the thread for handling the connection with this client.
   *
   * @param self The iterator of this Client object inside the server's
   * <tt>clients</tt> set. This is used to remove itself from
   * the <tt>clients</tt> set once the client has closed the
   * connection.
   */
  void start(const weak_ptr<Client> self) {
    thr = new thread(
      bind(&Client::threadMain, this, self),
      CLIENT_THREAD_STACK_SIZE
    );
  }
  
  ~Client() {
    if (thr != NULL) {
      thr->join();
      delete thr;
    }
    close(fd);
  }
};
 
 
static void
gracefulShutdown(int sig) {
  serverDone = true;
}
 
int
Server::start() {
  serverDone = false;
  if (!statusReportFIFO.empty()) {
    thread thr(
      bind(&Server::statusReportThreadMain, this),
      1024 * 128
    );
  }
 
  signal(SIGINT, gracefulShutdown);
  siginterrupt(SIGINT, 1);
  
  while (!serverDone) {
    int fds[2], ret;
    char x;
    
    // The received data only serves to wake up the server socket,
    // and is not important.
    if (!serverDone) {
      do {
        ret = read(serverSocket, &x, 1);
      } while (ret == -1 && errno == EINTR && !serverDone);
    }
    if (ret == 0 || serverDone) {
      // All web server processes disconnected from this server.
      // So we can safely quit.
      break;
    }
    
    // We have an incoming connect request from an
    // ApplicationPool client.
    if (!serverDone) {
      do {
        ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
      } while (ret == -1 && errno == EINTR && !serverDone);
    }
    if (ret == -1 || serverDone) {
      throw SystemException("Cannot create an anonymous Unix socket", errno);
    }
    
    MessageChannel(serverSocket).writeFileDescriptor(fds[1]);
    do {
      ret = close(fds[1]);
    } while (ret == -1 && errno == EINTR);
    
    ClientPtr client(new Client(*this, fds[0]));
    pair<set<ClientPtr>::iterator, bool> p;
    {
      mutex::scoped_lock l(lock);
      clients.insert(client);
    }
    client->start(client);
  }
  if (serverDone) {
    deleteStatusReportFIFO();
    exit(0);
  }
  return 0;
}
 
int
main(int argc, char *argv[]) {
  try {
    Server server(SERVER_SOCKET_FD, argv[1], argv[2], argv[3], argv[4], argv[5]);
    return server.start();
  } catch (const exception &e) {
    fprintf(stderr, "*** An unexpected error occured in the Passenger "
      "ApplicationPool server:\n%s\n",
      e.what());
    fflush(stderr);
    return 1;
  }
}
 
#endif /* _PASSENGER_APPLICATION_POOL_SERVER_EXECUTABLE_H_ */