forked from php-pm/php-pm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ProcessSlave.php
551 lines (464 loc) · 16.2 KB
/
ProcessSlave.php
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
<?php
declare(ticks = 1);
namespace PHPPM;
use PHPPM\React\HttpResponse;
use PHPPM\React\HttpServer;
use React\Socket\Connection;
use Symfony\Component\Debug\BufferingLogger;
use Symfony\Component\Debug\ErrorHandler;
class ProcessSlave
{
use ProcessCommunicationTrait;
/**
* Current instance, used by global functions.
*
* @var ProcessSlave
*/
public static $slave;
/**
* The HTTP Server.
*
* @var React\Server
*/
protected $server;
/**
* @var \React\EventLoop\LibEventLoop|\React\EventLoop\StreamSelectLoop
*/
protected $loop;
/**
* Connection to ProcessManager, master process.
*
* @var \React\Socket\Connection
*/
protected $controller;
/**
* @var string
*/
protected $bridgeName;
/**
* @var Bridges\BridgeInterface
*/
protected $bridge;
/**
* @var string
*/
protected $appBootstrap;
/**
* @var string[]
*/
protected $watchedFiles = [];
/**
* Contains the cached version of last sent files, for performance reasons
*
* @var array|null
*/
protected $lastSentFiles;
/**
* @var bool
*/
protected $inShutdown = false;
/**
* @var BufferingLogger
*/
protected $errorLogger;
protected $logFormat = '[$time_local] $remote_addr - $remote_user "$request" $status $bytes_sent "$http_referer"';
/**
* Contains some configuration options.
*
* 'port' => int (server port)
* 'appenv' => string (App environment)
* 'static' => boolean (true) (If it should server static files)
* 'logging' => boolean (false) (If it should log all requests)
* ...
*
* @var array
*/
protected $config;
public function __construct($bridgeName = null, $appBootstrap, array $config = [])
{
gc_disable();
$this->config = $config;
$this->appBootstrap = $appBootstrap;
$this->bridgeName = $bridgeName;
if ($this->config['session_path']) {
session_save_path($this->config['session_path']);
}
}
/**
* @return boolean
*/
public function isDebug()
{
return $this->config['debug'];
}
/**
* @return boolean
*/
public function isLogging()
{
return $this->config['logging'];
}
/**
* Shuts down the event loop. This basically exits the process.
*/
public function shutdown()
{
if ($this->inShutdown) {
return;
}
if ($this->errorLogger && $logs = $this->errorLogger->cleanLogs()) {
$messages = array_map(
function ($item) {
//array($level, $message, $context);
$message = $item[1];
$context = $item[2];
if (isset($context['file'])) {
$message .= ' in ' . $context['file'] . ':' . $context['line'];
}
if (isset($context['stack'])) {
foreach ($context['stack'] as $idx => $stack) {
$message .= PHP_EOL . sprintf(
"#%d: %s%s %s%s",
$idx,
isset($stack['class']) ? $stack['class'] . '->' : '',
$stack['function'],
isset ($stack['file']) ? 'in' . $stack['file'] : '',
isset($stack['line']) ? ':' . $stack['line'] : ''
);
}
}
return $message;
},
$logs
);
error_log(implode(PHP_EOL, $messages));
}
$this->inShutdown = true;
if ($this->loop) {
$this->sendCurrentFiles();
$this->loop->tick();
}
if ($this->controller && $this->controller->isWritable()) {
$this->controller->close();
}
if ($this->server) {
@$this->server->shutdown();
}
if ($this->loop) {
$this->sendCurrentFiles();
$this->loop->tick();
@$this->loop->stop();
}
exit;
}
/**
* @return boolean
*/
protected function isServingStatic()
{
return $this->config['static'];
}
/**
* @return Bridges\BridgeInterface
*/
protected function getBridge()
{
if (null === $this->bridge && $this->bridgeName) {
if (true === class_exists($this->bridgeName)) {
$bridgeClass = $this->bridgeName;
} else {
$bridgeClass = sprintf('PHPPM\Bridges\\%s', ucfirst($this->bridgeName));
}
$this->bridge = new $bridgeClass;
}
return $this->bridge;
}
/**
* Bootstraps the actual application.
*
* @param string $appBootstrap
* @param string $appenv
* @param boolean $debug
*
* @throws \Exception
*/
protected function bootstrap($appBootstrap, $appenv, $debug)
{
if ($bridge = $this->getBridge()) {
$bridge->bootstrap($appBootstrap, $appenv, $debug);
$this->sendMessage($this->controller, 'ready');
}
}
/**
* Adds a file path to the watcher list queue which will be sent
* to the master process after each request.
*
* @param string $path
*/
public function registerFile($path)
{
$this->watchedFiles[] = $path;
}
/**
* Sends to the master a snapshot of current known php files, so it can track those files and restart
* slaves if necessary.
*/
protected function sendCurrentFiles()
{
$files = array_merge($this->watchedFiles, get_included_files());
$flipped = array_flip($files);
//speedy way checking if two arrays are different.
if (!$this->lastSentFiles || array_diff_key($flipped, $this->lastSentFiles)) {
$this->lastSentFiles = $flipped;
$this->sendMessage($this->controller, 'files', ['files' => $files]);
}
$this->watchedFiles = [];
}
/**
* Connects to ProcessManager, master process.
*/
public function run()
{
$this->loop = \React\EventLoop\Factory::create();
$this->errorLogger = new BufferingLogger();
ErrorHandler::register(new ErrorHandler($this->errorLogger));
$client = stream_socket_client($this->config['controllerHost']);
$this->controller = new \React\Socket\Connection($client, $this->loop);
$this->controller->on('error', function ($data) {
var_dump($data);
});
$pcntl = new \MKraemer\ReactPCNTL\PCNTL($this->loop);
$pcntl->on(SIGTERM, [$this, 'shutdown']);
$pcntl->on(SIGINT, [$this, 'shutdown']);
register_shutdown_function([$this, 'shutdown']);
$this->bindProcessMessage($this->controller);
$this->controller->on(
'close',
\Closure::bind(
function () {
$this->shutdown();
},
$this
)
);
$this->server = new React\Server($this->loop); //our version for now, because of unix socket support
$this->server->on('error', function ($data) {
var_dump($data);
});
$http = new HttpServer($this->server);
$http->on('request', array($this, 'onRequest'));
$http->on('error', function ($data) {
var_dump($data);
});
$port = $this->config['port'];
$host = $this->config['host'];
while (true) {
try {
$this->server->listen($port, $host);
break;
} catch (\React\Socket\ConnectionException $e) {
usleep(500);
}
}
$this->sendMessage($this->controller, 'register', ['pid' => getmypid(), 'port' => $port]);
$this->loop->run();
}
public function commandBootstrap(array $data, Connection $conn)
{
$this->bootstrap($this->appBootstrap, $this->config['app-env'], $this->isDebug());
if ($this->isDebug()) {
$this->sendCurrentFiles();
}
}
/**
* Handles incoming requests and transforms a $request into a $response by reference.
*
* @param \React\Http\Request $request
* @param HttpResponse $response
*
* @throws \Exception
*/
public function onRequest(\React\Http\Request $request, HttpResponse $response)
{
$this->prepareEnvironment($request);
if ($this->isLogging()) {
$this->setupResponseLogging($request, $response);
}
$this->handleRequest($request, $response);
if (memory_get_usage() > Utils::getMaxMemory() * 0.8) {
//80% of allowed memory used, so let's call the garbage collector.
gc_collect_cycles();
}
}
protected function handleRequest(\React\Http\Request $request, HttpResponse $response)
{
if ($bridge = $this->getBridge()) {
if ($this->isServingStatic()) {
if (true === $this->serveStatic($request, $response)) {
return;
}
}
$bridge->onRequest($request, $response);
if ($this->isDebug()) {
$this->sendCurrentFiles();
}
} else {
$response->writeHead('404');
$response->end('No Bridge Defined.');
}
if (headers_sent()) {
//when a script sent headers the cgi process needs to die because the second request
//trying to send headers again will fail (headers already sent fatal). Its best to not even
//try to send headers because this break the whole of approach of php-pm using php-cgi.
error_log(
'Headers has been sent, but not redirected to client. Force restart of a worker. ' .
'Make sure your application does not send headers on its own.'
);
$this->shutdown();
}
}
protected function prepareEnvironment(\React\Http\Request $request)
{
$_SERVER['REQUEST_METHOD'] = $request->getMethod();
$_SERVER['REQUEST_TIME'] = (int)microtime(true);
$_SERVER['REQUEST_TIME_FLOAT'] = microtime(true);
$_SERVER['QUERY_STRING'] = http_build_query($request->getQuery());
foreach ($request->getHeaders() as $name => $value) {
$_SERVER['HTTP_' . strtoupper(str_replace('-', '_', $name))] = $value;
}
//We receive X-PHP-PM-Remote-IP from ProcessManager.
//This header is only used to proxy the remoteAddress from master -> slave.
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_PHP_PM_REMOTE_IP'];
unset($_SERVER['HTTP_X_PHP_PM_REMOTE_IP']);
$_SERVER['SERVER_NAME'] = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
$_SERVER['REQUEST_URI'] = $request->getPath();
$_SERVER['DOCUMENT_ROOT'] = isset($_ENV['DOCUMENT_ROOT']) ? $_ENV['DOCUMENT_ROOT'] : getcwd();
$_SERVER['SCRIPT_NAME'] = isset($_ENV['SCRIPT_NAME']) ? $_ENV['SCRIPT_NAME'] : 'index.php';
$_SERVER['SCRIPT_FILENAME'] = $_SERVER['DOCUMENT_ROOT'] . $_SERVER['SCRIPT_NAME'];
}
/**
* @param \React\Http\Request $request
* @param HttpResponse $response
*
* @return bool returns true if successfully served
*/
protected function serveStatic(\React\Http\Request $request, HttpResponse $response)
{
$filePath = $this->getBridge()->getStaticDirectory() . $request->getPath();
if (substr($filePath, -4) !== '.php' && is_file($filePath)) {
$response->writeHead(200, [
'Content-Type' => $this->mimeContentType($filePath),
'Content-Length' => filesize($filePath),
]);
$response->end(file_get_contents($filePath));
return true;
}
return false;
}
protected function setupResponseLogging(\React\Http\Request $request, HttpResponse $response)
{
$timeLocal = date('d/M/Y:H:i:s O');
$response->on('end', function () use ($request, $response, $timeLocal) {
$requestString = $request->getMethod() . ' ' . $request->getPath() . ' HTTP/' . $request->getHttpVersion();
$statusCode = $response->getStatusCode();
if ($response->getStatusCode() < 400) {
$requestString = "<info>$requestString</info>";
$statusCode = "<info>$statusCode</info>";
}
$message = str_replace([
'$remote_addr',
'$remote_user',
'$time_local',
'$request',
'$status',
'$bytes_sent',
'$http_referer',
'$http_user_agent',
], [
$_SERVER['REMOTE_ADDR'],
'-', //todo remote_user
$timeLocal,
$requestString,
$statusCode,
$response->getBytesSent(),
isset($request->getHeaders()['Referer']) ? $request->getHeaders()['Referer'] : '-',
isset($request->getHeaders()['User-Agent']) ? $request->getHeaders()['User-Agent'] : '-',
],
$this->logFormat);
if ($response->getStatusCode() >= 400) {
$message = "<error>$message</error>";
}
$this->sendMessage($this->controller, 'log', ['message' => $message]);
});
}
/**
* @param string $filename
*
* @return string
*/
protected function mimeContentType($filename)
{
$mimeTypes = array(
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'ts' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
);
$ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
if (isset($mimeTypes[$ext])) {
return $mimeTypes[$ext];
} elseif (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
//we need to suppress all stuff of this call due to https://bugs.php.net/bug.php?id=71615
$mimetype = @finfo_file($finfo, $filename);
finfo_close($finfo);
if ($mimetype) {
return $mimetype;
}
}
return 'application/octet-stream';
}
}